即使从表单传递数据后,我也收到NOT NULL约束错误。我使用ajax发布数据。我检查了request.POST和网络请求选项卡。两者都显示store_contact_number中包含数据。
这是我的代码
class ListStore(FormView):
form_class = StoreForm
template_name = 'Store/list-store.html'
def form_invalid(self, form):
if self.request.is_ajax():
print('ajax form error', form.errors)
response = {
'error': form.errors
}
return JsonResponse(response, status=400)
else:
return super(ListStore, self).form_invalid(form.errors)
def form_valid(self, form):
success_message = "Thank you for listing your store. We Welcome you."
store, created = Store.objects.get_or_create(merchant=self.request.user)
if self.request.is_ajax():
response = {
'result': success_message
}
return JsonResponse(response)
else:
message.success(self.request, success_message)
return self.render_to_response(self.get_context_data())
class Store(models.Model):
merchant = models.ForeignKey(User, blank=False, null=False)
token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False)
name_of_legal_entity = models.CharField(max_length=250, blank=False, null=False)
pan_number = models.CharField(max_length=20, blank=False, null=False)
registered_office_address = models.CharField(max_length=200)
name_of_store = models.CharField(max_length=100)
email = models.EmailField(blank=False, null=False)
store_contact_number = models.PositiveIntegerField(blank=False, null=False)
$('.list-store-form').on('submit', function(event) {
event.preventDefault(); // preventing from the brwoser default behavior for form submission
var form = $(this);
console.log(form);
$.ajax({
async: true,
url: form.attr('action'),
data: form.serialize(),
type: 'POST',
dataType: 'json',
headers: {
'X-CSRFToken': window.csrf_token
},
success: function(data) {
if (data.form_is_valid) {
alert('Store Listed');
}
// $('.display').html(
// "<div class='ui floating message'> <i class='close icon'></i>" + data.result + '</div>'
// );
},
错误在store_contact_number中显示为
/ list / store中的IntegrityError NOT NULL约束失败: Store_store.store_contact_number
<QueryDict: {'store_contact_number': ['98489678'], 'email': ['admin@gmail.com'], 'registered_office_address': ['Delhi'], 'csrfmiddlewaretoken': ['kSaPMgNt'], 'name_of_store': ['BigMart'], 'pan_number': ['98713962'], 'name_of_legal_entity': ['BigMart Pvt Ltd']}>
表格
class StoreForm(forms.ModelForm):
class Meta:
model = Store
exclude = ('is_active', 'token', 'merchant',)
答案 0 :(得分:1)
您需要在store = form.save()
方法的开头添加form_valid
并删除行store, created = Store.objects.get_or_create(merchant=self.request.user)
。
编辑:实际上并不是那么简单,因为form.save()也会因为没有指定merchant
字段而失败。您需要覆盖表单的__init__
或save
方法,以便传入商家。
类似的东西:
def save(self, merchant, *args, **kwargs):
commit = kwargs.pop('commit', True)
kwargs['commit'] = False
store = super().save(*args, **kwargs)
store.merchant = merchant
if commit:
store.save()
return store
然后使用:
调用它def form_valid(self, form):
store = form.save(merchant=self.request.user)
success_message = "Thank you for listing your store. We Welcome you."
if self.request.is_ajax():
response = {
'result': success_message
}
return JsonResponse(response)
else:
message.success(self.request, success_message)
return self.render_to_response(self.get_context_data())