Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.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 - Fatal编程技术网

Python 如何为每个用户设置权限?

Python 如何为每个用户设置权限?,python,django,Python,Django,我需要设置权限,例如:如果我的网站上有两个用户,他们都有权写文章,他们可以删除或编辑他们的文章。那么,我如何设置“删除”或“编辑”按钮而不使网站上的所有用户都可以访问该按钮?只需使发布该帖子的用户可以访问该按钮 问题_view.html {% extends 'base.html' %} {% block title %} This Question Belong To User: {{ request.user }} {% endblock %} {% block body %} &

我需要设置权限,例如:如果我的网站上有两个用户,他们都有权写文章,他们可以删除或编辑他们的文章。那么,我如何设置“删除”或“编辑”按钮而不使网站上的所有用户都可以访问该按钮?只需使发布该帖子的用户可以访问该按钮

问题_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>&nbsp; | &nbsp;
                    <a href="">Edit</a>
                    <span>
                        <a href="">Like</a>&nbsp; | &nbsp;
                        <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 %}
帐户模型

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})
从django.shortcuts导入渲染,重定向
从.forms导入UserAskingForm、CommentForm
from.models导入UserAsking,Comment
从account.models导入UserProfile
从django.contrib.auth.decorators导入所需的登录名
从django.http导入HttpResponse
@需要登录
def用户_询问(请求):
form=UserAskingForm
如果request.method==“POST”:
form=UserAskingForm(request.POST,instance=request.user.userprofile)
如果form.is_有效():
asking=form.save(commit=False)
asking.title=form.cleaned_数据['title']
asking.question=form.cleaned_数据['question']
asking.field=form.cleaned_数据['field']
asking=UserAsking.objects.create(userprofile=request.user.userprofile,
title=asking.title,
问题,
字段=询问。字段)
询问。保存()
返回重定向('社区:用户\问题')
其他:
form=UserAskingForm()
返回呈现(请求,'community/asking_question.html',{'form':form})
返回呈现(请求,'community/asking_question.html',{'form':form})
@需要登录
def用户_问题(请求):
all_objects=UserAsking.objects.all().order_by('-title'))
如果不是所有_对象:
返回HttpResponse('此页面还没有任何问题')
返回呈现(请求'community/user_questions.html',{'all_objects':all_objects})
def问题视图(请求、用户id):
my_question=UserAsking.objects.get(pk=user_id)#问题编号,例如用户“medoabdin”的“1”
注释形式=注释形式
comments=Comment.objects.filter(userasking\uuu title=my\u question.title)
上下文={'my_question':my_question,'comment_form':comment_form,
“注释”:注释}
#添加注释
如果request.method==“POST”:
评论表单=评论表单(request.POST)
如果注释形式有效():
comment\u form.instance.userasking\u id=用户\u id
注释\表单保存()
返回重定向('社区:问题视图',用户id)
返回呈现(请求“community/question_view.html”,上下文)
@需要登录
def delete_post(请求,post_id=None):
post\u to\u delete=UserAsking.objects.get(id=post\u id)
all_objects=UserAsking.objects.all()
尝试:
post_to_delete.delete()
返回重定向('community:user\u asking')
除:
HttpResponse(“出了什么问题”)
返回呈现(请求'community/user_questions.html',{'all_objects':all_objects})

在您的视图中,您应该传递对象(例如,此处张贴)和请求的用户,然后在编辑链接的模板代码中使用if语句检查张贴的作者是否是请求的用户:

{{ if user == userasking.userprofile.user }}
    <a href="">Edit</a>
{{if user==userasking.userprofile.user}

在您的视图中,您应该传递对象(例如,此处张贴)和请求的用户,然后在编辑链接的模板代码中使用if语句检查张贴的作者是否是请求的用户:

{{ if user == userasking.userprofile.user }}
    <a href="">Edit</a>
{{if user==userasking.userprofile.user}

{%if post.userprofile.user==user%}
将检查帖子是否属于该用户(假设
user
是您的
请求。user
)。它不起作用??模板中您帖子的变量名是什么?用户是在您的上下文中定义的吗?(是否
if user.is\u authenticated
work?)显示模板的其余部分,但问题视图已显示特定用户的问题(您传递了用户id)。如果这只是显示当前登录用户的问题,为什么不在视图中检查user_id==request.user.id?如果这应该显示给任何用户,那么您可以在模板中检查
myquestion.userprofile.user==request.user
{%if post.userprofile.user==user%}
将检查帖子是否属于该用户(假设
user
是您的
请求。user
).它不起作用??模板中的帖子变量名是什么?用户是在您的上下文中定义的吗?(是否
if user.is\u authenticated
work?)显示模板的其余部分,但问题视图已显示特定用户的问题(您传递了用户id)。如果这只是显示当前登录用户的问题,为什么不在视图中检查user_id==request.user.id?如果这应该显示给任何用户,那么在模板中,您可以检查
myquestion.userprofile.user==request.user
。您在第一部分是正确的。在第二部分,为什么它不起作用?你确定userasking.userprofile.user设置正确吗?第一部分你说得对。在第二部分中,为什么它不起作用?您确定userasking.userprofile.user设置正确吗?