我编写了代码,但我不知道如何使用Django模板设置隐藏代码的'name'
和'value'
。我看了Django's Widgets Docs,但我找不到路。
(Pdb) print(errors)
<ul class="errorlist"><li>friend_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>add_remove<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
首先,我试着像
一样写作<input type="hidden" name="friend_id" value="{{ user_info.user_id }}">
和
friend_id = request.POST.friend_id
但是如果没有Django的Form,我无法获得如何获取POST值。所以,我使用Django的表格和以下代码。
views.py
from myapp.forms import HiddenUserPage
hiddenform = HiddenUserPage
if request.method == 'POST':
hidden = hiddenform(request.POST)
if hidden.is_valid():
from myapp.models import Friends
try:
friend_id = hidden.cleaned_data['friend_id']
add_remove = hidden.cleaned_data['add_remove']
if add_remove == "add":
f = Friends(user_id=request.user.user_id, friend_id=friend_id)
f.save()
elif add_remove == "remove":
f = Friends.objects.filter(user_id=request.user.user_id).get(friend_id=friend_id)
f.delete()
except:
errors = "DB error"
else:
errors = hidden.errors
else:
hidden = hiddenform()
errors = ""
view = {
'errors': errors,
'hidden': hidden,
}
template = 'myapp/user/user_page.html'
return render(request, template, view)
forms.py
class HiddenUserPage(forms.Form):
friend_id = forms.CharField(widget=forms.HiddenInput())
add_remove = forms.CharField(widget=forms.HiddenInput())
user_page.html
<form method="POST" action="" class="">
{% csrf_token %}
<p class="submit">
<button class="confirmbutton" type="submit">
{% if is_friend %}
remove friend
<!-- # I'd like to write like # -->
<!-- <input type="hidden" name="friend_id" value="remove"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% else %}
add friend
<!-- <input type="hidden" name="friend_id" value="add"> # -->
<!-- <input type="hidden" name="friend_id" value="{{ user_info.user_id }}"> # -->
{{ hidden.add_remove }}
{{ hidden.friend_id }}
{% endif %}
</button>
</p>
</form>
抱歉,我的代码很脏。
答案 0 :(得分:2)
看起来问题在于向表单提供初始数据,然后通常在将initial
传递给表单实例的视图中完成,例如:
# In your view.py
def ...(...):
# Inside your view function
if request.method == 'GET':
# Provide initial data to the form here
# Get your 'user_info' from models or sessions,
# or wherever you keep it
hidden = hiddenform(initial={"friend_id":user_info.user_id})
if reuest.method == 'POST':
hidden = hiddenform(request.POST)
# Process posted form data
...
# More code general for both HTTP verbs
view = {'errors': errors, 'hidden': hidden}
template = 'myapp/user/user_page.html'
return render(request, template, view)
您可能还希望将表单绑定到模型数据,请参阅the docs for more info。