Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.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/Django我如何使它只有对象/帖子的创建者才能看到他们帖子的delete/edit函数按钮?_Python_Django - Fatal编程技术网

Python/Django我如何使它只有对象/帖子的创建者才能看到他们帖子的delete/edit函数按钮?

Python/Django我如何使它只有对象/帖子的创建者才能看到他们帖子的delete/edit函数按钮?,python,django,Python,Django,我目前是python开发新手,目前正在学校学习多个堆栈。我的代码是最基本的形式。我还没有得到认证,也没有人介绍我认识KWARGS或pk。我现在也不知道这些是什么。我该如何使“删除”按钮只显示在创建对象的用户的“思考”帖子的一侧,以便他们可以自己删除该对象,但该按钮不可用于其他用户的帖子?此外,我将如何实现一个“喜欢/不喜欢”按钮,以迄今为止我所学的最简单的形式为每个对象帖子来回转换?这是我当前的代码 型号.py from __future__ import unicode_literals fr

我目前是python开发新手,目前正在学校学习多个堆栈。我的代码是最基本的形式。我还没有得到认证,也没有人介绍我认识KWARGS或pk。我现在也不知道这些是什么。我该如何使“删除”按钮只显示在创建对象的用户的“思考”帖子的一侧,以便他们可以自己删除该对象,但该按钮不可用于其他用户的帖子?此外,我将如何实现一个“喜欢/不喜欢”按钮,以迄今为止我所学的最简单的形式为每个对象帖子来回转换?这是我当前的代码

型号.py

from __future__ import unicode_literals
from django.db import models
import re
import bcrypt

class UserManager(models.Manager):
    def registration_validator(self, postData):
        errors = {}
        EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
        if not EMAIL_REGEX.match(postData['email']):    # test whether a field matches the pattern            
            errors['email'] = ("Invalid email address!")
        if len(self.filter(email = postData['email'])) > 0:
            errors['email'] = "Email address has already been taken!"
        if len(postData['first_name']) < 2:
            errors["first_name"] = "Insufficient amount of character letters, you must type over 2 characters for your first name!"
        if len(postData['last_name']) < 2:
            errors["last_name"] = "Insufficient amount of character letters, you must type over 2 characters for your last name!"
        if len(postData['password']) < 8:
            errors["password"] = "Insufficient amount of character letters, you must type over 8 characters for your password!"
        if postData['password'] != postData['confpw']:
            errors["confpw"] = "Passwords do not match!"
        if (len(postData['first_name']) < 1) or (len(postData['last_name']) < 1) or (len(postData['password']) < 1) or (len(postData['confpw']) < 1) or (len(postData['email']) < 1):
            errors["empty_fields"] = "All fields require input to register!"
        return errors

class ThoughtManager(models.Manager):
    def thought_validator(self, postData):
        errors = {}
        if len(postData['desc']) < 5:
            errors['desc'] = "Insufficient amount of character letters, you must type over 5 characters for your description!"
        if len(postData['desc']) < 1:
            errors['desc'] = "Please provide a thought!" 
        return errors    

class User(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = UserManager()

class Thought(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    desc = models.CharField(max_length=255)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateField(auto_now=True)
    user = models.ForeignKey(User, related_name="thoughts")
    like = models.ManyToManyField(User, related_name="likes", blank=True)
    objects = ThoughtManager()

    def total_likes(self):
        return self.likes.count()
from django.shortcuts import render, HttpResponse, redirect
from .models import *
from django.contrib import messages
import bcrypt

# within index
def index(request):
    return render(request, "thought_board/index.html")

def register(request):
    errors = User.objects.registration_validator(request.POST)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value, extra_tags = key)
        return redirect('/')
    else:
        password = request.POST['password']
        pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
        user = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'], password=pw_hash)
        request.session['user_id'] = user.id
        return redirect('/thoughts')

def login(request):
        user = User.objects.filter(email=request.POST['email'])
        if not user:
            messages.error(request, "Invalid email!")
            return redirect('/')
        logged_user = user[0]
        if bcrypt.checkpw(request.POST['password'].encode(), logged_user.password.encode()):
            request.session['user_id'] = logged_user.id
            return redirect('/thoughts')
        else:
            messages.error(request, "Invalid email and/or password!")
            return redirect('/')

def logout(request):
    request.session.clear()
    return redirect('/')

#within thoughts
def thoughts(request):
    context = {
        "user": User.objects.get(id=request.session['user_id']),
        "thoughts": Thought.objects.all()
    }
    return render(request, "thought_board/thoughts.html", context)

def add(request):
    errors = Thought.objects.thought_validator(request.POST)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value, extra_tags = key)
        return redirect('/thoughts')
    else:
        Thought.objects.create(desc=request.POST['desc'], user=User.objects.get(id=request.session["user_id"]))
        return redirect('/thoughts')

