How to build a form for nested models? - django-models

I am building an app in Django 1.9 with the models Customers and Addresses:
class Customers(models.Model):
name = models.CharField(db_column='NAME', max_length=400)
email = models.CharField(db_column='EMAIL', max_length=255, unique=True)
phone_number = models.CharField(db_column='PHONE_NUMBER', max_length=200, blank=True, null=True)
address = models.ForeignKey(Addresses, db_column='ADDRESS_ID', related_name='customer_address', null=True)
class Addresses(models.Model):
street = models.TextField(db_column='STREET', max_length=2000)
city = models.CharField(db_column='CITY', max_length=400, blank=True, null=True)
postal_code = models.CharField(db_column='POSTAL_CODE', max_length=200, blank=True, null=True)
country = models.ForeignKey(Country, db_column='COUNTRY_ID', null=True)
I am new in Django, so please forgive me if this has too much mistakes.
I want to create a new Customer using a form:
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
phone_number = forms.IntegerField(label=_(u'Phone Number'), required=False, widget=TextInput(attrs={'style': 'width:80px'}))
But I still want to be able to add the address. I read some stuff about nested forms, but I didn't understand.
Could you, please, help in building a form that creates a Customer with name, email, phone_number and address?

I figured it out! :)
You have to override the save method of the form.
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
a_street = forms.CharField(label=_(u'Street'), widget=TextInput(), required=False)
a_postal_code = forms.CharField(label=_(u'Postal Code'), widget=TextInput(), required=False)
a_city = forms.CharField(label=_(u'City'), widget=TextInput(), required=False)
a_country = forms.CharField(label=_(u'Country'), widget=TextInput(), required=False)
# Override the save method like this
def save(self, commit=True):
c = super(CustomersForm, self).save(commit=False)
# Address
if c.address:
a = c.address
else:
a = Addresses()
a.street = self.cleaned_data.get('a_street')
a.city = self.cleaned_data.get('a_city')
a.postal_code = self.cleaned_data.get('a_postal_code')
a.country = self.cleaned_data.get('a_country')
if commit:
a.save()
c.address = a
c.save()
return c

Related

Updating a profile image in django

so I have this issue when trying to update a profile photo in django.
The Profile photo actually updates if I upload an image. But there are cases where a user may want to update other details on the profile update page without having to update the profile photo.
Trying to implement that gave me a multivalue error.
I've been on it for some time now, Please, who knows how I can handle that.
Here's my code on views.py file
def profile_update(request, user_id):
if request.method == 'POST':
user_obj = User.objects.get(id=user_id)
user_profile_obj = UserProfile.objects.get(user=user_id)
user_img = request.FILES['user_img']
username = request.POST["username"]
email = request.POST["email"]
phone = request.POST["phone"]
address = request.POST["address"]
fs_handle = FileSystemStorage()
img_name = 'uploads/profile_pictures/user_{0}'.format(user_id)
if fs_handle.exists(img_name):
fs_handle.delete(img_name)
fs_handle.save(img_name, user_img)
user_profile_obj.profile_pic = img_name
user_profile_obj.phone = phone
user_profile_obj.address = address
user_profile_obj.save()
user_obj.username = username
user_obj.email = email
user_obj.save()
user_obj.refresh_from_db()
Here's my models.py file
`
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
address = models.CharField(max_length=65, null=True, blank=True)
phone = models.CharField(max_length=65, null=True, blank=True)
profile_pic = models.FileField(null=True, blank=True, upload_to="uploads/profile_pictures", validators = [FileExtensionValidator(allowed_extensions=['jpg','jpeg','png'])])
def __str__(self):
return str(self.user)
`

Creating a simple messaging function (NOT REAL TIME) using Django

