Django公共和私人职位

4sup72z8  于 2023-02-17  发布在  Go
关注(0)|答案(1)|浏览(100)

我试图实现公共和私人职位的特点,我已经创建了is_private的模型,并检查它的值,如果它是真或假。基于此,我想显示私人和公共职位。'(E. x如果is_private设置为假,那么职位应该是可见的所有用户,如果它是私人的,那么应该是可见的,只有经过身份验证的用户。

models.py 

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class post_model(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_private = models.BooleanField(default=True)

    def __str__(self) -> str:
        return self.title + "\n" + self.description```
views.py 

@login_required(login_url='/login')
def home(request):
    form = post_form(request.POST or None)
    posts = post_model.objects.all()
    if form.is_valid():
        posts = post_model.objects.all().values('is_private')

        for post in posts:
          if post['is_private']:
              posts = posts.exclude(is_private=False)
          else:
              posts = posts.exclude(is_private=True)
    else:
        form = post_form()
    return render(request, 'main/home.html', {'posts': posts, 'form': form})
forms.py 

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from . models import post_model

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class post_form(forms.ModelForm):
    class Meta:
        model = post_model
        fields = ['title','description','is_private']
post.html

{% extends 'main/base.html' %}
{% block title%}Create Post{% endblock %}
{% load crispy_forms_tags %}
{%block content%} 
<div class="container" style="align-items: center;">
  <form method="post">
    {% csrf_token %}
    {{ form|crispy }}
     <div class="text-center mt-3">
        <button type="submit" class="btn btn-primary btn-lg">Post</button>
    </div>
  </form>
</div>

在这一点上,它呈现所有用户的公共和私人职位...那么我怎么才能限制其他用户?

k7fdbhmy

k7fdbhmy1#

Django自带会话认证,你应该使用is_authenticated来验证用户是否被认证,比如

if request. user.is_authenticated:
# Do something for authenticated users.
...
else:
# Do something for anonymous users.

对于你的情况,我会这样做

@login_required(login_url='/login')
def home(request):
form = post_form(request.POST or None)
posts = post_model.objects.all()
if form.is_valid():
    posts = post_model.objects.all().values('is_private')

    if user.is_authenticated:
        posts=post_model.objects.all().filter(is_private=True)
    else:
        post=post_model.objects.all().filter(is_private=False)
   
else:
    form = post_form()
return render(request, 'main/home.html', {'posts': posts, 'form': form})

相关问题