The problem with the code is that the form is sucessfully getting passed but the model is not saving the many to many field in the Profile models. All the values are getting saved except the food and type. Please help me with the code. Model
class Relationship(models.Model):
status = models.CharField(max_length =30)
def __str__(self):
return self.status
class Food(models.Model):
food_name = models.CharField(max_length = 80)
def __str__(self):
return self.food_name
class City(models.Model):
city = models.CharField(max_length = 80)
def __str__(self):
return self.city
class Type(models.Model):
types = models.CharField(max_length =80)
def __str__(self):
return self.types
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
avatar = models.ImageField(upload_to = image_upload_to)
city = models.OneToOneField(City)
fav_food = models.ManyToManyField(Food)
relationship = models.OneToOneField(Relationship)
preferrs = models.ManyToManyField(Type)
def get_absolute_url(self):
return reverse('chatbot')
def __str__(self):
return self.user.get_username()
`
And my Model form is as follow
class ProfileForm(ModelForm):
class Meta:
model=Profile
fields = ['avatar','city','fav_food','relationship','preferrs']
and my view is as follow
def ProfileCreate(request):
template="profile.html"
context={}
if request.user.get_username()=='':
return redirect('account_login')
if Profile.objects.all().filter(user__username=request.user.get_username()).count()>0:
return redirect('chatbot')
else:
form = ProfileForm(request.POST ,request.FILES or None)
if form.is_valid():
new_profile = form.save(commit=False)
user = User.objects.all().filter(username=request.user.get_username())[0]
new_profile.user=user
new_profile.save()
return redirect('chatbot')
context['form']=form
return render(request,template,context)
Since you are saving the form with commit=False
, you must call the form's save_m2m
method after saving the instance.
new_profile = form.save(commit=False)
# no need to fetch the user here, just use request.user
new_profile.user = request.user
new_profile.save()
form.save_m2m()
See the docs on the model form save method for more info.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments