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

Viewed 118

This is my models.py file

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)

and this is my forms.py file

from django import forms
from .models import Borrow


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


and this is the function in my views.py file that renders the form

@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})

The role of this function is to render that form and to save the data that user will enter and automatically assign the username of the current user to the field 'name' in form.

I tried alot of things to get the username of the current user and assign it to the field 'name' but nothing works and that field stays blank.

enter image description here

1 Answers

You're using a models.ForeignKey(User) so that table will store a user id, not a username. I'd call this field user and not name, personally.

Therefore you need to provide a user instance to it like this;

@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()

If you wanted to easily get the username for a Borrow instance you could do this;

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

If you want the form to offer users by username, you can either have the str method of your user model return username, or create custom choices as a tuple of user ID & username in the form __init__

Related