當你實例化視圖中的表格,你應該通過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})
所以,明白了,你要爲每個用戶有什麼'select'下拉?他/她自己的圖像?他/她自己的圖像名稱? –
自己的形象是那個上傳之前上傳的形式,即工作,但沒有權威性例如 –
@nik_m任何想法?能幫幫我嗎? –