Djano表单多选-无法分配QuerySet,必须是用户实例

时间:2019-05-26 20:00:51

标签: django python-3.x django-models django-forms django-views

我正在尝试建立基本的工作/任务清单。在“职位创建”表单中,我试图通过“注册用户”列表中的“多个选择”字段来增加“作者”向工作分配其他人员的功能。

到目前为止,它似乎可以通过管理表单来工作。但是,当我在“作业创建页面”上执行相同操作时,会收到以下ValueError:

无法分配“ QuerySet [CustomUser:testuser1,CustomUser:testuser2]”:“ Job.personnel”必须是“ CustomUser”实例。

我不确定该视图中我做错了什么,我看过类似的话题,但是那些选项要么不起作用,要么我只是不理解解决方案(我对Django /一般是Python)。

任何帮助或建议如何更好地实施,将不胜感激!

作业应用程序中的作业模型

from django.conf import settings
from django.db import models
from user.models import CustomUser

class Job(models.Model):
    """A model for active jobs"""
    job_title = models.CharField(max_length=200)
    author = models.ForeignKey(
        CustomUser, 
        null=True, 
        on_delete=models.SET_NULL, 
        related_name = 'authors'
        )  
    personnel = models.ForeignKey(
        CustomUser,
        null=True, 
        on_delete=models.SET_NULL, 
        related_name = 'addition_personnel'
        )
    job_text = models.TextField()
    created_date = models.DateTimeField(auto_now_add=True)  
    last_update = models.DateTimeField(null=True, auto_now=True) 
    close_date = models.DateField(null=True, blank=True)
    #  Job status choices 
    OPEN = 'Open'
    CLOSED = 'Closed'
    JOB_STATUS_CHOICES = (
        (OPEN, 'Open'),
        (CLOSED, 'Closed')
    )
    job_status = models.CharField(
        choices = JOB_STATUS_CHOICES,
        max_length = 10,
        null = True,
        blank = True,
        default = ''
    )

    def __str__(self):
        return self.job_title

用户应用中的CustomUser模型

from django.contrib.auth.models import AbstractUser

from django.db import models

class CustomUser(AbstractUser):
    """ custom user model """
    Position = models.CharField(max_length=100, null='', blank = True)

表单-将ModelForm与ModelMultipleChoiceField一起使用

from django import forms
from .models import Job
from user.models import CustomUser


class JobCreateForm(forms.ModelForm):
    """Create new job form"""
    personnel_queryset = CustomUser.objects.all()
    personnel = forms.ModelMultipleChoiceField(
        queryset=personnel_queryset,  
        widget=forms.CheckboxSelectMultiple(), 
        required=False
        )

    class Meta:
        model = Job
        fields = [
            'job_title',
            'job_text',
            'close_date',
            'job_status',
            'personnel'
        ]

和“查看摘要”

def job_create(request):
    """Job create form view"""
    if request.method == 'POST':
        form = JobCreateForm(request.POST)
        personnel = CustomUser.objects.all()
        if form.is_valid():
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.personnel = personnel
            new_job.save()  
            return redirect('job_detail', 
                            job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm() 
    return render(request, 'jobs/job_create.html', {'form':form})

1 个答案:

答案 0 :(得分:0)

我想我很怀疑/只是让它起作用。

我对人员与工作之间的关系进行了重新思考,并将其从Froeign密钥更改为多对多,因为Jobs可以分配许多人员,而人员可以分配给许多工作。

通过乔布斯模型。

...

personnel = models.ManyToManyField(CustomUser, blank=True)
...

然后使用此Trouble saving Django form: 'UserProfile' object has no attribute 'save_m2m' 以及有关模型表单和保存方法的主题 https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

我将视图更改为:

def job_create(request):
    """Job creation view with form"""
    #  if this is a POST request we need to process the form data 
    if request.method == 'POST':
        #  create a form instance and populate it with data from the request:
        form = JobCreateForm(request.POST)
        #  check whether form data is valid:
        personnel = CustomUser.objects.all()
        if form.is_valid():
            #  process the data in the form.cleaned_data as required
            # personnel_inst = CustomUser.objectss
            new_job = form.save(commit=False)
            new_job.author = request.user
            new_job.save()  
            form.save_m2m()
            return redirect('job_detail', job_details_id=new_job.pk)
    #  if a GET (or any other mehtod) blank form is created
    else:
        form = JobCreateForm() 
    return render(request, 'jobs/job_create.html', {'form':form})