Django -序列化器字段可能命名不正确,并且不匹配`QuerySet`示例上的任何属性或键

cygmwpex  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(114)

我遇到了一个我想不明白的问题。首先,我的代码:
models.py

from django.db import models
import random

def pass_gen():
    password = ''
    def rand_uni():
        return random.randint(33, 126)
    def rand():
        return random.randint(8, 20)
    code = rand()
    for num in range(code):
        r_int = chr(rand_uni())
        password += r_int
    return password

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=200)

class Password(models.Model):
    url = models.CharField(max_length=800)
    password = models.CharField(default=pass_gen(), max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['url', 'user'], name='unique_url_and_user_id')
        ]

Serializers.py:

from rest_framework import serializers
from vault.models import User, Password

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class PasswordSerializer(serializers.ModelSerializer):
    url = serializers.CharField(max_length=800)

    class Meta:
        model = Password
        fields = ('url', 'password', "user")

views.py:

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from vault.models import User, Password
from django.views.decorators.csrf import csrf_exempt
from vault.serializers import UserSerializer, PasswordSerializer

# Create your views here.

# GET list of all users
@csrf_exempt
def user_all(request):
    if request.method == 'GET':
        user = User.objects.all()
        serializer = UserSerializer(user, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method=='POST':
        data = JSONParser().parse(request)
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

#GET and DELETE unique users  
@csrf_exempt
def user_detail(request, id):
    try:
        user = User.objects.get(pk=id)
    except User.DoesNotExist:
        return HttpResponse(status=404)
    
    if request.method=='GET':
        serializer = UserSerializer(user)
        return JsonResponse(serializer.data)
    
    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
    
#get all passwords by unique user
@csrf_exempt
def passwords_one_user(request):
    user = request.GET.get('user')
    url = request.GET.get('url')
    password = Password.objects.filter(user=user).filter(url=url)
    try:
        passwords = Password.objects.filter(user=user)
    except Password.DoesNotExist:
        return HttpResponse(status=404)
    
    if request.method=="GET" and url==None:
        serializer = PasswordSerializer(passwords)
        return JsonResponse(serializer.data)
    
    elif request.method=='POST':
        data = JSONParser().parse(request)
        serializer = PasswordSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
    
    elif request.method=="GET":
        serializer = PasswordSerializer(password)
        return JsonResponse(serializer.data)
    
    elif request.method=='PUT':
        data = JSONParser().parse(request)
        serializer = PasswordSerializer(password, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        password.delete()
        return HttpResponse(status=204)

本质上,我可以让Users序列化程序来POST和GET数据。我可以将密码POST到我的数据库中,但每次我尝试获取密码时,都会收到错误:
AttributeError at/password/Got AttributeError当尝试获取序列化程序PasswordSerializer上的字段url的值时。序列化器字段可能命名不正确,并且与QuerySet示例上的任何属性或键都不匹配。原始例外文本为:“QuerySet”对象没有属性“url”。
(As注意,我测试GET的url路径是http://localhost:8000/password?user_id = 1)。
从本质上讲,我只是希望有这个拉密码连接到用户,我在网址中指定。

yizd12fk

yizd12fk1#

您使用QuerySetPassword s,因此是一个集合(可以包含零个,一个或多个密码)。因此,您需要使用:

if request.method == 'GET' and url == None:
    serializer = PasswordSerializer(passwords, many=True)
    return JsonResponse(serializer.data)

注意你的default=…不应该调用这个方法,否则它只会调用一次,当你启动服务器的时候,并使用这个密码来执行所有的操作。它创建的模型,这可能是一个严重的安全问题,因此:

import random

from django.db import models

def pass_gen():
    return ''.join(
        chr(random.randint(33, 126)) for _ in range(random.randint(8, 20))
    )

# …

class Password(models.Model):
    # …
    password = models.CharField(
        default=pass_gen, max_length=100  # 🖘 no parenthesis
    )

相关问题