我试图弄清楚如何使用数据库中的用户列表填充下拉选择表单。提交表单时,我希望将所选用户添加到Task模型对象ManyToMany用户字段中。然而,这样做的逻辑令我感到困惑。如何使用模型对象列表填充表单,如何捕获views.py文件中提交的对象?
答案 0 :(得分:0)
<强> models.py 强>
class Task(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(User)
<强> urls.py 强>
from django.conf.urls import patterns, url
urlpatterns = patterns('app.views',
url(r'^task/(?P<task_id>\d+)/$', 'task', name='task'),
url(r'^task/(?P<task_id>\d+)/adduser/$', 'add_user', name='add_user'),
)
<强> views.py 强>
from django import forms
from django.shortcuts import get_object_or_404, redirect, render
from app.models import Task
class AddUserForm(forms.Form):
user = forms.ModelChoiceField(queryset=User.objects.all())
def task(request, task_id):
task = get_object_or_404(Task, pk=task_id)
return render(request, 'task_detail.html',
{'task': task, 'form': AddUserForm()}
def add_user(request, task_id):
task = get_object_or_404(Task, pk=task_id)
if request.method == 'POST':
form = AddUserForm(request.POST)
if form.is_valid():
task.users.add(form.cleaned_data['user'])
return redirect('task', task_id)
<强> task_detail.html 强>:
<form action="{% url 'add_user' task.id %}" method="POST">
{% csrf_token %}
<h1>{{ task.name }}</h1>
<ul>
{% for u in task.users.all %}
<li>{{ u }}</li>
{% endfor %}
</ul>
<p>Add another user</p>
{{ form.as_p }}
<button>Add</button>
</form>