Home > Software design >  Django: Create a Model instance with the build-in User Model fields
Django: Create a Model instance with the build-in User Model fields

Time:09-23

So i have a Car model. And every car is submitted is assigned to a user. Also every user has his own dashboard where they can submit cars (Only for logged in users).

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

class Car(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    model_car= models.CharField(max_length=200)
    description = models.TextField()
    car_image = models.ImageField(null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)

This is my forms.py where i create cars. And then i render this form to the frontend.

from django import forms
from django.forms import ModelForm
from tasks.models import Car

class CreateCarForm(ModelForm):
    class Meta:
        model=Car
        fields='__all__'
        exclude = ('user',)

Views.py

def create_car(request):
    
    form = CreateCarForm()
    if request.method=="POST":
 
        form = CreateCarForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request,'Car was Created')
            return redirect('create_car')

    context={'form':form}
    return render(request, 'dashboard/create_car.html',context)

Now it just creates a car instance, but with no selected user. What i would like to do is to create this Car instance, but in the user field, to auto assign the current logged-in user username.

How can i achieve this?

CodePudding user response:

You can set the .user instance of the Car instance wrapped in the CreateCarForm:

from django.contrib.auth.decorators import login_required

@login_required
def create_car(request):
    form = CreateCarForm()
    if request.method=='POST':
        form = CreateCarForm(request.POST,request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.success(request,'Car was Created')
            return redirect('create_car')

    context={'form':form}
    return render(request, 'dashboard/create_car.html', context)
  • Related