Reputation:
in my project flow I first create a database entry in Orders. At this point, the foreign_key transaction_profile stays empty. At a later point in my checkout_page view, the transaction_profile get's created.
After transaction_profile.save() happened I want to connect the newly created Transaction_Profile with the Order model entry where Order.objects.filter(order_id=request.session['order_id']).
I am really struggling right now to get this done. Anyone here how can help me finding the right track?
checkout > views.py
def checkout_page(request):
if request.POST:
transaction_profile = TransactionProfileModelForm(request.POST)
if transaction_profile.is_valid():
transaction_profile.save()
o = Order.objects.filter(order_id=request.session['order_id'])
#if qs.count() == 1:
o.transaction_profile.add(transaction_profile)
else:
transaction_profile = TransactionProfileModelForm()
context = {
'transaction_profile': transaction_profile,
}
[...]
transactions > models.py
class TransactionProfile(models.Model):
email = models.EmailField()
address_line_1 = models.CharField(max_length=120)
address_line_2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120)
country = models.CharField(max_length=120)
state = models.CharField(max_length=120)
postal_code = models.CharField(max_length=120)
update = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
orders > models.py
class Order(models.Model):
order_id = models.CharField(max_length=10, unique=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
transaction_profile = models.ForeignKey(TransactionProfile, blank=True, null=True, on_delete=models.CASCADE)
Upvotes: 0
Views: 43
Reputation: 2675
You have to save the instance first and assign it to Order
object:
if request.POST:
transaction_profile = TransactionProfileModelForm(request.POST)
if transaction_profile.is_valid():
instance = transaction_profile.save(commit=False)
instance.save()
o = Order.objects.get(order_id=request.session['order_id'])
o.transaction_profile = instance
o.save()
Upvotes: 1