Home > OS >  Django ModelForm submit button not working
Django ModelForm submit button not working

Time:06-12

I am trying to make a Django ModelForm that retrieves data from my database using the GET method. When I click the submit button nothing happens. What am I doing wrong?

HTML doc

<form role="form" action="" method="GET" id="form-map" >
     <h2>Search Properties</h2>
     {% csrf_token %}
     {{ form.as_p }}
          <input type="submit" action= ""  value="Submit">
          <input type="reset"  value="Reset">
</form><!-- /#form-map -->

forms.py

from django import forms
from .models import StLouisCitySale208
from django.forms import ModelForm, ModelMultipleChoiceField


class StLouisCitySale208Form(ModelForm):
    required_css_class = 'form-group'
    landuse = forms.ModelMultipleChoiceField(label='Land use', widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('landuse', flat=True).distinct())
    neighborho =forms.ModelMultipleChoiceField(label='Neighborhood',widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('neighborho', flat=True).distinct())
    policedist = forms.ModelMultipleChoiceField(label='Police district',widget=forms.SelectMultiple,queryset=StLouisCitySale208.objects.values_list('policedist', flat=True).distinct())
    class Meta:
        model = StLouisCitySale208
        fields = ['landuse', 'neighborho', 'policedist', 'precinct20','vacantland', 'ward20', 'zip', 'zoning','asmtimprov', 'asmtland', 'asmttotal', 'frontage', 'landarea','numbldgs', 'numunits']

views.py

from django.views.generic import FormView, TemplateView
from .forms import StLouisCitySale208Form

class StLouisCitySale208View(FormView):
    form_class = StLouisCitySale208Form
    template_name = 'maps/StlouiscitySale208.html'

maps/urls.py

from django.urls import path
from .views import StLouisCitySale208View, ComingSoonView

app_name = 'maps'

urlpatterns = [
    path("maps/stlouiscitysale208",StLouisCitySale208View.as_view(),name="stlouiscitysale208"),
    path('maps/coming_soon', ComingSoonView.as_view(), name="coming_soon")
]

CodePudding user response:

You need a get method in your class to tell the button what to do.

class MyView(View):
    def get(self, request):
     # <view logic>
    return HttpResponse('result')

https://docs.djangoproject.com/en/4.0/topics/class-based-views/intro/

CodePudding user response:

Your form currently has method="GET" which is something you'd use for search, or some other operation which doesn't change the state of the application.

It sounds like you're hoping to create objects using your model form, so change that to method="POST" and you'll at least allow the application to create your object. There may be more to debug at that point, but you need to start by sending data to the server.

  • Related