【问题标题】:How to get the username of the current user and assign it to a certain field in a form in django?如何获取当前用户的用户名并将其分配给django表单中的某个字段?
【发布时间】:2021-07-18 23:58:32
【问题描述】:

这是我的 models.py 文件

from django.db import models
from django.contrib.auth.models import User


# Create your models here.



class Book(models.Model):
    category_choices =(
        #("Undefined","Undefined"),
        ("Action", "Action"),
        ("Romance", "Romance"),
        ("Horror", "Horror"),
        ("Comedy", "Comedy"),
        ("Adventure", "Adventure"),
        ("Dramatic", "Dramatic"),
        ("Crime","Crime"),
        ("Fantasy","Fantasy"),
    )
    
    name = models.CharField(max_length=100)
    author = models.CharField(max_length=100, null=True)
    content = models.TextField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    image = models.ImageField(upload_to= 'photos/%y/%m/%d', blank = True)
    category = models.CharField(
        max_length = 20,
        choices = category_choices,
        #default = 'Undefined'
        )
    publication_year = models.CharField(max_length=4, null=True)
    ISBN = models.CharField(max_length=13, null=True, unique=True)
    active = models.BooleanField(default= True)

    def __str__(self):
        return self.name

class Borrow(models.Model):
    name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
    period = models.PositiveIntegerField(default=0)
    id = models.IntegerField(primary_key=True)

    def __str__(self):
        return str(self.book)

这是我的 forms.py 文件

from django import forms
from .models import Borrow


class BorrowForm(forms.ModelForm):
    class Meta:
        model = Borrow
        fields = ('name', 'book', 'period')


这是我的views.py文件中呈现表单的函数

@login_required
def borrowing(request):
    momo = BorrowForm()
    if request.method == 'POST':
        momo = BorrowForm(request.POST)
        if momo.is_valid():
            instacne = momo.save(commit=False)
            instacne.user = request.user.username
            instacne.save()
            return redirect('profile')
    return render(request, 'books/book.html', {'momo': momo})

此函数的作用是呈现该表单并保存用户将输入的数据并自动将当前用户的用户名分配给表单中的“名称”字段。

我尝试了很多方法来获取当前用户的用户名并将其分配给字段“名称”,但没有任何效果,并且该字段保持空白。

【问题讨论】:

    标签: python django django-models django-views django-forms


    【解决方案1】:

    您使用的是models.ForeignKey(User),因此该表将存储用户 ID,而不是用户名。我个人称这个字段为user 而不是name

    因此你需要像这样向它提供一个用户实例;

    @login_required
    def borrowing(request):
        initial = {}
        if request.user.is_authenticated:
            initial.update({'name': request.user})
        momo = BorrowForm(initial=initial)
    
        if request.method == 'POST':
            momo = BorrowForm(request.POST)
            if momo.is_valid():
                instance = momo.save(commit=False)
                instance.user = request.user
                instance.save()
    

    如果您想轻松获取 Borrow 实例的用户名,您可以这样做;

    class Borrow(models.Model):
        name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
        book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL)
        period = models.PositiveIntegerField(default=0)
        id = models.IntegerField(primary_key=True)
    
        def __str__(self):
            return str(self.book)
    
        @property
        def username(self):
            return self.name.username
    

    如果您希望表单按用户名提供用户,您可以让用户模型的 str 方法返回用户名,或者创建自定义选项作为用户 ID 和用户名的元组,格式为 __init__

    【讨论】:

    • 有没有办法在BorrowForm() 中添加参数instance = 像这样:momo = BorrowForm(instance = request.user.username)
    • @AhmedHalim 你想对表单中的实例做些什么?
    • 是的,因为正如您在上图中看到的那样,有一个字段Name 包含以前注册过的所有用户的用户名列表,因此必须不允许用户借用使用另一个用户的另一个用户名预订,因此我们无法让用户看到它。我只是为了解释它确实是空白的,所以我需要该表单来自动实例化当前用户的用户名
    • @AhmedHalim 好的,听起来您想为当前用户的name 字段提供初始值,所以我更新了视图以显示如何加载初始数据。跨度>
    • 哇,谢谢你成功了。但是如果我想让字段名称成为不可编辑的字段,我该怎么办,这样用户就无法更改它。
    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 2021-01-19
    • 2021-08-17
    • 2015-02-14
    • 2020-09-15
    • 2020-02-23
    • 2017-06-03
    • 2014-08-21
    相关资源
    最近更新 更多