Мне нужно установить разрешение, например: если у меня есть два пользователя на моем веб-сайте, и у них обоих есть право написать сообщение, и они могут удалять или редактировать свои сообщения. Итак, как я могу установить кнопку удаления или редактирования, не делая ее доступной для всех пользователей на сайте, просто сделать ее доступной для пользователя, который сделал сообщение
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">
{% if user.is_authenticated %}
<a data-showin=".my-form" class="showin">Comment</a> |
<a href="">Edit</a>
<span>
<a href="">Like</a> |
<a href="">Unlike</a>
</span>
{% endif %}
</div>
<hr>
<!-- Comment Text -->
<div class="user-answer">
<div class="row">
<div class="col-xs-12">
{% for comment in comments %}
<p>{{ comment }}</p>
<p>1 hour ago</p>
{% endfor %}
</div>
</div>
</div>
<!-- Comment Field -->
{% include 'community/comment_form.html' %}
</div>
</div>
{% endblock %}
community.models
from django.db import models
from account.models import UserProfile
from django.contrib.auth.models import User
from django.utils import timezone
import django
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.ForeignKey(UserAsking, on_delete=models.CASCADE)
comment = models.TextField(max_length=500, blank=True, null=True)
def __str__(self):
return self.comment
account.models
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)
если вы не возражаете, мне нужно объяснить это здесь ... я понятия не имею о файлы я могу прикрепить, но я думаю, что если вы понимаете, что мне нужно, вы можете попросить меня помочь
Большое спасибо
community.views.py
from django.shortcuts import render, redirect
from .forms import UserAskingForm, CommentForm
from .models import UserAsking, Comment
from account.models import UserProfile
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
@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')
if not all_objects:
return HttpResponse('<h1>This page Have no any question yet</h1>')
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
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.save()
return redirect('community:question_view', user_id)
return render(request, 'community/question_view.html', context)
@login_required
def delete_post(request, post_id=None):
post_to_delete = UserAsking.objects.get(id=post_id)
all_objects = UserAsking.objects.all()
try:
post_to_delete.delete()
return redirect('community:user_asking')
except:
HttpResponse('something wrong')
return render(request, 'community/user_questions.html', {'all_objects': all_objects})