Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我如何在一个与另一个模型存在多对多关系的应用程序上向用户添加评论?_Python_Django_Django Forms_Many To Many_Comments - Fatal编程技术网

Python 我如何在一个与另一个模型存在多对多关系的应用程序上向用户添加评论?

Python 我如何在一个与另一个模型存在多对多关系的应用程序上向用户添加评论?,python,django,django-forms,many-to-many,comments,Python,Django,Django Forms,Many To Many,Comments,我被卡住了。现在我有许多模型,它们在许多应用程序中都有关系,我将解释如下: -第一个模型是(UserProfile),它与(User)模型有(one-to-one)关系 另外,我有(UserAsking)与(UserProfile)有关系(ForeignKey),最后一部分是(Comment),它与(UserAsking)有(多对多)关系,我想发表一条评论,这条评论与UserAsking模型有关。我有麻烦了,我怎么办? 我发现(many-to-many)不同于任何其他关系,并且我无法在(Comm

我被卡住了。现在我有许多模型,它们在许多应用程序中都有关系,我将解释如下:
-第一个模型是(UserProfile),它与(User)模型有(one-to-one)关系
另外,我有(UserAsking)与(UserProfile)有关系(ForeignKey),最后一部分是(Comment),它与(UserAsking)有(多对多)关系,我想发表一条评论,这条评论与UserAsking模型有关。我有麻烦了,我怎么办?
我发现(many-to-many)不同于任何其他关系,并且我无法在(Comment)模型中获取实例作为参数
如果有人能给我帮助的话?
先谢谢你

account/models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

CHOICE = [('male', 'male'), ('female', 'female')]


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
    city = models.CharField(max_length=20, blank=False)
    phone = models.IntegerField(default=0, blank=True)
    sex = models.CharField(max_length=10, default='male', choices=CHOICE)
    skill = models.CharField(max_length=100, default='You have no skills yet')
    logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)

    def __str__(self):
        return self.user.username


def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])


post_save.connect(receiver=create_profile, sender=User)
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)
community/models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

CHOICE = [('male', 'male'), ('female', 'female')]


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
    city = models.CharField(max_length=20, blank=False)
    phone = models.IntegerField(default=0, blank=True)
    sex = models.CharField(max_length=10, default='male', choices=CHOICE)
    skill = models.CharField(max_length=100, default='You have no skills yet')
    logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)

    def __str__(self):
        return self.user.username


def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])


post_save.connect(receiver=create_profile, sender=User)
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)
community/views.py

from django.shortcuts import render, redirect, get_list_or_404
from .forms import UserAskingForm, CommentForm
from .models import UserAsking
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)
    comment_form = CommentForm
    #x = request.user.userprofile.userasking_set
    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']
            # you have to edit on userasking instance
            #comments = Comment.objects.create(userasking=request.user.userprofile.userasking_set, comment=comments)
            comments.save()
            #return render(request, 'community/question_view.html', {'x': x})

    return render(request, 'community/question_view.html', {'my_question': my_question,
                                                            'comment': comment_form})
社区/表格.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']
社区/question_view.html

{% extends 'base.html' %}
{% block title %} This Question Belong To User: {{ request.user }} {% endblock %}

{% block body %}
    <!-- Full Question View -->
    <div class="my_question">
        <div class="container">
            <div class="answer-question">
                <div class="row">
                    <div class="col-md-6 col-xs-12">
                        <div class="title">
                            <h3 class="text-primary">{{ my_question.title }}</h3>
                            <span class="clock">1 hour ago</span>
                        </div>
                        <div class="question">
                            <p class="">{{ my_question.question }}</p>
                        </div>
                        <div class="field">
                            <span>{{ my_question.field }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Options e.g 'Edit, Comment, Delete etc...' -->
    <div class="options">
        <div class="container">
            <div class="col-sm-12">
                <a data-showin=".my-form" class="showin">Comment</a>&nbsp; | &nbsp;
                <a href="">Edit</a>&nbsp; | &nbsp;
                <a href="">Delete</a>
                <span>
                    <a href="">Like</a>&nbsp; | &nbsp;
                    <a href="">Unlike</a>
                </span>
            </div>
            <hr>
            <!-- Comment Text -->
            <div class="user-answer">
                <div class="row">
                    <div class="col-xs-12">
                        {% for field in comment %}
                        <p>(medo) - sub comment</p>
                        <p>1 hour ago</p>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <!-- Comment Field -->
            {% include 'community/comment_form.html' %}
            {{ x }}
        </div>
    </div>
{% endblock %}
{%extends'base.html%}
{%block title%}此问题属于用户:{{request.User}}{%endblock%}
{%block body%}
{{my_question.title}
一小时前

{{my_question.question}

{{my_question.field} | |
{注释%中字段的%s} (medo)-子评论

一小时前

{%endfor%} {%include'community/comment_form.html%} {{x} {%endblock%}
community/comment_form.html

<form method="get" action="" class="hide my-form">
    {% csrf_token %}
    <div class="row">
        {% for field in comment %}
        <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>

{%csrf_令牌%}
{注释%中字段的%s}
{{field}}
添加注释
{%endfor%}
community/url.py

from . import views
from django.urls import path

app_name = 'community'

urlpatterns = [
    path('', views.user_questions, name='user_questions'),
    path('ask-question/', views.user_asking, name='user_asking'),
    path('ask-question/question-view/<int:user_id>/', views.question_view, name='question_view'),
]
来自。导入视图
从django.url导入路径
应用程序名称='社区'
URL模式=[
路径(“”,views.user\u questions,name='user\u questions'),
路径('ask-question/',views.user\u asking,name='user\u asking'),
路径('ask-question/question-view/',views.question\u view,name='question\u view'),
]

恐怕我还没有完全理解您的问题:是否要在问题中添加注释(
UserAsking
instance)?不,UserAsking作为我知道的注释的实例是不正确的。我需要为注释模型创建一个实例,以便能够为用户进行注释