我目前是python开发的新手,目前正在学校学习多个栈。我的代码是最基本的形式。我还没有得到认证,也从来没有被介绍给KWARGS或pk。我现在也不知道这些是什么。我该如何使“删除”按钮只显示在创建对象的用户的“思考”帖子的一侧,这样他们就可以自己删除它,而其他用户的帖子就不能使用该按钮?另外,我将如何实现一个Like/Dislike按钮,以我迄今所学的最简单的形式为每个Object post来回转换?这是我现在的密码。你知道吗
型号.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()
视图.py
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)
这是我的删除按钮将被放置的模板
想法.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>
这就是一个按钮切换喜欢/不喜欢(或不喜欢)的地方
详细信息.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>
我对编码/编程非常陌生。我还可以将不必要的代码添加到我的视图/模型页面。请指出任何错误和/或建议,以改善我的初级编码/编程。你知道吗
**编辑:**很抱歉给您带来不便!我忘了添加模板。你知道吗
您可以修改视图.py像这样
希望这对你有帮助
相关问题 更多 >
编程相关推荐