Home > Net >  Select specific option from dropdown menu DJANGO
Select specific option from dropdown menu DJANGO

Time:02-22

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']

CodePudding user response:

Use the Stock object as initial value, so not queryset.item_name, but queryset (although since it is not a queryset, it is better to rename this to stock):

from django.shortcuts import get_object_or_404

def create_order(request, pk):
    stock = get_object_or_404(Stock, id=pk)
    if request.method == 'POST':
        form = CreateOrderForm(request.POST, initial={'order_item': stock})
        if form.is_valid():
            form.save()
    else:
        form = CreateOrderForm(initial={'order_item': stock})
    context = {
        'form':form
    }
    return render(request, 'add_items.html', context)

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

  • Related