简体   繁体   English

Django如何正确提交表单并处理请求?

[英]Django how to properly submit form and handle request?

I'm new to Django/Python and working on a webapp that queries a DB of cars based on selects/dropdowns on the home page and sends the user to a details page about the car they selected. 我是Django / Python的新手,并且正在使用一个Webapp,该Webapp根据主页上的选择/下拉列表查询汽车数据库,并将用户发送到有关他们选择的汽车的详细信息页面。 This is done through a 'make', 'model', and 'trim' dropdown box. 这是通过“ make”,“ model”和“ trim”下拉框完成的。 What I'm having trouble understanding and getting errors doing, is submitting the trim ID upon clicking a button that will submit the form. 我在理解和执行错误时遇到的麻烦是,在单击提交表单的按钮后提交了整理ID。 I know what needs to happen I just don't know how to do so using Django views and templates. 我知道需要发生什么,我只是不知道如何使用Django视图和模板来完成。

The make box is populated via returned queryset from IndexView. 通过从IndexView返回的queryset填充make框。 The model box is populated via jQuery/Ajax dependent upon which make was selected in the make box. 通过jQuery / Ajax填充模型框,具体取决于在make框中选择了哪个make。 The trim box is the same way, populated dependent upon what was selected in the model box. 装饰框的使用方法与之相同,取决​​于在模型框中选择的内容。 I now need to be able to submit the form (which really only needs to submit the trim ID because the trim IS the specified car) in order to show details about the car that the user has chosen. 现在,我需要能够提交表单(由于装饰是指定的汽车,因此实际上只需要提交装饰ID),以显示有关用户选择的汽车的详细信息。

This is the error I am getting: 这是我得到的错误:

Reverse for 'search' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['search/(?P<trim>\\d+)/$']

This is basically what my homepage template looks like: 这基本上是我的主页模板的样子:

  <form action="{% url 'search:search' trim.id %}" class="form-inline" id="dropdownText"> <div class="form-group" id="dropdownGroup"> <span style="display:inline-block" class="selectBox"> <select class="form-control" id="make"> <option value='empty'></option> {% for make in allMakes %} <option value="{{ make.id }}">{{ make.name }}</option> {% endfor %} </select> <label for="make" style="display:block">Make</label> </span> <span style="display:inline-block" class="selectBox"> <select class="form-control" id="model" disabled> <!-- List each make's model's name with JQ. --> </select> <label for="model" style="display:block">Model</label> </span> <span style="display:inline-block" class="selectBox"> <select class="form-control" id="trim" name="selectedTrim" disabled> <!-- List all trims for each make/model with JQ. --> </select> <label for="trim" style="display:block">Trim</label> </span> </div> <div class="text-center"> <button type="submit" class="btn btn-default" id="go">GO!</button> </div> </form> 

URLs: 网址:

# Index
url(r'^$', views.IndexView.as_view(), name='index'),

# /trimId
url(r'^(?P<pk>\d+)/$',
DetailView.as_view(), name='detail'),

# /search
url(r'^search/(?P<trim>\d+)/$', views.search, name='search'),

# Uses Ajax/JSON to change the model/trim boxes. Use make
# and model instead of pk to pass them into the view fxns.
url(r'^getmodels/(?P<make>\d+)/', views.getModels, name='getmodels'),
url(r'^gettrims/(?P<model>\d+)/', views.getTrims, name='gettrims'),

Views: 观看次数:

class IndexView(generic.ListView):
    template_name = 'search/index.html'

    # Name of the template varible.
    context_object_name = 'allMakes'

        def get_queryset(self):
            # Return what will be listed in index.html
            return Make.objects.all()

class DetailView(generic.DetailView):
    model = Trim
    template_name = 'search/detail.html'

# Take in the request and the ID for the selected Make
# and return something that we can work with in JS!
def getModels(request, make):
    selectedMake = Make.objects.get(id=make)

    # Get the models based on what was selected as the make.
    models = Model.objects.all().filter(make=selectedMake)
    # Translate to JSON
    jsonModels = serializers.serialize("json", models)
    # Return the JSON.
    return HttpResponse(jsonModels, content_type='application/javascript')

def getTrims(request, model):
    selectedModel = Model.objects.get(id=model)

    trims = Trim.objects.all().filter(model=selectedModel)
    jsonTrims = serializers.serialize("json", trims)
    return HttpResponse(jsonTrims, content_type='application/javascript')

# Can I make this redirect to the DetailView with the ID for the
# trim to show details for?
def search(request, trim):
    selectedTrim = get_object_or_404(Trim, pk=trim)
    context = {'trim': selectedTrim}
    return render(request, 'search/detail.html', context)

That error: 该错误:

Reverse for 'search' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['search/(?P<trim>\\d+)/$']

means that you didn't give the id parameter (you called it trim). 表示您没有提供id参数(您称其为trim)。 It should be part of the arguments or keyword arguments. 它应该是参数或关键字参数的一部分。

I assume that's because there is no trim object in the template here: 我认为这是因为模板中没有修剪对象:

<form action="{% url 'search:search' trim.id %}"

Is that template rendered via a DetailView? 该模板是否通过DetailView呈现? If that's the case the following would probably work: 如果是这样的话,以下方法可能会起作用:

<form action="{% url 'search:search' object.id %}"

The solution to the problem I was having lied in my url patterns. 解决这个问题的方法是我使用了网址格式。 By taking out the ID portion of the search URL, and changing the view as such: 通过取出搜索 URL的ID部分,并按如下方式更改视图:

def search(request):

    trim = request.GET['selectedTrim']
    selectedTrim = get_object_or_404(Trim, id=trim)
    context = {'trim': selectedTrim}
    return render(request, 'search/detail.html', context)

and my form action to: 而我的表单动作是:

action="{% url 'search:search' %}"

I was able to successfully pass the selected trim to the view via request method, and not through the url regex variable, which was causing the error due to the selected trim ID not actually existing via context provided to the template (I think). 我能够通过请求方法,而不是通过url regex变量,成功地将选定的修剪传递给视图,这是由于通过提供给模板的上下文实际不存在所选修剪ID导致的错误(我认为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM