Я новичок в использовании (многие-ко-многим) отношений, мне нужно разрешить пользователям оставлять комментарии к посту пользователя. этот сайт выглядит как Quora или StackOverflow, который пользователь должен зарегистрировать, чтобы получить поле вопросов, чтобы задать свой вопрос, и другим пользователям, которые на сайте могут оставлять там комментарии.
Итак, как я могу продолжить, добавив (добавить) в (много-к -мани) или реальный вопрос: как я могу добавить комментарий (многие ко многим) в этот код, если кто-нибудь поможет мне решить эту проблему, пожалуйста.
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']