开发者

Django- How do I add hidden fields to a formset and populate them?

开发者 https://www.devze.com 2023-02-10 10:06 出处:网络
I\'m working on a project that has a RSVP form on it. Right now I have it functioning to process their basic info including number of additional guests they are bringing with them. This number is then

I'm working on a project that has a RSVP form on it. Right now I have it functioning to process their basic info including number of additional guests they are bringing with them. This number is then used to populate X number of fields in a formset on the next page that just asks for guest names and comments.

what I'm looking to be able to do is add a hidden field to the formset of guest names which would 开发者_StackOverflow中文版contain the name of the person who registered them as coming.

I am already passing session data to prepopulate the first guest name with the registering guest's info, and I have a session variable defined that could populate the hidden field. I just need to know how to add the field to the formset.

from django.db import models

#models.py
class Guest(models.Model):
    ATTENDING_CHOICES = (
        (u'Yes', u'Yes'),
        (u'No', u'No'),
        (u'Maybe', u'Maybe?')
    )

    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=50)
    attending = models.CharField(max_length=15, choices=ATTENDING_CHOICES)
    no_of_guests = models.IntegerField(verbose_name='Total # of guests', max_length=3)
    notes = models.TextField(null=True, blank=True)
    def __unicode__(self):
        return u'%s, %s - %s' % (self.last_name, self.first_name, self.email)

class GuestsAttending(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    comments = models.CharField(null=True, blank=True, max_length=100)
    #This is the field that I would like to be hidden and filled
    registered_by = models.CharField(max_length=40, blank=True, null=True, editable=False)
    def __unicode__(self):
        return u'%s %s' % (self.last_name, self.first_name)

and Views:

#views.py
from django.forms.models import modelformset_factory

def guest_create(request):
    context_instance=RequestContext(request)
    if request.method == 'POST':
        form = GuestForm(request.POST)
        if form.is_valid():
            request.session['first_name']= request.POST['first_name']
            request.session['last_name']= request.POST['last_name']
            request.session['e_mail']= request.POST['email']
            request.session['no_of_guests']= request.POST['no_of_guests']
            form.save()
            return HttpResponseRedirect('/guest_list_add/')
    else:
        form = GuestForm()
    return render_to_response('rsvp.html', locals(), context_instance,)

def guest_list_add(request):
    n = int(request.session['no_of_guests'])
    context_instance=RequestContext(request)
    GuestFormset = modelformset_factory(GuestsAttending, extra=int(n))
    if request.method == 'POST':
        formset = GuestFormset(request.POST)
        if formset.is_valid():
            instance = formset.save()
            return HttpResponseRedirect('/submitted/')
    else:
        formset = GuestFormset(queryset=GuestsAttending.objects.none(), initial=[
            {'first_name': request.session['first_name'],
            'last_name': request.session['last_name'],
        ])
    return render_to_response('guest_list_add.html', locals(), context_instance,)

Let me know if you'd like to see any addition code- like templates maybe?

So, my question in a detailed summary- How can I add request.session data (first & last name and email) to every "registered_by" field in my formset (view=guest_list_add, model=GuestsAttending) Thanks!


Why does it need to be a hidden field in the formset? You've got access to that stuff in the view, why not just do it there?

if formset.is_valid():
    for form in formset:
        guest = form.save(commit=False)
        guest.invited_by = "%s %s" (request.session['first_name'], request.session['last_name'])
        guest.save()


have you tried filling your formset with that additional "referrer" data just before you save it on the database?

For instance, in the saving objects in the formset section of django's documentation on modelform formsets, you'll see that you can process the items on the formset if you do a save(commit=False) on the formset and then iterate on the instances inside the formset. That way, you can do pretty much whatever you want with them for example: you can fill them up with your referrer data.

0

精彩评论

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

关注公众号