簡體   English   中英

如何獲取當前用戶的用戶名並將其分配給django表單中的某個字段?

[英]How to get the username of the current user and assign it to a certain field in a form in django?

這是我的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})

該函數的作用是呈現該表單並保存用戶將輸入的數據並自動將當前用戶的用戶名分配給表單中的“名稱”字段。

我嘗試了很多方法來獲取當前用戶的用戶名並將其分配給字段“名稱”,但沒有任何效果並且該字段保持空白。

在此處輸入圖片說明

您正在使用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方法返回用戶名,或者創建自定義選項作為__init__表單中的用戶 ID 和用戶名元組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM