簡體   English   中英

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

[英]Django update model with unique field

我正在嘗試允許用戶編輯主題。 每當我嘗試更新主題時,我都會收到以下錯誤:

標題:具有此標題的主題已經存在。

# 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(),
        }

只要你有unique=True它就會一直給你那個錯誤報告我所做的是從模型字段中刪除unique=True ,並在創建視圖類中檢查 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')

這樣,就不會創建現有的主題標題,如果您不將檢查代碼段代碼放入更新視圖中,則可以輕松更新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM