开发者

Values in Many-to-Many field not getting selected when editing an object in a custom(Non-admin) Django view

开发者 https://www.devze.com 2023-04-03 10:03 出处:网络
We have a django-model containing a many-to-many field. We use the same form to add/edit objects. When an existing object is loaded for editing all fields have values associated with them except the M

We have a django-model containing a many-to-many field. We use the same form to add/edit objects. When an existing object is loaded for editing all fields have values associated with them except the Many-to-Many field(None of the options is the MultipleSelectBox Widget are selected)

Is there any speci开发者_如何学编程al way to bind values to Many-to-Many field so that the the current values of the field appear selected in the MultipleSelectBox Widget when the form loads the object for editing.

I tried reading up similar questions put up by users on SO, but couldn't find the answer to my query :(.


Had the same problem, and it was caused by commit=False. The way to fix it is with save_m2m()

# Create a form instance with POST data.
f = AuthorForm(request.POST)
# Create, but don't save the new author instance.
new_author = f.save(commit=False)
# Modify the author in some way.
new_author.some_field = 'some_value'
# Save the new instance.
new_author.save()
# Now, save the many-to-many data for the form.
f.save_m2m()


Try To Do This! This Is My Example To Show You How Can You Do It :D

class FirstModel(models.Model):
    title = models.CharField(max_length = 100, unique = True)

class SecondModel(models.Model):
    name = models.CharField(max_length = 100, unique = True)
    first_model = models.ManyToManyField(FirstModel)

class MyForm(forms.Form):
    name = forms.CharField(max_length = 100, required = True)
    first_model = forms.ChoiceField(widget = forms.MultipleSelect)

After You save It In Your add Function, Then To Edit It In edit Function, Do This:

def edit(request):
    my_model = MyModel.objects.filter(name = 'You Unique Name').get()
    first_model = my_model.first_model.all()
    my_form = MyForm(initial = {'first_model': first_model})

That's It :D

0

精彩评论

暂无评论...
验证码 换一张
取 消