def delete(request, id):
    thought = Thought.objects.get(id=id)
    thought.delete()
    return redirect('/thoughts')

#within views
def views(request, id):
    thought = Thought.objects.get(id=id)
    likes = thought.like.all()
    is_liked = likes.filter(id=id)
    is_liked = False
    if thought.like.filter(id=request.user.id).exists():
            is_liked = True
    context = {
        "thought": thought,
        "users": likes,
        "is_liked": is_liked,
        "logged_user": User.objects.get(id=request.session['user_id'])
    }
    return render(request, "thought_board/details.html", context)

def like(request, id):
    thought = Thought.objects.get(id=id)
    user = User.objects.get(id=request.session['user_id'])
    thought.like.add(user)
    return redirect('/thoughts/'+id)

def unlike(request, id):
    thought = Thought.objects.get(id=id)
    user = User.objects.get(id=request.session['user_id'])
    thought.like.remove(user)
    return redirect('thoughts/'+id) 
这是放置“删除”按钮的模板

thinks.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Thought Board</title>
</head>
<body>
<style>
.container{
    padding: 10px 0px 0px 0px;
}
.nav{
    float: right;
}
.button{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}
.header-desc{
    padding-bottom: 20px;
    width: 100%;
}
#desc-thoughts{
    width: 60%;
    border: 2px solid black;
    height: 32px;
    box-shadow: 3px 3px black;
}
#add-thoughts{
    margin-left: 20px;
    width: 120px;
    background-color: #2b78e4;
    border: solid black;
    box-shadow: 3px 3px black;
    color:white;
    font-size: 16px;
}
#text-area{
    border: 2px solid black;
    overflow-y: scroll;
    resize: none;
    height: 100px;
    width: 465px;
}
.inline-input{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.inline{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.p{
    width: 100px;
}
#thought-board{
    padding-top: 20px;
}
.details a{
    color: blue;
    text-decoration: underline;
    cursor: pointer;
    background: none;
    margin-left: 102px;
    font-size: 16px;
}
.delete{
    display: inline-block;
    margin-left: -100px;
}
.delete-btn{
    background-color: #cc0101;
    color: white;
    width: 100px;
}
#likes{
    margin-left: 455px;
    margin-top: -25px;
}
#line{
    border: 1px solid black;
    width: 750px;
}
</style>
    <div class="container">
        <div class="nav">
            <a href="/" class="button">Logout</a>
        </div>
        <h1>Hello {{user.first_name}} {{user.last_name}}!</h1>
        <div>
        {% if messages %}
        <ul class="messages">    
            {% for message in messages %}    
                <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>    
            {% endfor %}
        </ul>
        {% endif %}
            <form action="/thoughts/add/" method="POST">
            {% csrf_token %}
                <div class="header-desc">
                    <input type="text" id="desc-thoughts" name="desc" placeholder="Post a Great Thought Here!">
                    <button type="submit"  id="add-thoughts">Add Thought!</button>
                </div>
            </form>
        </div>
        <hr id="line" align="left">
        {% for thought in thoughts %}
        <div id="thought-board">
            <div class="inline-input p">
                <p id="p">{{thought.user.first_name}} says:</p>
            </div>
            <div class="inline">
                <textarea readonly id="text-area">{{thought.desc}}</textarea>
            </div>
            <div class="delete">
                <form action="/thoughts/{{thought.id}}/delete/">
                    <button type="submit" class="delete-btn">Delete</button>
                </form>
            </div>
            <div class="details">
                <a href="/thoughts/{{thought.id}}/" method="GET">Details</a>
                <p id="likes">{{thought.like.count}} people like this</p>
            </div>
        </div>
        {% endfor %}
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Thought Board</title>
</head>
<body>
<style>
.container{
    padding: 10px 0px 0px 0px;
}
.table-secondary{
    border: 2px solid black;
}
.table th{
    border: 2px solid black;
}
.table td{
    border: 2px solid black;
}
.nav{
    float: right;
}
.dashboard{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
    margin-right: 10px;
}
.logout{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}
#text-area{
    border: 2px solid black;
    overflow-y: scroll;
    resize: none;
    height: 100px;
    width: 555px;
    background-color: white;
}
.inline-input{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.label{
    width: 100px;
    text-align: right;
    margin-right: 10px;
}
.input{
    padding-top: 50px;
}
.btn{
    width: 80px;
    background-color: #009e0f;
    border: solid black;
    box-shadow: 3px 3px black;
    color:white;
    margin-left: 590px;
    margin-top: 5px;
}
.btn2{
    width: 80px;
    background-color: #ff9900;
    border: solid black;
    box-shadow: 3px 3px black;
    color:black;
    margin-left: 590px;
    margin-top: 5px;
}
.table{
    width: 59%;
}
</style>

    <div class="container">
        <div class="header float-right">
        <form action="/thoughts/" method="GET">
        {% csrf_token %}
            <a href="/thoughts/" class="dashboard">Dashboard</a>
            <a href="/" class="logout">Logout</a>
        </form>
        </div>
            <div class="input">
                <div class="inline-input label">
                    <label>{{thought.user.first_name}} says:</label>
                </div>
                <div class="inline-input">
                    <textarea id="text-area" readonly>{{thought.desc}}</textarea>
                </div>
            </div>
            <form action="/thoughts/{{thought.id}}/like/" method="POST">
                {% if is_liked == logged_user %}
                {% csrf_token %}
                <button type="submit" value="{{thought.id}}" class="btn">Like</button>
            </form>
                {% else %}
            <form action="/thoughts/{{thought.id}}/unlike/" method="POST">
                {% csrf_token %}
                <button type="submit" value="{{thought.id}}" class="btn2">Unlike</button>
                {% endif %}
            </form>
        <div class="people-likes">
            <table class="table table-bordered table-striped">
                <p>People who liked this thought:<p>
                <thead class="table-secondary">
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                </thead>
                {% for user in users %}
                    <tr>
                        <td>{{user.first_name}}</td>
                        <td>{{user.last_name}}</td>
                    </tr>
                {% endfor %}
            </table>
        </div>
        </form>
        </div>
    </div>
</body>
</html>

思想委员会
.集装箱{
填充:10px 0px 0px 0px;
}
.导航{
浮动:对;
}
.按钮{
字体大小:20px;
背景:无;
边界:无;
颜色:蓝色;
文字装饰:下划线;
光标:指针;
}
.标题说明{
垫底:20px;
宽度:100%;
}
#描述思想{
宽度:60%;
边框:2件纯黑;
高度:32px;
盒影:3px 3px黑色;
}
#添加想法{
左边距:20px;
宽度:120px;
背景色:#2b78e4;
边框:纯黑;
盒影:3px 3px黑色;
颜色:白色;
字体大小:16px;
}
#文本区{
边框:2件纯黑;
溢出y:滚动;
调整大小:无;
高度:100px;
宽度:465px;
}
.内联输入{
显示:内联块;
垂直对齐:顶部;
宽度:50%;
}
.内联{
显示:内联块;
垂直对齐:顶部;
宽度:50%;
}
p{
宽度:100px;
}
#思想委员会{
填充顶部:20px;
}
.详情a{
颜色:蓝色;
文字装饰:下划线;
光标:指针;
背景:无;
左边距:102px;
字体大小:16px;
}
.删除{
显示:内联块;
左边距:-100px;
}
.删除btn{
背景色:#cc0101;
颜色:白色;
宽度:100px;
}
#喜欢{
左边距:455px;
利润上限:-25px;
}
#线{
边框:1px纯黑;
宽度:750px;
}
你好{{user.first_name}{{user.last_name}}!
{%if消息%}
    {消息%中的消息为%s} {{message}} {%endfor%}
{%endif%} {%csrf_令牌%} 加上思想!
{%为思想中的思想%}

{{think.user.first_name}说:

{{think.desc}} 删除

{{think.like.count}像这样的人

{%endfor%}
这是一个按钮切换喜欢/不喜欢(或不喜欢)的地方

details.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Thought Board</title>
</head>
<body>
<style>
.container{
    padding: 10px 0px 0px 0px;
}
.nav{
    float: right;
}
.button{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}
.header-desc{
    padding-bottom: 20px;
    width: 100%;
}
#desc-thoughts{
    width: 60%;
    border: 2px solid black;
    height: 32px;
    box-shadow: 3px 3px black;
}
#add-thoughts{
    margin-left: 20px;
    width: 120px;
    background-color: #2b78e4;
    border: solid black;
    box-shadow: 3px 3px black;
    color:white;
    font-size: 16px;
}
#text-area{
    border: 2px solid black;
    overflow-y: scroll;
    resize: none;
    height: 100px;
    width: 465px;
}
.inline-input{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.inline{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.p{
    width: 100px;
}
#thought-board{
    padding-top: 20px;
}
.details a{
    color: blue;
    text-decoration: underline;
    cursor: pointer;
    background: none;
    margin-left: 102px;
    font-size: 16px;
}
.delete{
    display: inline-block;
    margin-left: -100px;
}
.delete-btn{
    background-color: #cc0101;
    color: white;
    width: 100px;
}
#likes{
    margin-left: 455px;
    margin-top: -25px;
}
#line{
    border: 1px solid black;
    width: 750px;
}
</style>
    <div class="container">
        <div class="nav">
            <a href="/" class="button">Logout</a>
        </div>
        <h1>Hello {{user.first_name}} {{user.last_name}}!</h1>
        <div>
        {% if messages %}
        <ul class="messages">    
            {% for message in messages %}    
                <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>    
            {% endfor %}
        </ul>
        {% endif %}
            <form action="/thoughts/add/" method="POST">
            {% csrf_token %}
                <div class="header-desc">
                    <input type="text" id="desc-thoughts" name="desc" placeholder="Post a Great Thought Here!">
                    <button type="submit"  id="add-thoughts">Add Thought!</button>
                </div>
            </form>
        </div>
        <hr id="line" align="left">
        {% for thought in thoughts %}
        <div id="thought-board">
            <div class="inline-input p">
                <p id="p">{{thought.user.first_name}} says:</p>
            </div>
            <div class="inline">
                <textarea readonly id="text-area">{{thought.desc}}</textarea>
            </div>
            <div class="delete">
                <form action="/thoughts/{{thought.id}}/delete/">
                    <button type="submit" class="delete-btn">Delete</button>
                </form>
            </div>
            <div class="details">
                <a href="/thoughts/{{thought.id}}/" method="GET">Details</a>
                <p id="likes">{{thought.like.count}} people like this</p>
            </div>
        </div>
        {% endfor %}
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Thought Board</title>
</head>
<body>
<style>
.container{
    padding: 10px 0px 0px 0px;
}
.table-secondary{
    border: 2px solid black;
}
.table th{
    border: 2px solid black;
}
.table td{
    border: 2px solid black;
}
.nav{
    float: right;
}
.dashboard{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
    margin-right: 10px;
}
.logout{
    font-size: 20px;
    background: none;
    border: none;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}
