我是 Django 新手,只是尝试使用 ModelForms 提交表单以创建新事件并将其保存到数据库中。
我正在尝试将行插入三个表:Location、Event(具有 location_id FK)和 EventSchedule(作为 event_id FK)。
这是保存表单的方法。当它被调用时,不会返回错误,但是新的行不会插入到数据库中。:
addNewEvent()(在views.py中)
def addNewEvent(self, event_form, location_form, event_sched_form, latitude, longitude):
new_event = event_form.save(commit=False)
new_location = location_form.save(commit=False)
new_event_sched = event_sched_form.save(commit=False)
# set any necessary values and save forms
new_location.latitude = latitude
new_location.longitude = longitude
new_location.save()
new_event.flagged = False
new_event.location = new_location
new_event.save()
new_event_sched.event = new_event
new_event_sched.save()
模型.py
class Location(models.Model):
name = models.CharField(max_length=200)
#address = models.CharField(max_length=200)
city = models.CharField(max_length=200)
state_code = models.CharField(max_length=100)
zip = models.CharField(max_length=100, blank=True)
country = models.CharField(max_length=100)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
class Meta:
db_table = 'location'
class Event(models.Model):
CATEGORIES = (
('KID', 'Kids'),
('FAM', 'Family'),
('NIT', 'Nightlife'),
('OUT', 'Outdoors'),
('ART', 'Arts'),
('MSC', 'Music'),
('SPT', 'Sports'),
('SAL', 'Sale'),
('EDU', 'Educational'),
('POL', 'Political'),
('FOD', 'Food'),
('OTH', 'Other')
)
location = models.ForeignKey(Location)
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
category = models.CharField(max_length=20, choices=CATEGORIES)
age_req = models.IntegerField(null=True)
cost_per_person = models.DecimalField(max_digits=5, decimal_places=2, null=True)
flagged = models.BooleanField()
users = models.ManyToManyField(User, through='UserEvent')
class Meta:
db_table = 'event'
class EventSchedule(models.Model):
event = models.ForeignKey(Event)
start_date_time = models.DateTimeField()
end_date_time = models.DateTimeField()
class Meta:
db_table = 'event_schedule'
表格.py
from django.forms import ModelForm, forms from models import Event, Location, EventSchedule
class EventForm(ModelForm):
class Meta:
model = Event
fields = ('name','description','category','age_req','cost_per_person')
class LocationForm(ModelForm):
class Meta:
model = Location
fields = ('name','city','state_code','zip','country')
class EventScheduleForm(ModelForm):
class Meta:
model = EventSchedule
fields = ('start_date_time', 'end_date_time')
任何帮助深表感谢。
谢谢,
彼得
编辑:
我什至无法保存模型,更不用说 ModelForm(即使我在其他地方成功地做到了)。我添加了以下代码以将用户与事件相关联。没有错误,但它不会向数据库添加一行:
new_user_event = UserEvent(user=user,
event=new_event,
datetime_created=datetime.datetime.now())
new_user_event.save()
有任何想法吗?
编辑2:
new_user_event 截图:http: //imgur.com/JUauG
编辑 3:
这就是我实例化 ModelForms 的方式:
event_form = EventForm(request.POST or None)
location_form = LocationForm(request.POST or None)
event_sched_form = EventScheduleForm(request.POST or None)