[Fixed]-How to save choices value in django ?

1👍

It seems like you need to convert your model. If you could provide a sample of the structure that you are using it would be helpful. Still lets try solving your query. First you need identify that choices is nothing more than a many to many field. Saving it in the db should be a bit easier that way. Lets try taking an example with choices for a user:

class Choices(models.Model):
  description = models.CharField(max_length=100)

class UserProfile(models.Model):
  user = models.ForeignKey(User, blank=True, unique=True, verbose_name='profile_user')
  choices = models.ManyToManyField(Choices)
  def __unicode__(self):
    return self.name

Now if you want to make a default form you could simply do something like:

class ProfileForm(forms.ModelForm):
  Meta:
    model = UserProfile

Now comes your main view. This can be editted and rendered to whatever your use case demands it to be:

if request.method=='POST':
  form = ProfileForm(request.POST)
  if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    #Implement this as a pre-save so that you can add additional value
    profile.save()
else:
  form = ProfileForm()

Hope this helps.

Leave a comment