Django:在Get请求中返回了来自表单的错误下拉值

问题描述

我希望基于选择/下拉列表的结果执行库存查询-我已经设置了从html下拉列表中获取的参数以通过URL传递,该URL需要用于过滤另一页上的查询集,但并非如此工作-我不断收到“无反向匹配”错误。 下拉值是主页上一组相关下拉值的一部分;汽车的“制造”和“模型”。 我想使用“模型”的值来打开另一个网页“ search_results”上的可用库存。 我基本上是从“索引”页面发布下拉菜单“ modelddl”的值,并希望在“ search_results”页面获取该值。然后,这应该允许对查询集进行过滤,以便可以填写表。不管我做什么,我似乎都不会在下拉菜单中选择“模型”值,因此该表将呈现为没有任何值。
******更新******使URls在传递值方面起作用,尽管指定了要在表单操作上使用的下拉名称,但它是从makeddl下拉列表而不是modelddl下拉列表传递值索引模板。

URL输出; http:// localhost:56543 / search_results / makeselection = BMW&modelselection = BMW

尽管'modelselection'下拉列表中的值为'116d',但传递了BMW值,这是'makeselection'下拉列表的值。

注释中的更新代码。 所做的更改在下面的评论中。

非常感谢您的帮助!

关键模型

 class MotorMakes(models.Model):
    MotorMakeName = models.CharField(max_length=50,unique=True,default=False)
    
    def __str__(self):
        return self.MotorMakeName or ''
    
    def __unicode__(self):
        return u'%s' % (self.MotorMakeName) or ''

class MotorModelsV2(models.Model):
    MotorMakeName =  models.CharField(max_length=50,default=False,)
    MotorModelName = models.CharField(max_length=50,)
    Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE,default=False)
    Mlid = models.IntegerField(default=False,unique=True)
    MotorImage = models.ImageField(upload_to='Car_Pics',blank=True)
    
    def __str__(self):
        return self.MotorModelName or ''

    def __unicode__(self):
        return u'%s' % (self.MotorModelName) or ''

    class Meta:
        ordering = ('MotorMakeName',)

class GarageInventory(models.Model):
    MotorDetailRef = models.ForeignKey(MotorDetail,null=True)
    GarageID = models.CharField(max_length=5,default='',)
    ListMake= models.CharField(max_length=50,)
    ListSeries = models.CharField(max_length=50,null=True)
    ListModel= models.CharField(max_length=50,default='')
    #ListSeries = models.ForeignKey(CarSeries,on_delete=models.SET_NULL,null=True)
    #ListModel= models.ForeignKey(CarModel,null=True)
    Title = models.CharField(max_length=100,null=True)
    BodyType = models.CharField(max_length=25,null=True)
    GaragePrice = models.DecimalField(max_digits=10,decimal_places=2,default='0')
    FuelType = models.CharField(max_length=15,default='')
    Colour = models.CharField(max_length=15,default='')
    DoorType = models.CharField(max_length=10,null=True)
    CarEngine = models.CharField(max_length=10,null=True)
    Year = models.CharField(max_length=10,null=True)
    created_date = models.DateTimeField(default = timezone.Now)

    
    def __str__(self):
        return '%s %s %s %s' % (self.GarageID,self.ListModel,self.ListMake,self.Title) or ''
        #return self.Model and self.Title or ''

    def __unicode__(self):
        return u'%s' % (self.Title) or ''

    class Meta:
        ordering = ( 'ListMake','ListModel','Title')

Views.py

def home(request): #this is the index file
    """Renders the home page."""
    displayCounty=County.objects.all()
    displayMake=MotorMakes.objects.all()
    displayModel=MotorModelsV2.objects.all()
    displayDetail=MotorDetail.objects.all()
    return render(request,'index.html',{'County':displayCounty,'MotorMakesView':displayMake,'MotorModelsView':displayModel,'MotorDetailView':displayDetail})

 
   
    assert isinstance(request,HttpRequest)
    return render(
        request,'app/index.html',{
            'title':'Home Page','year':datetime.Now().year,}

    )

 class SearchResultsView(ListView):
    model = GarageInventory.objects.all()
    template_name = 'search_results.html'

    def SearchInventory(request,inputvalue=None):
        if request.method=='GET':
            inputvalue=request.GET.get('modelselection',False)
            displayInventory = GarageInventory.objects.all().filter(ListModel=inputvalue)
        else:
            displayInventory = GarageInventory.objects.all()

        return render(request,'search_results',{'GarageInventoryView':displayInventory,})

index.html

<!DOCTYPE html>
{% extends "app/layout.html" %}

