代码之家  ›  专栏  ›  技术社区  ›  Abdelhamed Abdin

我该如何解决这个问题:NOT NULL约束失败错误?[姜戈]

  •  1
  • Abdelhamed Abdin  · 技术社区  · 4 年前

    以前我创建了user_id来定位URL中的问题,现在当我使用user_id时,我用user_slug替换了user_id,我必须使用以下行:
    comment_form.instance.userasking_id=user_id

    现在我必须使用user_slug,但它返回了错误:
    NOT NULL约束失败:community_comment.userasking_id

    据我所知,它希望我通过参数传递id,但我没有,因为我使用了user_slug,所以,我该如何解决这个问题?

    views.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 %}
    

    models.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
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Pavan kumar    4 年前

    由于您有blank=True和unique=True,因此在某些模型字段中,django将None或blank视为唯一条目。删除唯一约束并处理代码中的唯一性部分。 more info 如果你确定 want to use unique key 使用字符字段(唯一=True,空=True,空白=True)