当你实例化视图中的表格,你应该通过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任何想法?能帮帮我吗? –