Django更新具有唯一字段的模型

时间:2017-07-29 03:42:00

标签: python django

我正在尝试允许用户编辑主题。每当我尝试更新主题时,我都会收到以下错误:

标题:已存在此标题的主题。

# views.py
...
def post(self, request, title):
    topic = Topic.objects.all().get(title=title)
    form = self.form_class(request.POST)
    if (form.is_valid()):
        topic.update(
            title=form.cleaned_data('title'),
            tags=form.cleaned_data('tags'),
        )
        return redirect('/topics/' + topic.title)
    else:
        return render(request, self.template_name, {'topic': topic, 'form': form})

# models.py
class Topic(models.Model):
    ...
    title = models.CharField(max_length=256, unique=True)
    ...

# forms.py
class EditTopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = [
            'title',
            'tags',
        ]
        widgets = {
            'tags': TagWidget(),
        }

1 个答案:

答案 0 :(得分:0)

只要您拥有unique=True,它将不断为您提供该错误报告 我所做的是从模型字段中删除unique=True, 并在create view类中检查了views.py:

from django.contrib import messages

if form.is_valid(): topic = Topic.objects.all() title_checker = form.cleaned_data['title'] for title in topic: if title == title_checker: messages.info(self.request, "THIS TITLE ALREADY EXISTS!!") return redirect('your-topic-create-page')

与此相关,无法创建现有的主题标题,并且如果不将检查器代码段代码放在更新视图中,则可以轻松地更新