Django 2.0:UpdateView创建一个新对象,而不是更新

时间:2018-10-22 15:12:11

标签: python django

由于某种原因,我的UpdateView正在创建新对象,而不是更新现有对象。我尝试将URL参数从slug更改为pk无济于事。

models.py

class EarthScienceEvents(models.Model):
    slug = models.SlugField("Slug", primary_key=True)
    name = models.CharField("Name", max_length=200)

forms.py

class EarthScienceEventForm(forms.ModelForm):
    class Meta:
        model = EarthScienceEvents
        fields = ['name']

urls.py

urlpatterns = [    
    path("update/<slug:pk>", views.EarthScienceEventsUpdateView.as_view(), name="update"),
]

views.py

class EarthScienceEventsUpdateView(UpdateView):
    model = EarthScienceEvents
    form_class = EarthScienceEventForm
    template_name = "earth_science_events/create_update.html"
    success_url = reverse_lazy('earth_science_events:list')

create_update.html

        <form action="" method='POST'>
            {% csrf_token %}
            {{ form | crispy }}
            <button type="submit">Update</button>
        </form>

编辑:

我也尝试过这样做,以明确定义要发布到的URL:

<form action="{% url 'earth_science_events:update' object.slug %}" method='POST'>
    {% csrf_token %}
    {{ form | crispy }}
    <button type="submit">Update</button>
</form>

这不能解决问题。

这里可能是什么问题?

0 个答案:

没有答案