我有这些模特,州和城市,
class State(models.Model):
name = models.CharField(max_length=255)
shortname = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=255)
state = models.ForeignKey(State)
def __unicode__(self):
return self.name
我得到一个“IntegrityError(1048,”列'state_id'不能为空“)”当我保存表单时,奇怪的是状态是创建的,这就是我在做什么
def form_valid(self, form):
city = form.cleaned_data['city_name']
state = form.cleaned_data['state_name']
m = State.objects.get_or_create(name=state)
state_id = m[0].id
City.objects.get_or_create(name=state, id=state_id)
form.save()
我能做什么?
class StoreForm(ModelForm):
class Meta:
model = Store
fields = '__all__'
class StoreGoogleMapForm(StoreForm):
city_name = forms.CharField(
widget=forms.TextInput(
attrs={'readonly': 'readonly'}
)
)
state_name = forms.CharField(
widget=forms.TextInput(
attrs={'readonly': 'readonly'}
)
)
class Meta(StoreForm.Meta):
exclude = (
'state', 'city'
)
widgets = {
'retailer': forms.HiddenInput(),
'lon': forms.HiddenInput(),
'lat': forms.HiddenInput(),
}
def clean(self):
cleaned_data = super(StoreGoogleMapForm, self).clean()
city_name = cleaned_data.get("city_name")
state_name = cleaned_data.get("state_name")
return cleaned_data
class NewStore(LoginRequiredMixin, CreateView):
model = Store
template_name = "new_store.html"
form_class = StoreGoogleMapForm
def get_context_data(self, **kwargs):
ctx = super(NewStore, self).get_context_data(**kwargs)
ctx['cobrand'] = self.retailer
return ctx
def get(self, request, *args, **kwargs):
self.retailer = get_object_or_404(Cobrand, pk=kwargs['pk'])
self.object = Store(retailer=self.retailer)
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def form_valid(self, form):
city = form.cleaned_data['city_name']
state = form.cleaned_data['state_name']
m = State.objects.get_or_create(name=state)
City.objects.get_or_create(name=city, state=m[0])
form.save()
messages.add_message(
self.request,
messages.SUCCESS,
'The store was successfuly created!',
extra_tags='success'
)
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse_lazy('store_list', kwargs={'pk': self.kwargs['pk']})
def post(self, request, *args, **kwargs):
self.retailer = get_object_or_404(Cobrand, pk=kwargs['pk'])
self.object = Store(retailer=self.retailer)
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
答案 0 :(得分:0)
将该行修改为
City.objects.get_or_create(name=city, state=m[0])
您不需要form.save()
。
无论如何,这段代码有点奇怪,你的表格怎么样?
答案 1 :(得分:0)
get_or_create返回两个参数https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create,然后您可以将对象直接传递到下一个语句。
state, created = State.objects.get_or_create(name=state)
City.objects.get_or_create(name=state, state=state)
怀疑你不应该在form_valid中这样做,但没有其余的代码,不能确定。