(Django)需要帮助从数据库获取内容

wfveoks0  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(122)

所以,让我们再试一次,我对编程非常陌生,不太了解细节,所以请耐心等待,我正在制作一个有登录和门票系统的网站,我遵循教程并使用Django身份验证和登录来制作登录系统
(Views.py被分为两部分,以便更容易理解,至少我希望如此)
Views.py(注册部分)

from django.contrib.auth import authenticate, login

#Registering system, requires that both passwords area equal to register
def cadastro(request):
    return render(request,'cadastro.html')

def store(request):
    data = {}
    if(request.POST['password'] != request.POST['password-conf']):
        data['msg'] = 'Senhas diferentes! Tente Novamente'
        data['class'] = 'alert-danger'
    else:
        user = User.objects.create_user(request.POST['user'], request.POST['email'], request.POST['password'])
        user.save()
        data['msg'] = 'Usuário cadastrado com sucesso!'
        data['class'] = 'alert-success'
    return render(request,'cadastro.html',data)

字符串
Cadastro.hmtl

<form name="form-users" id="formUsers" method="post" action="/store/">
    <div class="col-4 mt-4 m-auto">
        {% if msg %}
            <div class="alert {{class}}">
                {{msg}}
            </div>
        {% endif %}

        {% csrf_token %}
        <input class="form-control mt-4" type="text" name="user" id="user" placeholder="Nome de Usuario:">
        <input class="form-control mt-4" type="email" name="email" id="email" placeholder="Email:">
        <input class="form-control mt-4" type="password" name="password" id="password" placeholder="Senha:">
        <input class="form-control mt-4" type="password" name="password-conf" id="password-conf" placeholder="Repita a Senha:">
        <input class="btn btn-primary mt-4" type="submit" value="Cadastrar">
        <a href="/loginv">Ja tem uma conta? Faça Login</a>
    </div>
</form>


Views.py(登录部分)

from django.contrib.auth import authenticate, login

#Login system
def loginv(request):
    return render(request,'loginv.html')

def loginr(request):
 data = {}
 user = authenticate(username=request.POST['user'], password=request.POST['password'])
 if user is not None:
        login(request, user)
        return redirect('/dashboard/')
 else:
        data['msg'] = 'Usuário ou Senha inválidos!'
        data['class'] = 'alert-danger'
        return render(request,'loginv.html',data)


loginv.html

<form name="form-login" id="formLogin" method="post" action="/loginr/">
    <div class="col-4 mt-4 m-auto">
        {% if msg %}
            <div class="alert {{class}}">
                {{msg}}
            </div>
        {% endif %}

        {% csrf_token %}
        <input class="form-control mt-4" type="text" name="user" id="user" placeholder="Nome de Usuario:">
        <input class="form-control mt-4" type="password" name="password" id="password" placeholder="Senha:">
        <input class="btn btn-primary mt-4" type="submit" value="Entrar">
        <a href="/cadastro">Ainda não tem uma conta? Cadastre-se</a>
    </div>
</form>


所以,这两个都在使用,并且都工作正常,但是我没有在www.example.com上声明它们models.py,现在我不知道如何从数据库中获取它们,我猜这些表是自动与Django一起来的,或者当我创建项目时,但我真的不知道,如果有人能向我解释这一点,我真的很感激,而且因为我的帖子没有提供足够的信息而关闭,我将发布临时ticket form和models.py以防万一,它们也工作得很好,但我需要用户名才能出票
ticket.html

{% block content %}
    {% if request.user.is_authenticated %}
    <form name="form-ticket" id="formTicket" method="POST" action="/ticketr/">
        <div class="col-4 mt-4 m-auto">
            {% if msg %}
                <div class="alert {{class}}">
                    {{msg}}
                </div>
            {% endif %}
    
            {% csrf_token %}
            <input class="form-control mt-4" type="text" name="numctt" id="numctt" placeholder="Numero para contato:">
            <input class="form-control mt-4" type="text" name="nomctt" id="nomctt" placeholder="Nome para contato:">
            <input class="form-control mt-4" type="int" name="areaserv" id="areaserv" placeholder="Area do servico:">
            <input class="form-control mt-4" type="int" name="tiposerv" id="tiposerv" placeholder="Tipo de servico:">
            <input class="form-control mt-4" type="text" name="tickettext" id="tickettext" placeholder="Descricao:">
            <input class="btn btn-primary mt-4" type="submit" value="Entrar">
            
        </div>
    </form>
    {% else %}
        Você não tem acesso a essa área!
    {% endif %}
{% endblock %}


models.py

from django.db import models

# Create your models here.

class Userdb(models.Model):
    ticketid = models.AutoField(primary_key=True)
    nomctt = models.CharField(max_length=50)
    numctt = models.CharField(max_length=9)
    tiposerv = models.IntegerField()
    areaserv = models.IntegerField()
    tickettext = models.CharField(max_length=200) 
    
    class Meta:
        db_table = 'dbuser'


我不知道如何获取Django认证系统收集的数据

yzxexxkh

yzxexxkh1#

我猜这些表是Django自动生成的,或者是我创建项目时自动生成的,但我真的不知道。
是的,Django自带了自己的身份验证系统django.contrib.auth,默认情况下是启用的(docs)。
如果你正在使用它,那么你需要像here那样查询django.contrib.auth模块的模型,例如:

from django.contrib.auth.models import User
print(User.objects.all())

字符串
或者,您可以使用get_user_model函数来获取对当前User模型的引用:

from django.contrib.auth import get_user_model
user_model = get_user_model()
print(user_model.objects.all())


这是更强大的,如果你决定创建自己的用户模型。

更新

哦,这帮助很大,这是我正在寻找的,但我如何在HTML上显示这个,就像我如何显示用户名一样
要获取User对象的用户名,请使用username属性:user_object.username。为了能够在模板中显示用户名,您必须将其包含在模板可用的上下文中。例如,在视图中,由于您正在使用render函数,data就是模板上下文。您可以将用户对象或用户名添加到数据中:

def store(request):
    data = {}
    if(request.POST['password'] != request.POST['password-conf']):
        ...
    else:
        user = User.objects.create_user(request.POST['user'], request.POST['email'], request.POST['password'])
        user.save()
        data['msg'] = 'Usuário cadastrado com sucesso!'
        data['class'] = 'alert-success'
        data['user'] = user
        data['username'] = user.username
    return render(request,'cadastro.html',data)


然后你可以在你的模板中使用它:

{% block content %}
    {% if request.user.is_authenticated %}
        <p>Hello, user '{{ user.username }}'</p> 
        <p>Hello, user '{{ username }}'</p> 
        ...


要轻松获取当前登录的用户,可以使用request对象的user属性。将请求包含在模板上下文data['request'] = request中,然后您可以在模板中使用它:

<p>Hello, user '{{ request.user.username }}'</p>

相关问题