我尝试附加要与表单一起保存的用户数据。但是我得到了一个非空约束错误,我不明白,因为它似乎不是一个空约束。 "列中的空值" user_id"违反了非空约束"
查看:
class SupplierOnlineAccountView(CreateView):
form_class = SupplierOnlineAccountForm
template_name = 'standard_form.html'
success_url = '../contacting'
def form_valid(self, form):
if self.request.user.is_authenticated():
form.instance.user = self.request.user
else:
form.instance.temp_user = self.request.session.session_key
form.instance.service_type = self.request.session['service_type']
form.instance.online_account = self.request.session['online_account']
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
self.object = form.save()
api(username, password, self.object)
return super().form_valid(form)
形式:
class SupplierOnlineAccountForm(forms.ModelForm):
supplier_list = Supplier.objects.all()
supplier = forms.ModelChoiceField(queryset=supplier_list, empty_label=None, to_field_name='name')
class Meta:
model = SupplierAccount
fields = ['supplier', 'username', 'password']
型号:
class SupplierAccount(models.Model):
service_type = models.CharField(max_length=10, null=True)
online_account = models.BooleanField()
supplier = models.ForeignKey(Supplier)
tariff = models.ForeignKey(Tariff, null=True)
tariff_prices = models.ForeignKey(TariffPrices, null=True)
p_usage = models.ForeignKey(PowerUsage, null=True)
g_usage = models.ForeignKey(GasUsage, null=True)
username = models.CharField(max_length=255, null=True)
password = models.CharField(max_length=255, null=True)
user = models.ForeignKey(EUser)
def __str__(self):
return self.service_type
class EUser(models.Model):
address = models.ForeignKey(Address, null=True)
temp_user = models.CharField(max_length=255, null=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, default=None)
title = models.CharField(max_length=10)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
def __str__(self):
return str(self.user)
错误:
Traceback (most recent call last):
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (6, t, ytest@yahoo.com, testpass, null, null, 2, null, null, null, D).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/contextlib.py", line 30, in inner
return func(*args, **kwds)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/views/generic/edit.py", line 256, in post
return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/views/generic/edit.py", line 222, in post
return self.form_valid(form)
File "/Users/B/Library/Mobile Documents/com~apple~CloudDocs/PycharmProjects/switcher5/euser/views.py", line 58, in form_valid
self.object = form.save()
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/forms/models.py", line 451, in save
self.instance.save()
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/base.py", line 812, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/base.py", line 851, in _do_insert
using=using, raw=raw)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 159, in execute
return self._record(self.cursor.execute, sql, params)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/debug_toolbar/panels/sql/tracking.py", line 101, in _record
return method(sql, params)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Users/B/.virtualenvs/switcher5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (6, t, ytest@yahoo.com, testpass, null, null, 2, null, null, null, D).
答案 0 :(得分:1)
您的视图在保存表单时不需要用户,但模型会这样做,因为ForeignKey到EUser没有null = True。如果要允许用户未经过身份验证的情况,则需要在user
外键上设置该属性。