尝试使 request.user="m2mFormfield" 获取 ValueError 需要在字段 "project" 中有一个值,然后才能使用这种多对多关系

trying to make request.user="m2mFormfield" get ValueError needs to have a value for field "project" before this many-to-many relationship can be used

我在尝试让我的表单字段之一自动填写当前登录用户时遇到此错误,这是我的代码

models.py

class Project(models.Model):
    project_category = models.ForeignKey(Category)
    project_name = models.CharField(max_length=200)
    project_maker = models.ManyToManyField(User)
    pub_date = models.DateTimeField('date published')
    project_detail = RichTextField(config_name='default')
    def __unicode__(self):
        return self.project_name

forms.py

class StartProjectForm(forms.ModelForm):
class Meta:
    model = Project
    fields = ('project_category','project_name','project_detail')

views.py

@login_required
def StartProjectFormView(request,pk):

if request.method == "POST":
    form = StartProjectForm(request.POST)
    #form with data
    if form.is_valid():
        project_form = form.save(commit=False)
        project_form.project_maker = request.user
        #this line start the error
        project_form.pub_date = datetime.now()
        project_form.save()
        form.save_m2m()
        #don't know why can't use project_form.save_m2m here

        return redirect('boodemo:project_status', pk=project_form.pk)
else:
    form = StartProjectForm()
    #empty form
return render(request, 'boodemo/start_project.html', {'form': form,})

这是错误日志

    Environment:


Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'boodemo',
 'bootstrap3',
 'ckeditor')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.locale.LocaleMiddleware')


Traceback:
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/home/ubuntu/virtualproject/venv/bootsdemo/boodemo/views.py" in StartProjectFormView
  211.                 project_form.project_maker = request.user
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
  1185.         manager = self.__get__(instance)
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__
  1175.             through=self.field.rel.through,
File "/home/ubuntu/virtualproject/venv/lib/python2.7/site-packages/django/db/models/fields/related.py" in __init__
  831.                                  (instance, source_field_name))

Exception Type: ValueError at /demo/newproject/1
Exception Value: "<Project: test auto maker 12>" needs to have a value for field "project" before this many-to-many relationship can be used.

一切正常,直到我添加 project_form.project_maker = request.user 我已经尝试了一些解决方案,比如向 form.py 添加一个参数,比如

class StartProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ('project_category','project_name','project_detail')
#   def __init__(self, *args, **kwargs):
#        self.user = kwargs.pop('user', None)

#        super(StartProjectForm, self).__init__(*args, **kwargs)

该行有 # 确实消除了错误,但仍然没有保存在 project_maker 字段中

因为你有一个ManyToMany,你需要先保存实例,然后才能添加关系。如果您有 ForeignKeyOneToOne,则不需要这样做。有关详细信息,请参阅 documentation on ManyToMany

要解决您的问题,请在添加用户之前先保存对象:

project_form = form.save(commit=False)
project_form.pub_date = datetime.now()
project_form.save()
project_form.project_maker.add(request.user) # This is how you use ManyToMany
project_form.save_m2m()