Я застрял. теперь у меня есть много моделей, которые связаны между собой во многих приложениях. Я объясню это следующим образом:
- первая модель ( UserProfile ), в которой ( один к одному *) 1005 *) связь с ( Пользователь ) моделью
также у меня есть ( UserAsking ), которая имеет отношение ( ForeignKey ) с ( UserProfile *) 1014 *) и последняя часть ( Комментарий ), которая имеет ( Многие ко многим ) отношения с ( UserAsking ).
в данном случае, я хочу сделать комментарий и этот комментарий, имеющий отношение к модели UserAsking . У меня проблемы, как я могу это сделать?
Я обнаружил, что ( многие-ко-многим ) отличается от любых других отношений, и я не могу получить экземпляр в качестве аргумента в ( Комментарий ) модель
если кто-нибудь может мне помочь?
спасибо заранее
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)
сообщество / модели .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)
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})
community / 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']
community / 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> |
<a href="">Edit</a> |
<a href="">Delete</a>
<span>
<a href="">Like</a> |
<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 %}
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>
community / urls.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'),
]