Reputation: 37
I have two Django models:
class seller_event(models.Model):
event_id = models.AutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length = 300, default = 'Null')
description = models.CharField(max_length = 300, default = 'Null')
location = models.CharField(max_length= 300, default = 'Null')
cash_payment = models.BooleanField(default=True)
paytm_payment = models.BooleanField(default=False)
def __unicode__(self):
return str(self.event_id)
class seller_event_items(models.Model):
item_id = models.AutoField(primary_key=True)
event_id = models.ForeignKey(seller_event)
item_name = models.CharField(max_length = 300, default = 'Null')
item_price = models.CharField(max_length = 300, default = 'Null')
item_quant = models.CharField(max_length = 300, default = 'Null')
def __unicode__(self):
return str(self.item_id)
The foreign key for the second table is the primary key for the first table. Essentially, I am trying to associate items with a sale. I have a forms like such:
forms.py:
class Seller_event(forms.ModelForm):
class Meta:
model = seller_event
exclude = {'user'}
class Seller_event_items(forms.ModelForm):
class Meta:
model = seller_event_items
exclude = {'event_id'}
views.py:
def newlist(request):
if request.user.is_authenticated():
user = request.user
print user
if request.method == 'POST':
seller_event_form = Seller_event(request.POST)
seller_event_items_form = Seller_event_items(request.POST)
if seller_event_form.is_valid() and seller_event_items_form.is_valid():
new_seller_event = seller_event_form.save(commit=False)
new_seller_event.user = user
new_seller_event.save()
seller_event_items_form.save()
return redirect('/home')
else:
seller_event_form = Seller_event()
seller_event_items_form = Seller_event_items()
return render(request, 'home/newlist.html', {'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_form})
The form here is helping a seller both create a sale and then populate the sale with items.
How can I go about automatically setting the fk on the items table as the event_id (pk for seller_events table)? I have excluded it from the form, but I'm not sure what to do after this.
Thanks in advance!
Upvotes: 0
Views: 42
Reputation: 912
add this line before seller_event_items_form.save()
when the model is saved
you can reference it as ForeignKey
seller_event_items.event_id = new_seller_event
Upvotes: 3
Reputation: 599648
You do it in exactly the same way you are already setting the user on the new_seller_event.
The relationship between the event and the user is the same as the relationship between the item and the event.
Upvotes: 1