簡體   English   中英

我該如何解決這個問題:NOT NULL 約束失敗錯誤? [姜戈]

[英]How can I solve the problem: NOT NULL constraint failed error? [Django]

之前我創建了 user_id 來定位 URL 中的問題,現在當我使用 user_id 時,我將 user_id 替換為 user_slug 我必須使用以下行:
comment_form.instance.userasking_id = user_id

現在我必須使用 user_slug 但它返回了那個錯誤:
NOT NULL 約束失敗:community_comment.userasking_id

我知道它希望我通過參數傳遞 id 但我沒有,因為我使用了 user_slug 所以,我該如何解決這個問題?

視圖.py

from django.shortcuts import render, redirect
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from account.models import UserProfile
from django.contrib.auth.models import User


@login_required
def user_asking(request):
    form = UserAskingForm
    if request.method == 'POST':
        form = UserAskingForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            asking = form.save(commit=False)
            asking.title = form.cleaned_data['title']
            asking.question = form.cleaned_data['question']
            asking.field = form.cleaned_data['field']
            asking = UserAsking.objects.create(userprofile=request.user.userprofile,
                                               title=asking.title,
                                               question=asking.question,
                                               field=asking.field)
            asking.save()
            return redirect('community:user_questions')
    else:
        form = UserAskingForm()
        return render(request, 'community/asking_question.html', {'form': form})

    return render(request, 'community/asking_question.html', {'form': form})


@login_required
def user_questions(request):
    all_objects = UserAsking.objects.all().order_by('-title')
    context = {
        'all_objects': all_objects,
    }
    return render(request, 'community/user_questions.html', context)


# Delete post
@login_required
def delete_post(request, post_id=None, **kwargs):
    post_to_delete = UserAsking.objects.get(id=post_id)
    my_post = UserAsking.objects.get(id=post_id)
    if request.user == my_post.userprofile.user:
        try:
            post_to_delete.delete()
            return redirect('community:user_asking')
        except:
            return HttpResponse('something wrong')
    else:
        return redirect('community:user_questions')

def question_view(request, user_slug):
    try:
        my_question = UserAsking.objects.get(ask_slug=user_slug) # question number e.g '1' for user 'medoabdin'
        # user_id = UserAsking.objects.get(id=my_question.id)
    except UserAsking.DoesNotExist:
        return HttpResponse('<h1>This Page Is Not Exist</h1>')
    comment_form = CommentForm
    comments = Comment.objects.filter(userasking__title=my_question.title)
    context = {'my_question': my_question, 'comment_form': comment_form,
               'comments': comments}
    # Add comment
    if request.method == 'POST':
        comment_form = comment_form(request.POST)
        if comment_form.is_valid():
            # comment_form.instance.userasking_id = user_id
            comment_form.instance.user_slug = user_slug
            comment_form.save()
            return redirect('community:question_view', my_question)

    return render(request, 'community/question_view.html', context)

comment_form.html

{% if user.is_authenticated %}
    <form method="post" action="" class="hide my-form">
        {% csrf_token %}
        <div class="row">
            {% for field in comment_form %}
            <div class="col-sm-10">
                <div class="form-group">
                    {{ field }}
                </div>
            </div>
            <div class="col-sm-1">
                <button type="submit" class="btn btn-primary btn-lg">Add Comment</button>
            </div>
            {% endfor %}
        </div>
    </form>
{% endif %}

模型.py

from django.db import models
from account.models import UserProfile
from django.contrib.auth.models import User
from django.utils import timezone
from django.template.defaultfilters import slugify

CHOICE = [('Technology', 'Technology'), ('Computer Science', 'Computer Science'),
          ('Lawyer', 'Lawyer'), ('Trading', 'Trading'),
          ('Engineering', 'Engineering'), ('Life Dialy', 'Life Dialy')
]


class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
    date = models.DateTimeField(auto_now_add=True)
    ask_slug = models.SlugField(max_length=100, unique=True, blank=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.ask_slug = slugify(self.title)
        super().save(*args, **kwargs)


class Comment(models.Model):
    userasking = models.ForeignKey(UserAsking, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    comment_slug = models.SlugField(max_length=100, unique=True, blank=True)

    def __str__(self):
        return self.comment

由於您有空白=True 和唯一=True,在某些 model 字段中,django 將無或空白視為唯一條目。 移除唯一性約束並處理代碼中的唯一性部分。 更多信息,如果您明確 想使用唯一鍵使用 Charfield(unique =True, null= True, blank = True)

暫無
暫無

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

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