Django - / add_location / findlocation_app_location.user_id中的IntegrityError可能不是NULL

时间:2016-05-19 13:48:15

标签: django

models.py:

from django.contrib.auth.models import User

class Location(models.Model):
    user = models.ForeignKey(User)
    ...
    ...

views.py:

class AddLocationPageView(CreateView):
    model = Location
    form_class = LocationForm
    template_name = 'add_location.html'
    success_url = '/add_location/location_added/'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(AddLocationPageView, self).dispatch(*args, **kwargs)

forms.py:

from multiupload.fields import MultiFileField
from .models import Location, LocationType, Equipment, VisitTime, Photo


class LocationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)

        self.fields["types"].queryset = LocationType.objects.all()
        self.fields["equipment"].queryset = Equipment.objects.all()
        self.fields["visit_times"].queryset = VisitTime.objects.all()


    class Meta:
        model = Location
        fields = ['name', 'types', 'equipment', 'visit_times', 'keywords', 'description']

        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Напр. Стоунхендж'}),
            'keywords': forms.TextInput(attrs={'placeholder': 'Напр. море, побережье, скалы'}),
            'description': forms.Textarea(attrs={'placeholder': 'Любая информация, которую посчитаете нужной'}),
            'types': forms.CheckboxSelectMultiple(),
            'equipment': forms.CheckboxSelectMultiple(),
            'visit_times': forms.CheckboxSelectMultiple(),
        }

    photos = MultiFileField(min_num=1, max_num=10)

    def save(self, commit=True):
        instance = super(LocationForm, self).save(commit)
        for each in self.cleaned_data['photos']:
            Photo.objects.create(photo=each, location=instance)

        return instance

urls.py:

url(r'^add_location/$', AddLocationPageView.as_view(), name='add_location'),

当我尝试保存位置表单时,我看到错误。 为了摆脱这个麻烦,我必须做些什么? 任何建议将非常感谢!

非常感谢!

我在下面添加了追溯以获得更清晰。

回溯:

File "C:\commercial_projects\fl\lib\site-packages\django\core\handlers\base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\base.py" in view
      71.             return self.dispatch(request, *args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\utils\decorators.py" in _wrapper
      34.             return bound_func(*args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
      22.                 return view_func(request, *args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\utils\decorators.py" in bound_func
      30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
    File "C:\commercial_projects\fl\src\findlocation_app\views.py" in dispatch
      43.         return super(AddLocationPageView, self).dispatch(*args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\base.py" in dispatch
      89.         return handler(request, *args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in post
      249.         return super(BaseCreateView, self).post(request, *args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in post
      215.             return self.form_valid(form)
    File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in form_valid
      193.         self.object = form.save()
    File "C:\commercial_projects\fl\src\findlocation_app\forms.py" in save
      33.         instance = super(LocationForm, self).save(commit)
    File "C:\commercial_projects\fl\lib\site-packages\django\forms\models.py" in save
      459.                              construct=False)
    File "C:\commercial_projects\fl\lib\site-packages\django\forms\models.py" in save_instance
      105.         instance.save()
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in save
      734.                        force_update=force_update, update_fields=update_fields)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in save_base
      762.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in _save_table
      846.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in _do_insert
      885.                                using=using, raw=raw)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\manager.py" in manager_method
      127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\query.py" in _insert
      920.         return query.get_compiler(using=using).execute_sql(return_id)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
      974.                 cursor.execute(sql, params)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
      79.             return super(CursorDebugWrapper, self).execute(sql, params)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
      64.                 return self.cursor.execute(sql, params)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\utils.py" in __exit__
      98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
      64.                 return self.cursor.execute(sql, params)
    File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
      318.         return Database.Cursor.execute(self, query, params)

    Exception Type: IntegrityError at /add_location/
    Exception Value: findlocation_app_location.user_id may not be NULL                                               

1 个答案:

答案 0 :(得分:3)

你必须先了解问题所在。您在模型中有user字段的外键,但您在表单中将其排除在外。由于user字段不能为空,因此数据库将拒绝您的保存。要为ModelForm设置外键,您应该覆盖form_valid方法:

class AddLocationPageView(CreateView):
    model = Location

    def form_valid(self, form):
        location = form.save(commit=False)
        location.user = self.request.user
        return super(CreateArticle, self).form_valid(form)

您还可以在表单中加入user,这样您的表单会在您保存时包含信息,因此不会更改代码。但我打赌这不是你想要的,因为那时你的表单会显示一个下拉菜单,让你选择一个没有意义的用户。

请参阅django doc what's going on with commit=False