2017-04-09 87 views
0

選我已經在這個question閱讀代碼和好看。 但如果我有用戶身份驗證,並且我希望用戶只選擇您的odjects如何更改該代碼?爲ex選擇您的個人上傳圖像。權威性選擇forms.py

from django.forms.widgets import Select 
    class ProvinceForm(ModelForm): 
     class Meta: 
      CHOICES = Province.objects.all() 

      model = Province 
      fields = ('name',) 
      widgets = { 
       'name': Select(choices=((x.id, x.name) for x in CHOICES)), 
      } 

我的模型:

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

所以,明白了,你要爲每個用戶有什麼'select'下拉?他/她自己的圖像?他/她自己的圖像名稱? –

+0

自己的形象是那個上傳之前上傳的形式,即工作,但沒有權威性例如 –

+0

@nik_m任何想法?能幫幫我嗎? –

回答

1

當你實例化視圖中的表格,你應該通過user對象,這樣my_form = MyModelForm(user=request.user)

然後建立自己的MyModelForm

# forms.py 

from django.forms import ModelForm 
from django.forms.widgets import Select 

class MyModelForm(ModelForm): 
    def __init__(self, *args, **kwargs): 
     # extract "user" value from kwrags (passed through form init). If there's no "user" keyword, just set self.user to an empty string. 
     self.user = kwargs.pop('user', '') 
     super(MyModelForm, self).__init__(*args, **kwargs) 
     if self.user: 
      # generate the choices as (value, display). 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('id', 'upload') 
      self.fields['upload'].widget = Select(choices=choices) 

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

現在,每當你實例的形式與user關鍵字參數(my_form = MyModelForm(user=request.user)),這種形式將呈現這樣的(在你的模板寫它像{{ my_form }}):

<select> 
    <option value="the_id_of_the_MyModel_model">upload_name</option> 
    <option value="the_id_of_the_MyModel_model">upload_name</option> 
    ... 
</select> 

最後,爲了在下拉菜單中顯示圖像(請記住,「value」是在提交表單時將被髮送回服務器的數據,而顯示一個ju st用於UX),請撥打a look here

[更新]:如何做到這一點在你的views.py

# views.py 

def my_view(request): 
    my_form = MyModelForm(user=request.user) 
    if request.method == 'POST': 
     my_form = MyModelForm(request.POST, user=request.user) 
     if my_form.is_valid(): 
      # ['upload'] should be the name of the <select> here, i.e if <select name="whatever"> then this should be "whatever" 
      pk = my_form.cleaned_data['upload'] 
      # image, now, is the value of the option selected (that is, the id of the object) 
      obj = MyModel.objects.get(id=pk) 
      print(obj.upload.url) # this should print the image's path 
    return render(request, 'path/to/template.html', {'my_form': my_form}) 
+0

my_form = MyModelForm(user = request.user)'我在我的views.py?和html頁面中做了什麼? –

+0

該代碼顯示我在super() –

+0

語法錯誤是的。你在你的「視圖」中這樣做。在你的html中,簡單的'{{my_form}}'。你得到的錯誤是因爲你使用Python 2.切換到'超(MyModelForm,個體經營).__的init __(* ARGS,** kwargs)' –