Please I'm trying to implement a SIMPLE messaging function (NOT A REAL TIME CHAT)
But I keep getting this error message I understand what it says or mean but I'm not sure why I am unable to establish this relationship
Please I need help to alternative if I can't do things this way
This is my profile(Engineer) models
class Engineer(AbstractUser):
username = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, null=True)
bio = models.TextField()
avatar = models.ImageField(default="profile.png")
country = models.CharField(max_length=200)
years_of_experience = models.PositiveIntegerField(null=True, blank=True)
tech_stack = models.CharField(null=True, blank=True, max_length=300)
inbox = models.ForeignKey(Inbox, null=True, on_delete=models.CASCADE)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.username
and this is my Inbox models
class Inbox(models.Model):
sender = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name="mail_receiver")
message = models.CharField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.sender.username
Just make the Engineer import as follows
sender = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name="mail_receiver")

How can I use an if condition in model.py Django?

I would like if a student studies "Computer Science", for example, that in the "Categories" class he can only select certain "Categories". Unfortunately I get the following error:
ERRORS:
accounds.Categories.members: (fields.E305) Reverse query name for 'accounds.Categories.members' clashes with reverse query name for 'accounds.Categories.members_ptr'.
HINT: Add or change a related_name argument to the definition for 'accounds.Categories.members' or 'accounds.Categories.members_ptr'.
from django.db import models
from datetime import date
# Create your models here.
class Members(models.Model):
created_at = models.DateField(default=date.today, null=True)
vorname = models.CharField(max_length=200, null=True)
nachname = models.CharField(max_length=200, null=True)
Studiengang = (("IT & Technik","IT & Technik") ,("Designs & Medie", "Designs & Medie"),
("Personal & Recht","Personal & Recht"), ("Informatik","Informatik"))
studiengang = models.CharField(max_length=200, null=True, choices=Studiengang)
email = models.CharField(max_length=200, null=True)
passwort = models.CharField(max_length=200, null=True)
def __str__(self):
return self.vorname
class Categories(Members):
if Members.studiengang == "Informatik":
Kategorien = (
("Mathematik Grundlagen I", "Mathematik Grundlagen I"),
("Grundlagen der industriellen Softwaretechnik", "Grundlagen der industriellen
Softwaretechnik"),
)
kategorien = models.CharField(max_length=200, null=True, choices=Kategorien)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
class Statistik(models.Model):
fragen_insgesammt = models.IntegerField(null=True)
fragen_richtig_beantwortet = models.IntegerField(null=True)
fragen_falsch_beantwortet = models.IntegerField(null=True)
anzahl_der_punkte = models.IntegerField(null=True)
student = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
I would be super happy if someone could help
in Categories Model > members ForeignKey add argument (related_name)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL,related_name="members_list")

Please explain the _set.all() method in django>

I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;

anyone can tell me about invalid literal for int() with base 10: 'nokia'

Here below is my model and form class:
class BOQ(models.Model):
boq_amount =models.CharField(max_length=256)
boq_date = models.DateTimeField(default=datetime.datetime.now, blank=True)
boq_ver = models.CharField(max_length=256)
po_number = models.CharField(max_length=256)
po_date = models.DateTimeField(default=datetime.datetime.now, blank=True)
po_type = models.CharField(max_length=256)
po_amount = models.CharField(max_length=256)
inv_amount =models.CharField(max_length=256)
inv_number = models.CharField(max_length=256)
inv_date = models.DateTimeField(default=datetime.datetime.now, blank=True)
site_accepted_date = models.DateTimeField(default=datetime.datetime.now, blank=True)
pac_date = models.DateTimeField(default=datetime.datetime.now, blank=True)
comments= models.TextField()
client_data = models.ForeignKey(Customer, null=True)
def __str__(self):
return self.comments
class BOQForm(forms.ModelForm):
class Meta:
model = BOQ
exclude = ('', 'client_data')
fields = ('boq_amount', 'boq_date', 'boq_ver', 'po_number', 'po_date', 'po_type', 'po_amount', 'inv_amount','inv_number', 'inv_date', 'site_accepted_date', 'pac_date', 'comments')
The problem is that when i fill the form and submit it,the data is saved into database when go to django administration pannel and click on same record it will give the error:
invalid literal for int() with base 10: 'nokia'
see this picture showing error output
please anyone suggest me solution as early as possible for this who have resolve this kind of problem,i'm very thankfull to you if please..

Resources