#text-area{
    border: 2px solid black;
    overflow-y: scroll;
    resize: none;
    height: 100px;
    width: 555px;
    background-color: white;
}
.inline-input{
    display: inline-block;
    vertical-align: top;
    width: 50%;
}
.label{
    width: 100px;
    text-align: right;
    margin-right: 10px;
}
.input{
    padding-top: 50px;
}
.btn{
    width: 80px;
    background-color: #009e0f;
    border: solid black;
    box-shadow: 3px 3px black;
    color:white;
    margin-left: 590px;
    margin-top: 5px;
}
.btn2{
    width: 80px;
    background-color: #ff9900;
    border: solid black;
    box-shadow: 3px 3px black;
    color:black;
    margin-left: 590px;
    margin-top: 5px;
}
.table{
    width: 59%;
}
</style>

    <div class="container">
        <div class="header float-right">
        <form action="/thoughts/" method="GET">
        {% csrf_token %}
            <a href="/thoughts/" class="dashboard">Dashboard</a>
            <a href="/" class="logout">Logout</a>
        </form>
        </div>
            <div class="input">
                <div class="inline-input label">
                    <label>{{thought.user.first_name}} says:</label>
                </div>
                <div class="inline-input">
                    <textarea id="text-area" readonly>{{thought.desc}}</textarea>
                </div>
            </div>
            <form action="/thoughts/{{thought.id}}/like/" method="POST">
                {% if is_liked == logged_user %}
                {% csrf_token %}
                <button type="submit" value="{{thought.id}}" class="btn">Like</button>
            </form>
                {% else %}
            <form action="/thoughts/{{thought.id}}/unlike/" method="POST">
                {% csrf_token %}
                <button type="submit" value="{{thought.id}}" class="btn2">Unlike</button>
                {% endif %}
            </form>
        <div class="people-likes">
            <table class="table table-bordered table-striped">
                <p>People who liked this thought:<p>
                <thead class="table-secondary">
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                </thead>
                {% for user in users %}
                    <tr>
                        <td>{{user.first_name}}</td>
                        <td>{{user.last_name}}</td>
                    </tr>
                {% endfor %}
            </table>
        </div>
        </form>
        </div>
    </div>
