(姜戈)需要帮助从数据库中获取内容

(Django) Need help getting things from the database

提问人:Yukki 提问时间:11/14/2023 更新时间:11/14/2023 访问量:42

问:

所以,让我们再试一次,我对编程很陌生,对细节了解不多,所以请耐心等待一下,我正在制作一个具有登录和票务系统的网站,我按照教程制作了使用 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)

地籍.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>

所以,这两个都在使用并且都工作正常,但我没有在 models.py 上声明它们,现在我不知道如何从数据库中获取它们,我想这些表是随 Django 一起自动提供的,或者当我创建项目时,但我真的不知道,如果有人能向我解释这一点,我将不胜感激, 此外,由于我的帖子因没有提供足够的信息而被关闭,我将发布临时工单表格并 models.py 以防万一,它们也可以正常工作,但我需要用户名才能实际完成工单

工单.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 身份验证系统收集的数据

HTML Django

评论


答:

1赞 CoffeeBasedLifeform 11/14/2023 #1

我猜这些表是随 Django 一起自动出现的,或者是当我创建项目时自动出现的,但我真的不知道

是的,没错。Django 自带身份验证系统,默认启用 (docs)。django.contrib.auth

如果你正在使用它,那么你将需要查询该模块的模型,如下所述,例如:django.contrib.auth

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

或者,可以使用 get_user_model 函数获取对当前用户模型的引用:

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

如果您决定创建自己的用户模型,这将更加可靠。

更新

哦,这很有帮助,这就是我正在寻找的,但是我如何在 HTML 上显示它,就像我如何显示用户名一样

若要获取 User 对象的用户名,请使用 username 属性:。为了能够在模板中显示用户名,必须将其包含在模板可用的上下文中。例如,在您的视图中,由于您使用的是 render 函数,因此该模板上下文。您可以将用户对象或用户名添加到数据中:user_object.usernamedata

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> 
        ...

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

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

评论

0赞 Yukki 11/14/2023
哦,这很有帮助,这就是我正在寻找的,但是我如何在 HTML 上显示它,就像我如何显示用户名一样
0赞 CoffeeBasedLifeform 11/14/2023
好的,我已经更新了我的答案。
1赞 Yukki 11/14/2023
非常感谢你,这正是我需要的,只是尝试过并且工作得很好,我真的很迷茫,你真的救了我,很抱歉占用你的时间,再次感谢您的帮助!