Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select specific option from dropdown menu DJANGO

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading