Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

Update ManyToManyField in Django from form data

I am passing form like this:

guest = get_object_or_404(Guest, id=guest_id)
data = {'full_name': guest.full_name, 'street_address': guest.street_address,
        'city': guest.city, 'state': guest.state, 'zip_code': guest.zip_code, 
        'guests': guest.guests, 'children': guest.children,'email': guest.email,
        'phone_number': guest.phone_number, 'gift_description': guest.gift_description,
        'status': guest.status.all()}

form = GuestForm(initial=data)

Getting form data via post like this:

form = GuestForm(request.POST)
if form.is_valid():
    full_name = form.cleaned_data['full_name']
    street_address = form.cleaned_data['street_address']
    city = form.cleaned_data['city']
    state = form.cleaned_data['state']
    zip_code = form.cleaned_data['zip_code']
    guests = form.cleaned_data['guests']
    children = form.cleaned_data['children']
    email = form.cleaned_data['email']
    phone_number = form.cleaned_data['phone_number']
    gift_description = form.cleaned_data['gift_description']
    status = form.cleaned_data['status']

    guest = Guest.objects.filter(id=guest_id).update(user=request.user,
        full_name=full_name, street_address=street_address, city=city, 
        state=state, zip_code=zip_code, guests=guests, children=children,
        email=email, phone_number=phone_number, gift_description=gift_description,
        status=status) # The status is clearly not updated

How can I do this?

Edit

GuestForm

class GuestForm(ModelForm):
    status = forms.ModelMultipleChoiceField(
        queryset=GuestStatus.objects.all().order_by('arrangement'),
        widget=forms.CheckboxSelectMultiple, required=False)

    class Meta:
        model = Guest
        exclude = ['user', 'invitation_date']   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With reference to modelForm documentation, when you are using modelForms you don't need so much of code, your code would reduce to:

guest = get_object_or_404(Guest, id=guest_id)
form = GuestForm(instance=guest)

Again for post,

#get the guest instance, if updating existing record
form = GuestForm(request.POST, instance=guest)  
if form.is_valid():
    new_guest = form.save(commit=False) #you want to set excluded fields
    new_guest.user = request.user
    #new_guest.invitation_date = somedate
    new_guest.save()
    form.save_m2m() #should do this if save(commit=False) used

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...