【问题标题】:"<Comment: >" needs to have a value for field "id" before this many-to-many relationship can be used?“<Comment: >”需要字段“id”的值才能使用这种多对多关系?
【发布时间】:2020-02-15 23:51:20
【问题描述】:

我刚开始使用(多对多)关系, 我需要允许用户可以在用户帖子上发表评论。这个网站看起来像 Quora 或 StackOverflow 用户应该注册以获取问题字段以提出他的问题和其他用户的网站可以离开那里 cmets。
那么,我怎样才能通过添加(添加)在(多对)中继续-many) 或真正的问题是:如何在此代码中添加(多对多)注释 如果有人帮我完成这个问题,请。

views.py

from django.shortcuts import render, redirect, get_list_or_404
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from django.contrib.auth.decorators import login_required


@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')
    all_objects = get_list_or_404(all_objects)
    return render(request, 'community/user_questions.html', {'all_objects': all_objects})


def question_view(request, user_id):
    my_question = UserAsking.objects.get(pk=user_id) # question number e.g '1' for user 'medoabdin'
    comment_form = CommentForm

    if request.method == 'GET':
        comment_form = comment_form(request.GET)
        if comment_form.is_valid():
            comments = comment_form.save(commit=False)
            comments.comment = comment_form.cleaned_data['comment']
            # comments is the value of data
            comments.userasking.add()
            #users = User.objects.filter(username=request.user) # medoabdin
            #comments = Comment.objects.create(userasking=my_question, comment=comments)
            #comments.userasking.set(users)
            #comments.userasking.add(*users)

    return render(request, 'community/question_view.html', {'my_question': my_question, 'comment_form': comment_form})

models.py

from django.db import models
from account.models import UserProfile
from django.db.models.signals import post_save

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')

    def __str__(self):
        return self.title


class Comment(models.Model):
    userasking = models.ManyToManyField(UserAsking)
    comment = models.TextField(max_length=500, blank=True)

    def __str__(self):
        return self.comment

forms.py

from django import forms
from .models import UserAsking, Comment


class UserAskingForm(forms.ModelForm):
    title = forms.CharField(required=True,
                            widget=forms.TextInput(attrs={'placeholder': 'Type Your Title...',
                                                          'class': 'form-control',
                                                          'data-placement': 'top',
                                                          'title': 'type your title',
                                                          'data-tooltip': 'tooltip'
                                                          }),
                            help_text='Be specific and imagine you’re asking a question to another person')
    question = forms.CharField(required=True,
                               widget=forms.Textarea(attrs={'placeholder': 'Type Your Details Of Your Question...',
                                                            'class': 'form-control',
                                                            'data-placement': 'top',
                                                            'title': 'type your question simply',
                                                            'data-tooltip': 'tooltip'
                                                            }),
                               help_text='Include all the information someone would need to answer your question')

    class Meta:
        model = UserAsking
        fields = '__all__'
        exclude = ['userprofile']


class CommentForm(forms.ModelForm):
    comment = forms.CharField(max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': 'Type your comment simply',
                                                                                           'class': 'form-control'}))

    class Meta:
        model = Comment
        fields = ['comment']

【问题讨论】:

    标签: django many-to-many


    【解决方案1】:

    您首先将对象保存到数据库,然后才能在关系中使用它:

    def question_view(request, user_id):
        my_question = UserAsking.objects.get(pk=user_id)
        comment_form = CommentForm
        if request.method == 'GET':
            comment_form = comment_form(request.GET)
            if comment_form.is_valid():
                comments = comment_form.save()
                comments.userasking.add(my_question)
        # …

    话虽如此,我觉得很奇怪QuestionUserAsking 之间存在多对多关系。这是否意味着同一个评论可以与多个UserAsking 对象相关?

    【讨论】:

    • 我做了一个与 UserAsking 关联的关系,以使所有用户都有权创建 cmets。在这种情况下,每个用户在同一个问题上都会有很多 cmets 要做……如果您看到另一种正确的方式,我会听到 .. 我照您说的做了,但每次我都重新加载。该页面创建了新的 cmets 我该如何阻止它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多