MyModelForm' object has no attribute 'user using django

喜你入骨 提交于 2019-12-13 07:06:11

问题


i want to create i simple django image processing .first i have create correct a django auth and multi upload images in my app. now i want the user can select one self image from a list django form where i create and that image i get for my processing.i create something but not work.

i take that error :

'MyModelForm' object has no attribute 'user'

here the code :

views.py

@login_required(login_url="login/")
def myview(request):
    Myf = MyModelForm(request.user,request.POST)
    return render(request,'home.html',{'Myf':Myf})

forms.py

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        if 'user' in kwargs:
            self.user = kwargs.pop('user')
        super(MyModelForm, self).__init__(*args, **kwargs)
        choices = [(obj.id, obj.upload.url) for obj in MyModel.objects.filter(user=self.user)]
        self.fields['upload'].widget = Select(choices=choices)

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

if i replace Myf = MyForm(request.user,request.POST) with Myform = MyModelForm(user=request.user) then i think list worked like this

image list

but i cant take select image for image processing.

html :

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

  </form>

any idea ?


回答1:


Your MyForm class does not have user in the __init__ method's signature, so you need to provide it as a keyword argument when instantiating the form:

MyForm(user=request.user,data=request.POST)


来源:https://stackoverflow.com/questions/43459000/mymodelform-object-has-no-attribute-user-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!