Django的ModelForm中带有DB关系的多选字段

2 人关注

这是我第一次在Stackoverflow上发帖,所以请忽略错误。在发帖之前,我已经尝试了十几种解决方案,但都没有成功。我在模型中为用户建立了表关系。我需要创建一个ModelForm,让客户从前端为任何项目选择多个用户。我很难在代码中实现它。另外,对于另一个字段,我需要将选择限制在一个用户。以下是代码。

Models:

class Project(models.Model):
   project_name = models.CharField(max_length=100)
   assigned_to = models.ManyToManyField(User)
   project_url = models.URLField()
def __init__(self):
    return str(self.project_name)

Form.

class ProjectForm(forms.ModelForm)
     class Meta:
       fields = ['project_name', 'assigned_to ', 'project_url']

View:

def projects(request):
   template = 'projects/projects.html'
   if request.method == 'POST':
       form = ProjectForm(request.POST)
       if form.is_valid():
         form.save()
   else:
     form = ProjectForm()
   return render(request, template, {'form': form})

HTML:

<form action='' method='post'>
 {% csrf_token %}
 {{ form }}
 <button type='submit' class='btn btn-primary'>Submit</button>
 </form>

非常感谢您的帮助。

2 个评论
当我遇到这样的情况时,我有一个带复选框的用户列表。在提交时,我有一个post请求,发送用户列表,在views.py中,我从request.POST中获取列表,同时覆盖post方法,然后循环浏览列表,添加用户pk ...类似于```for pk in selected: try: user = User.objects.get(pk=pk) project.project_users.add(user) except User.DoesNotExist: continue ```不知道这是否是你要的方法
很好的解决方案,但我有一个确切的目标,就是在添加问题时在StackOverFlow选择 "标签"。但对于初学者来说,列表已经足够了,我以后会自己添加自动完成功能。
javascript
python
django
Zameer Ahmed
Zameer Ahmed
发布于 2019-07-31
1 个回答
Mudassar Hashmi
Mudassar Hashmi
发布于 2019-08-01
已采纳
0 人赞同

forms.py:

from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        assigned_users = kwargs.pop('assigned_to', [])
        super(ProjectForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs = {"class": "form-control"}
        self.fields['project_name'].required = True
        self.fields['project_url'].required = True
        if assigned_users:
            self.fields['assigned_to'].queryset = assigned_users
        self.fields['assigned_to'].required = True
        self.fields['project_name'].widget.attrs.update({
            'placeholder': 'Project Name'})
        self.fields['project_url'].widget.attrs.update({
            'placeholder': 'Project URL'})
    class Meta:
        model = Project
        fields = ('project_name', 'project_url', 'assigned_to')

views.py

def create_project(request):
    template_name = "create.html"
    users = []
    form = ProjectForm(assigned_to=users)
    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES, assigned_to=users)
        if form.is_valid():
            proj_obj = form.save(commit=False)
            proj_obj.created_by = request.user
            proj_obj.save()
            if request.POST.getlist('assigned_to', []):
                proj_obj.assigned_to.add(*request.POST.getlist('assigned_to'))
                assigned_to_list = request.POST.getlist('assigned_to')
            success_url = reverse('projects:list')
            if request.POST.get("savenewform"):
                success_url = reverse("leads:add_lead")
            return JsonResponse({'error': False, 'success_url': success_url})
        return JsonResponse({'error': True, 'errors': form.errors})
    context = {}
    context["proj_form"] = form
    context["users"] = users
    context["assignedto_list"] = [
        int(i) for i in request.POST.getlist('assigned_to', []) if i]
    return render(request, template_name, context)

创建.html。

<div class="form-control">
    {{ proj_form.project_name }}