</body>
</html>

思想委员会
.集装箱{
填充:10px 0px 0px 0px;
}
.表二{
边框:2件纯黑;
}
.表th{
边框:2件纯黑;
}
.表td{
边框:2件纯黑;
}
.导航{
浮动:对;
}
.仪表板{
字体大小:20px;
背景:无;
边界:无;
颜色:蓝色;
文字装饰:下划线;
光标:指针;
右边距:10px;
}
.注销{
字体大小:20px;
背景:无;
边界:无;
颜色:蓝色;
文字装饰:下划线;
光标:指针;
}
#文本区{
边框:2件纯黑;
溢出y:滚动;
调整大小:无;
高度:100px;
宽度:555px;
背景色:白色;
}
.内联输入{
显示:内联块;
垂直对齐:顶部;
宽度:50%;
}
.标签{
宽度:100px;
文本对齐:右对齐;
右边距:10px;
}
.输入{
填充顶部:50px;
}
.btn{
宽度:80px;
背景色:#009e0f;
边框:纯黑;
盒影:3px 3px黑色;
颜色:白色;
左边距:590px;
边缘顶部:5px;
}
.btn2{
宽度:80px;
背景色:#ff9900;
边框:纯黑;
盒影:3px 3px黑色;
颜色:黑色;
左边距:590px;
边缘顶部:5px;
}
.桌子{
宽度:59%;
}
{%csrf_令牌%}
{{think.user.first_name}}说:
{{think.desc}}
{%if\u like==logged\u user%}
{%csrf_令牌%}
喜欢
{%else%}
{%csrf_令牌%}
不像
{%endif%}
喜欢这种想法的人:
名字
姓
{users%%中的用户为%s}
{{user.first{u name}
{{user.last_name}
{%endfor%}
我对编码/编程非常陌生。我还可以在视图/模型页面中添加不必要的代码。请指出任何错误和/或建议,以改进我的初级编码/编程


**编辑:**很抱歉给您带来不便!我忘了添加模板。

您可以修改视图。py t