python - Django - Find out which model instance I'm editing in an inline formset -
note: i'm new django , python. i'm not sure if i've misunderstood use of inline formsets in way.
i needed able edit fields multiple instances of guest model (linked parent invite model) @ same time in 1 form. after lot of , forth, managed set inline formset submits successfully.
however, interface confusing, because don't know guest you're filling in details for. each guest has guest_name
field, , want display name each form, users know they're editing for.
here's (condensed) view:
def extra_view(request, code): # specific invite invite = get_invite(code) # context request. context = requestcontext(request) # store guests attending object guests_attending = invite.guest_set.filter(attending=true, invite=invite) # create formset each guest guestformset = inlineformset_factory(invite, guest, form=extraform, fields=('diet', 'transport'), extra=0, can_delete=false) if request.method == "post": formset = guestformset(request.post, request.files, instance=invite, queryset=guest.objects.filter(attending=1)) if formset.is_valid(): # save data database. formset.save() # redirect stuff here if guests_attending.count() > 0: formset = guestformset(instance=invite, queryset=guest.objects.filter(attending=1)) # return view return render_to_response('app/extra.html', { 'guestform': formset, 'invite': invite, 'guests_attending': guests_attending, 'errors': formset.errors }, context) else: # backup if no guests attending
here's how models look:
class invite(models.model): # code identify invites code = models.charfield(max_length=6, default=code_generator(4, do_check=true), unique=true) group_name = models.charfield(max_length=200) def __str__(self): return self.group_name class guest(models.model): invite = models.foreignkey(invite, on_delete=models.cascade) guest_name = models.charfield(max_length=200) diet = models.charfield(max_length=250, null=true, blank=true) transport = models.nullbooleanfield(default=false) attending = models.nullbooleanfield(default=false) def __str__(self): return self.guest_name
and here's template
{% if invite %} <form method="post" action=""> {% csrf_token %} {{ guestform.management_form }} <table> {% form in guestform %} <!-- guest editing for?! --> {% hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% field in form.visible_fields %} {{ field.errors }} <div> {{ field.help_text }} {{ field }} </div> {% endfor %} {% endfor %} </table> <button type="submit" class="btn">continue</button> </form> {% endif %}
you can access form's instance form.instance
. in template, like:
{{ form.instance.guest_name }}
Comments
Post a Comment