I have a page that lists all the items from a table named Stocks for each row there's a clickable ORDER button that leads users to another page where they can enter all their details as well as select what item and how much they wanna buy which would then save all of that data to a table named Orders.
This orders table is linked with the Stocks table like this:
class Order(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
quantity = models.IntegerField(default='0', blank=False, null=True)
order_item = models.ForeignKey(Stock, on_delete=models.CASCADE, blank=True)
address = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
Depending on what item they clicked the order button for I wanted to automatically select the corressponding item from the dropdown menu on the next page so that they won't have to.
def create_order(request, pk):
queryset = Stock.objects.get(id=pk)
form = CreateOrderForm(request.POST or None, initial={'order_item':queryset.item_name})
if form.is_valid():
form.save()
context = {
'form':form
}
return render(request, 'add_items.html', context)
I tried doing this by using the intitial command but for some reason it just won't change from the default blank option.
Here's my forms.py just in case
class CreateOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['name','quantity','order_item','address','city']