gpt4 book ai didi

Django:无法在 CBV 中保存相关模型

转载 作者:行者123 更新时间:2023-12-04 05:32:41 26 4
gpt4 key购买 nike

我有两个与 this case 非常相似的模型:

class Location(models.Model):
city = models.CharField(max_length=20)
address = models.CharField(max_length=30)

class Event(models.Model):
location = models.ForeignKey(Location)
date = models.DateField()
user = models.ForeignKey(User)

我试图以形式保存这些对象:
class EventForm(forms.ModelForm):
city = forms.CharField(label=_('City'), max_length=30)
address = forms.CharField(label=_('Street'), max_length=30, required=False)

class Meta:
model = Event

def __init__(self, *args, **kwargs)
super(EventForm, self).__init__(*args, **kwargs)
try:
self.fields['city'].initial = self.instance.location.city
self.fields['address'].initial = self.instance.location.street
except AttributeError:
pass

def save(self, commit=True):
event = super(EventForm, self).save(commit=False)
location = event.location
location.city = self.cleaned_data['city']
location.address = self.cleaned_data['address']
location.save()
return event

这会引发错误 'NoneType' object has no attribute 'city'
我还尝试在 CBV 中保存位置:
class EventEdit(UpdateView):
model = Event

def form_valid(self, form):
event = form.save(commit=False)
location = event.location
location.city = self.cleaned_data['city']
location.address = self.cleaned_data['address']
location.save()
event.save()
return HttpResponseRedirect(self.get_success_url())

同样,同样的错误 'NoneType' object has no attribute 'city'
在基于类的 View 中保存相关对象的正确方法是什么?

更新

我必须补充一点,我正在询问更新分配给事件的现有位置。添加新的事件位置在 EventCreate(CreateView) 中完成完全一样 罗汉建议。
class EventCreate(CreateView):
def form_valid(self, form):
self.object = form.save(commit=False)
location = Location()
location.address = self.request.POST['address']
location.city = self.request.POST['city']
location.save()
self.object.location = location
self.object.save()
return HttpResponseRedirect(self.get_success_url())

最佳答案

在您的 save方法 event.location将是 None .您需要创建 location实例然后保存它。

更新:用于保存现有对象:

我不确定您对 UpdateView 的实现看完是一条路Generic views - Models

我建议将 View 更改为:

class EventEdit(UpdateView):
model = Event

def form_valid(self, form):
#instance trying to update
event = form.instance
location = event.location
if location == None:
location = Location()
location.city = self.cleaned_data['city']
location.address = self.cleaned_data['address']
location.save()
event.location = location
#event.save() instead of this do
super(EventEdit, self).form_valid(form)
return HttpResponseRedirect(self.get_success_url())

旧解决方案:

我会将保存方法更改为
def save(self, commit=True):
event = super(EventForm, self).save(commit=False)
location = Location()
location.city = self.cleaned_data['city']
location.address = self.cleaned_data['address']
location.save()
event.location = location
event.save()
return event

关于Django:无法在 CBV 中保存相关模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12381717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com