I need some help getting past a django error using inline forms. I can't seem to figure this out. I could probably force-insert the eventID if I could figure out how to do that before it tries to validate.
When I submit my form I get an error: Hidden field (event): The inline foreign key did not match the parent instance primary key
Is there any way to make this code work?
The following code is supposed to let a teacher enrol multiple students for an event.
------ models.py ------------
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=200)
time = models.DateTimeField()
duration = models.DecimalField(max_digits=5, decimal_places=2)
location = models.CharField(max_length=200)
# Customer is a parent, teacher, or school
class Customer(models.Model):
event = models.ForeignKey(Event)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
address1 = models.CharField(max_length=60)
address2 = models.CharField(max_length=60, blank=True)
city = models.CharField(max_length=30)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=5)
phone_number = models.CharField(max_length=30)
email = models.EmailField()
# A customer can enroll several students for a single event.
class Attendee(models.Model):
event = models.ForeignKey(Event)
sponsor = models.ForeignKey(Customer)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
------ forms.py -----------
class AttendeeForm(forms.ModelForm):
event = forms.IntegerField(required=True, widget=forms.HiddenInput())
class Meta:
model = Attendee
fields = ( 'event', 'last_name', 'first_name', 'gender', 'schoolYr', )
#exclude = ('event', )
#widgets = {
# 'dtgPurchase' : DateTimeWidget(),
#}
def __init__(self, *args, **kwargs):
super(AttendeeForm, self).__init__(*args, **kwargs)
------- views.py ----------
def register3(request, event_id):
messages = []
try:
event = get_object_or_404(Event, id=event_id) #Event ID is passed in here.
AttendeeFormSet = inlineformset_factory(Event, Attendee, form=AttendeeForm, extra=1)
#AttendeeFormSet = formset_factory(AttendeeForm)
if request.method == 'POST':
print "POST"
formset = AttendeeFormSet(request.POST, request.FILES, prefix='attendees')
#formset.save(commit=False)
i=0
for form in formset.forms:
print "Form %s " % str(i)
# ?? Is is possible to set the event Here?
if formset.is_valid():
attendees = formset.save_all()
print "Yay!!!"
#return redirect('event_view', event_id=event.id)
else:
print "Invalid formset"
else: # is get method on first step
formset = AttendeeFormSet(instance=event, prefix='attendees')
print "Event: %s " % event
except Event.DoesNotExist:
raise Http404
c = Context({
'messages': messages,
'event' : event,
'attendees': formset,
})
return prepCxt(request, 'register3.html', c)
What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it’s used to create many-to-one relationships within tables. It’s a standard practice in relational databases to connect data using ForeignKeys. What’s the difference between foreign key and primary key?
The foreign key represents the primary key of the other instance. In standard practice, BigInt almost always references other instances as ForeignKey because the primary key of other instances is BigInt. Let’s have a look at the database structure of the Book model from the first example:
In other words, ForeignKey should be placed in the Child table, referencing the Parent table. NOTE - Without an Author, there can't be Book (Author is parent, Book is child model) In given example – One Author can write multiple books, and one Book can be written only by one Author. That’s why we placed ForeignKey in the Book model.
ForeignKey is a Field (which represents a column in a database table), and it’s used to create many-to-one relationships within tables. It’s a standard practice in relational databases to connect data using ForeignKeys. What’s the difference between foreign key and primary key? The primary key defines the unique value for a row in a table.
You may need to pass instance in POST processing as well.
formset = AttendeeFormSet(request.POST, request.FILES, prefix='attendees', instance=event)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With