从django中选择请求

时间:2017-04-16 19:39:26

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

我已经为每个用户创建了一个包含图像列表的精选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现在有一个用户图像列表,这是正确的,但之后我需要从表单中选择的图像。

可以用我的代码做到吗?

1 个答案:

答案 0 :(得分:0)

是的,您可以使用您的代码执行此操作。在您看来,您可以将其视为:

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

这将为您提供表格中的选定图像。

如果您想要选择多个图像,可以尝试以下操作: