Ticker

6/recent/ticker-posts

Header Ads Widget

GET/POST Operation in Django Framework

CURD Operation in Django



    Creating a Django application that handles POST requests from a form containing a dropdown list involves several steps:
    1. Define the Model (if applicable):
    If the dropdown choices are dynamic and come from a database, define a Django model to represent these choices.
    Python
    # myapp/models.pyfrom django.db import modelsclass Category(models.Model):    name = models.CharField(max_length=100)    def __str__(self):        return self.name
    2. Create the Form:
    Define a Django Form or ModelForm to handle the dropdown field and other form elements.
    Python
    # myapp/forms.pyfrom django import formsfrom .models import Category # If using a model for dropdown choicesclass MyForm(forms.Form):    # For static choices    FRUIT_CHOICES = [        ('apple', 'Apple'),        ('banana', 'Banana'),        ('orange', 'Orange'),    ]    selected_fruit = forms.ChoiceField(choices=FRUIT_CHOICES, label="Select a Fruit")    # For dynamic choices from a model    selected_category = forms.ModelChoiceField(queryset=Category.objects.all(), label="Select a Category")
    3. Define the View:
    The view handles both GET and POST requests.
    Python
    # myapp/views.pyfrom django.shortcuts import renderfrom .forms import MyFormdef my_view(request):    if request.method == 'POST':        form = MyForm(request.POST)        if form.is_valid():            # Process the submitted data            selected_fruit = form.cleaned_data['selected_fruit']            selected_category = form.cleaned_data['selected_category'] # If using ModelChoiceField            # Perform actions based on selected values            return render(request, 'myapp/success.html', {'fruit': selected_fruit, 'category': selected_category})    else:        form = MyForm()    return render(request, 'myapp/my_template.html', {'form': form})
    4. Create the Template:
    The HTML template displays the form with the dropdown and handles form submission.
    Code
    <!-- myapp/my_template.html --><form method="post">    {% csrf_token %}    {{ form.as_p }}    <button type="submit">Submit</button></form>
    5. Configure URLs:
    Map the view to a URL in your urls.py.
    Python
    # myproject/urls.py or myapp/urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [    path('my-form/', views.my_view, name='my_form'),]
    Explanation:
    • GET Request:
      When the page is initially loaded (a GET request), an empty MyForm instance is created and passed to the template for rendering.
    • POST Request:
      When the form is submitted (a POST request), a MyForm instance is created with the request.POST data.
    • Form Validation:
      form.is_valid() checks if the submitted data meets the form's validation rules.
    • Accessing Data:
      If the form is valid, form.cleaned_data provides a dictionary of validated form data, including the selected value from the dropdown.
    • Processing Data:
      The selected value can then be used to perform further actions, such as filtering database queries or displaying specific content.


    Post a Comment

    0 Comments