我有一个 Django 表单来创建事件(在 UI 中运行良好),现在我正在创建单元测试。我的事件模型有两个外键字段:
category
和location
,分别指向模型Category
和Venue
。 Category
和 Venue
模型具有属性 public_id
以防止在选择表单中暴露真实 ID。
当我尝试测试表格时,我不知道如何让它通过。它在断言
assert form.errors == {}
中失败:
{'类别':['选择一个有效的选项。该选择不是可用选择之一。'], '位置':['选择一个有效的选择。该选项不是可用选项之一。']} != {}
class Event(BaseModel):
# Event information
name = fields.CharField(max_length=255)
category = models.ManyToManyField(Category, related_name="events")
location = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name="events")
start_date = models.DateTimeField()
# more fields
class EventCreateForm(forms.ModelForm):
category = forms.ModelChoiceField(
widget=forms.Select(),
to_field_name="public_id",
label=_("Category"),
)
location = forms.ModelChoiceField(
widget=forms.Select(),
to_field_name="public_id",
label=_("Venue"),
)
class Meta:
model = Event
fields = [
"name",
"category",
"location",
# more fields...
]
labels = {
"name",
# more fields...
}
widgets = {
"name",
# more fields...
}
class EventCreateView(LoginRequiredMixin, CreateView):
model = Event
form_class = EventCreateForm
template_name = "events/events_create.html"
def form_valid(self, form):
form.instance.created_by_id = self.request.user.id
form.instance.updated_by_id = self.request.user.id
form.instance = form.save()
form.instance.category.add(
Category.objects.get(public_id=form.data["category"])
)
return super().form_valid(form)
我有两个名为
venue
和category
的固定装置。他们工作得很好。
@pytest.mark.django_db
@pytest.mark.parametrize(
"name, start_date, category, venue",
[
("Event name", tz.now() + timedelta(days=10), "category", "venue",),
],
indirect=["category", "venue"],
)
def test_valid_form(name, start_time, category, venue):
"""Test the form with valid data."""
form = EventCreateForm(
data={
"name": name,
"start_date": start_date,
"category": category.public_id, # <-- This is my fixture `category`
"location": venue.public_id, # <-- This is my fixture `venue`
},
files={"image": image},
)
assert form.errors == {}
assert form.is_valid() is True
我正在尝试替换我的这部分测试代码:
"category": category.public_id,
"location": venue.public_id,
与:
"category": category,
"location": venue,
"category": category.id,
"location": venue.id,
"category": category.pk,
"location": venue.pk,
在我的尝试中,我试图评论表格的
to_field_name="public_id",
部分,但它没有解决问题。