微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django:根据产品模型中最终用户的数据动态更新前端下拉列表

如何解决Django:根据产品模型中最终用户的数据动态更新前端下拉列表

我希望为浏览其图书收藏的用户提供下拉过滤器。下拉值当前填充有模型中的每个相应字段值,我只希望用户获得与他们相关的值,例如我只有出版商与我的书“Marvel”相关联,所以当我去过滤我的书时,我应该只看到出版商下拉菜单中的 Marvel。

即使设置了初始化函数,我也无法将用户值传递给表单下拉列表。当我将值传递给表单时,我不断收到错误消息,视图中没有诸如“uid”或“user”之类的属性

Models.py

class ComicInput(models.Model):
        Publisher = models.CharField(max_length=20,default='Marvel',choices=Publisher_Choices,null=True,blank=True )
        Title = models.CharField(max_length=50,default='',blank=False)
        Type = models.CharField(max_length=30,choices=Type_Choices,blank=True ) #default='Reg'
        Number = models.IntegerField(default='',blank=False)
        Category = models.CharField( max_length=12,default="Hold",choices=Category_Choices,blank=True,null=True)
        uid = models.ForeignKey(User,on_delete=models.CASCADE,editable=False) #default=False,null=True)

        def __unicode__(self):
            return '%s %s %s' % (self.uid,self.Title,self.Number,self.Grade,self.Series,self.CoverPic,self.Category)

        class Meta:
            ordering = ('Title','Series','Number')

Views.py

##################### 收藏夹查看器#############

@login_required(login_url="/login/") 
def ComicInventory(self):

    title_list = TitleChoiceField()
    publisher_list = PublisherChoiceField()
    sellingnotes_list = NotesChoiceField()
    category_list = CategoryChoiceField()

    if self.GET.get('titles'): # On screen drop down Filter for titles
        selected_title = self.GET.get('titles')
        displayInventory=ComicInput.objects.filter(Title=selected_title,uid=self.user)
        displaySumValue=ComicInput.objects.all().filter(Title=selected_title,uid=self.user).aggregate(Sum('Value'))
       
    else:
        displayInventory=ComicInput.objects.filter(uid=self.user)
        displaySumValue=ComicInput.objects.all().aggregate(Sum('Value'))
    context = {
        'displayInventory': displayInventory,'displaySumValue': displaySumValue,'title_list': title_list,}

    return render(self,'app/viewer.html',context)

HTML

<body>
    <h1><Strong>Here are your comics;</Strong></h1>
    <div class="panel-heading">
        **<!.. this is the Choice Field on HTML ..!>**           
        <div class="panel-title pull-left">
            <form method="get" action="{% url 'ComicInventory' %}">
                {{ category_list }}
                <input type="submit" value="Filter">
            </form>
        </div>
        

    <div class="container">
    <table class="table table-striped">
        <thead class="thead-dark">
            <tr>
                <th scope="col">Publisher</th>
                <th scope="col">Title</th>
                <th scope="col">Number</th>
                <th scope="col">Edition</th>
            </tr>
        </thead>
        {% for inv in  displayInventory %}
        <tbody class="table table-hover">
            <tr>
                <td>{{inv.Publisher}}</td>
                <td>{{inv.Title}}</td>
                <td>{{inv.Number}}</td>
                <td>{{inv.Edition}}</td>
alt="{{inv.Publisher}} image",height="60",width="100" /></a></td>
                <td> <a href="/edit/{{inv.id}}">Edit</a> </td>
                <td> <a href="/delete/{{inv.id}}">Delete</a> </td>
                
            </tr>
            
            {% endfor %}
       
        </tbody>
        <tfoot>
           <tr>
               <td><b>Total Value: {{displaySumValue}} </b></td>
           </tr>
        </tfoot>
    </table>



    </div>
</body>

编辑 Form.py ##Updated Model ChoiceField 启动自我,因此我可以获取用户并将其传递给视图##

class TitleChoiceField(forms.Form):

    class Meta:
        model = ComicInput
        fields = ('Title','uid',)
    
    def __init__(self,uid,*args,**kwargs):
        super(TitleChoiceField,self).__init__(*args,**kwargs)
        self.fields['titles'].queryset=ComicInput.objects.filter(uid=self.user).values_list("Title",flat=True).distinct().order_by('Title')

解决方法

Django AttributeError: Form object has no attribute '_errors'

根据上面的帖子更新表格:

Forms.py

class TitleChoiceField(forms.Form):
    

    class Meta:
        model = ComicInput
        fields = ('Title','uid',)
    
    titles = forms.ModelChoiceField(queryset =ComicInput.objects.all())

    def __init__(self,uid=None,*args,**kwargs):
        super(TitleChoiceField,self).__init__(*args,**kwargs)
        
        self.user = uid
        usrqry = ComicInput.objects.filter(uid=self.user).values_list('Title',flat=True).distinct().order_by('Title')
        
        self.fields['titles'].queryset=usrqry

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?