{% block content %}

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3mxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" />

        <script>
            $(document).ready(function()
            {
                    var $makevar = $("#makeddl");
                        $modelvar = $("#modelddl");
                        $options = $modelvar.find('option');
                        $makevar.on('change',function()
                        {
                        $modelvar.html($options.filter('[value="' + this.value + '"]'));
                        }).trigger('change');
            });
        </script>
</head>


<div class="container">
    <div class="jumbotron" style="background-image: url(https://t4.ftcdn.net/jpg/02/59/17/83/240_F_259178343_D9wu1JKg49PF0nywVuY7K27I0bMgt7hx.jpg); background-size: 100% 110%;">
       
        <h3 style ="color:midnightblue; text-align:left; font-family:verdana">
            Take the hassle ... 
            <br>
                out of the haggle ...
            </br>
        </h3>

        <p color:white;"></p>
    </div>
</div>




<div class="row">
    <div class="col-md-4">
        <h2>browse the Showroom</h2>
            <p>Choose a make,model and a county to get started</p>
            {#<! -- Drop Downs  -->#}
            <form  action = "{% url 'search_results' %}" method="post">{% csrf_token %} 
                <label for="makeddl">Choose Make</label>
                    {<select id="makeddl">
                        <option  disabled selected="true">Choose Make</option>
                        {% for makes in MotorMakesView %}
                        <option value ="{{ makes.MotorMakeName}}"> {{ makes.MotorMakeName }} </option>      
                        {% endfor %}
                    </select>
                <br><br>
                
                <label for="modelddl">Choose Model</label>
                    <select id="modelddl"> 
                        <option disabled selected ="True">Model</option>
                        {% for mods in MotorModelsView %}
                        <option value="{{ mods.MotorMakeName}}"> {{ mods.MotorModelName}} </option> 
                        {% endfor %}
                    </select>}
                <br><br>
               
                <label for="countyddl">Choose County</label>
                    <select type>
                        <option>County</option>
                        {% for result in County %}
                        <option>{{result.CountyName}}</option>
                        {% endfor %}
                    </select>
                <br><br>
         
            {#<! -- Submit Button -->#} 
            
                <input type="submit" value="Get Offers" placeholder="Search...">
                
                    
                <p><a class="btn btn-default" href="/search_results">Get Offers &raquo;</a></p>
            </form>

    </div>
   
    <div class="col-md-4">
        <h2>Estimate Trade-in Value</h2>
        <p>Estimate the Trade in value fo your car before speaking with the dealer.</p>
        <p><a class="btn btn-default" href="https://www.myvehicle.ie/faq/can-you-tell-me-what-the-true-value-of-the-car-is/">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Arrange a Loan</h2>
        <p>Apply for a loan with our partner ....</p>
        <p><a class="btn btn-default" href="https://carloans4u.ie/?gclid=CjwKCAjw57b3BRBlEiwA1ImytlZI9xjld1wY7n1ln6gERfjTCtwyXoBzj_6p-41pq7UxgDkY16ChVRoC2TUQAvD_BwE">Learn more &raquo;</a></p>
    </div>
</div>
 
{% endblock %}

search_results.html

**<!DOCTYPE html>
{% extends "app/layout.html" %}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
{% block content %}
<head>
    <Meta charset="utf-8" />
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3mxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" />
    <title>Search Results</title>
</head>
<body>
    <h1><Strong>Here are your deals;</Strong></h1>
    <p>
    </p>
            <table class= "table table-striped">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">Garage ID</th>
                        <th scope="col">Model</th>
                        <th scope="col">Make</th>
                        <th scope="col">Title</th>
                        <th scope="col">Year</th>
                        <th scope="col">Body</th>
                        <th scope="col">Offer Price</th>
                        <th scope="col">RRP</th>
                        
                    </tr>
                </thead> 
                    {% for inv in  GarageInventoryView %}
                <tbody class = "table table-hover">
                     <tr>   
                        <td>{{inv.GarageID}}</td>
                        <td>{{inv.ListModel}}</td>
                        <td>{{inv.ListMake}}</td>
                        <td>{{inv.Title}}</td>
                        <td>{{inv.Year}}</td>
                        <td>{{inv.BodyType}}</td>
                        <td>{{inv.GaragePrice}}</td>
                        
                        {% for mods in MotorDetailsView %}
                            <td>{{ mods.id}}> {{ mods.RRP}}</td>
                        {% endfor %}
                     </tr>
                    {% endfor %}
                </tbody>    
            </table>
               
       
</body>
</html>
{% endblock %}**

URLs.py

urlpatterns = [
    path('',views.home,name='home'),url(r'^search_results/(?P<inputvalue>\D+)/$',views.SearchResultsView,name ='search_results'),

解决方法

Index.html-表单方法为“发布”,将其更改为“获取”