【问题标题】:take select request from django from从 django 获取选择请求
【发布时间】:2017-09-12 11:19:46
【问题描述】:

我制作了一个 select django 表单,其中包含每个用户的图像列表。

如何在我的 views.py 中接受该选择请求?

我只设法创建了正确的选择列表,但我需要接受该选择请求。但我不知道怎么做。

models.py

class MyModel(models.Model):
    user = models.ForeignKey(User, unique=True)
    upload = models.ImageField(upload_to='upload')

views.py

   @login_required(login_url="login/")
    def carlist(request):
        Myform = MyModelForm(user=request.user)
        return render(request,'about.html',{'Myform':Myform})

选择 django 表单:

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        # extract "user" from kwrags (passed upon form init)
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(MyModelForm, self).__init__(*args, **kwargs)
        # generate the choices as (display, value). 
        # Display is the one that'll be shown to user, value is 
        # the one that'll be sent upon submitting 
        # (the "value" attribute of <option>)
        choices = MyModel.objects.filter(user=self.user).values_list('upload', 'id')
        self.fields['upload'].widget = Select(choices=choices)

    class Meta:
        model = MyModel
        fields = ('upload',)

html:

<form class="" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
  {{ Myform}}
<input type="submit" name="" value="Submit">

例如Myform 现在有一个用户图像列表,这是正确的,但之后我需要从表单中选择图像。

用我的代码能做到吗?

【问题讨论】:

    标签: python django python-2.7 django-forms django-views


    【解决方案1】:

    是的,你可以用你的代码做到这一点。在你看来,你可以得到它:

    class MyView(View):
         def post(self, request):
             form = MyModelForm(request.POST, request.FILES)
             if form.is_valid():
                  upload_inst = form.cleaned_data['upload']
                  ...        
    

    这将为您提供从表单中选择的图像。

    如果您想选择多张图片,您可以尝试以下操作:

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 2017-08-08
      • 2017-07-02
      • 2012-07-05
      • 1970-01-01
      • 2019-08-26
      • 2017-01-05
      • 2014-02-05
      • 2020-08-16
      相关资源
      最近更新 更多