如何在Django中使用@setter和token设置userkey_id?

huangapple go评论64阅读模式
英文:

How to set userkey_id with @setter and token in django?

问题

Views.py

class CreatePost(generics.CreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(userkey=self.request.user)

Post model.py

from django.db import models
from accounts.models import CustomUser

class Post(models.Model):
    # Foreign key
    userkey = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

    # Properties
    title = models.CharField(max_length=100, blank=True)
    image = models.FileField(upload_to='files/', null=True, verbose_name="", blank=True)
    price = models.IntegerField(default=0, blank=True)
    description = models.TextField(blank=True)
    likes = models.IntegerField(default=0)
    tags = models.CharField(max_length=30, blank=True, default="tag1,tag2,...") # SQLite doesn't support arrays
    date_modified = models.DateTimeField(auto_now=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, blank=True)
    sold = models.BooleanField(default=False, blank=True)

    @property
    def user(self):
        return self.userkey.username

    @user.setter
    def user(self, custom_user):
        self.userkey = custom_user

    @property
    def datejoined(self):
        return self.userkey.date_joined

    def __str__(self):
        return self.title

上述是代码的翻译,已经修正了@user.setter的问题,它接受一个custom_user参数,并将userkey设置为传入的用户对象。这应该解决你在客户端前端创建帖子时遇到的问题。希望这对你有所帮助。

英文:

I have created a client frontend and have tested the url using cUrl and it works, sending the auth token via axios headers allows me in to call the api. The problem is that I get a NOT NULL constraint failed: post_post.userkey_id error and have narrowed it down that the @user.setter is not getting the CustomUser from the Auth Token. How can I correctly use the @user.setter to set the user that has the corresponding auth token/created the post from the client frontend.

Views.py

class CreatePost(generics.CreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self,serializer):
        serializer.save(user = self.request.user)

Post model.py

from django.db import models
from accounts.models import CustomUser

class Post(models.Model):
    #foriegn keys
    userkey = models.ForeignKey(CustomUser, on_delete=models.CASCADE) 

    #properties
    title = models.CharField(max_length=100,blank=True)
    image= models.FileField(upload_to='files/', null=True, verbose_name="",blank=True) #image field
    price = models.IntegerField(default=0,blank=True)
    description = models.TextField(blank=True)
    likes = models.IntegerField(default=0)
    tags = models.CharField(max_length=30,blank=True,default="tag1,tag2,...") #sqlite doesnt support arrays
    date_modified = models.DateTimeField(auto_now=True,blank=True)
    created = models.DateTimeField(auto_now_add=True,blank=True)
    sold = models.BooleanField(default=False,blank=True)

    @property
    def user(self):
        return self.userkey.username

    @user.setter
    def user(self):
        return models.ForeignKey(CustomUser,on_delete=models.CASCADE)

    @property
    def datejoined(self):
        return self.userkey.date_joined

    def __str__(self):
        return self.title

The userkey is to get data from the user thus I have a @property def user function to collect data from another object. The userkey and @property def user work fine from the admin panel. The @user.setter is used in order to allow the user to be changed from the views.py otherwise I get a "cannot change attribute 'user'" error. Thus I know that the problem is specifically from the @user.setter, I just don't know what I am doing wrong, everything seems fine. Post creation only seems to work from the Admin panel.

答案1

得分: 0

已修复,错误在 views.py 中:

class CreatePost(generics.CreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(userkey=self.request.user)

应该更改 'userkey' 而不是 'user'。
同时删除了 user.setter。我试图更改用户,但应该更改用户键,因为那是字段,而用户是一个属性。

英文:

Fixed, the error was in the views.py

class CreatePost(generics.CreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def perform_create(self,serializer):
        serializer.save(userkey = self.request.user)

Should be changing the 'userkey' not the 'user'.
Also removed the user.setter. I was trying to change the user but it should have been the userkey as that is the field and user is a property.

huangapple
  • 本文由 发表于 2023年2月10日 14:20:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定