'Django Modelform user issues

I have a model form to list an item and I am trying to get the form to fill in the user id from the user that is submitting the form. Currently, the form is submitted successfully but it always uses the first user in the database's id for every item.

models.py

class Item(models.Model):
id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False )
creator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, default=2)
item_name = models.CharField(max_length=40)
price = models.DecimalField(max_digits = 6, decimal_places=2)
description = models.CharField(max_length= 500)
main_image = models.ImageField(upload_to=path_and_rename , max_length=255, null=True, blank=True)
image_2 = models.ImageField(upload_to='items/', blank=True)
image_3= models.ImageField(upload_to='items/', blank=True)
image_4= models.ImageField(upload_to='items/', blank=True)
image_5= models.ImageField(upload_to='items/', blank=True)
quantity = models.IntegerField(default=1, validators=[ MaxValueValidator(100),MinValueValidator(1)])
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.item_name

def get_absolute_url(self):
    return reverse("item_detail_view", args=[str(self.id)])

forms.py

from django.forms import ModelForm, forms
from .models import Item

class List_Item_Form(ModelForm):
forms.ModelChoiceField(queryset=Item.objects.filter(user=user))
   
    class Meta:
        model = Item
        
        def __init__(self, *args, **kwargs):
            user = kwargs.pop("user", None)
            super().__init__(*args, **kwargs)

views.py

class AddListing( generic.CreateView):
    template_name = 'store/add_listing.html'
    fields = ('item_name','price','description','main_image','quantity')
    model = Item
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)


Solution 1:[1]

It can be done using function based view too because there we get current user more easily.

Try this:

models.py

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


class Item(models.Model):
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    item_name = models.CharField(max_length=40)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    description = models.CharField(max_length=500)
    main_image = models.ImageField(
        upload_to=path_and_rename, max_length=255, null=True, blank=True)
    image_2 = models.ImageField(upload_to='items/', blank=True)
    image_3 = models.ImageField(upload_to='items/', blank=True)
    image_4 = models.ImageField(upload_to='items/', blank=True)
    image_5 = models.ImageField(upload_to='items/', blank=True)
    quantity = models.PositiveIntegerField(default=1)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.item_name

admin.py

from django.contrib import admin
from home.models import Item
@admin.register(Item)
class ItemRegister(admin.ModelAdmin):
    lis_display = ['id', 'creator', 'item_name', 'price', 'description']

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('', views.list, name='home'),
    path('success/', views.success, name='success')
]

forms.py

from django.forms import ModelForm, forms
from .models import Item


class ListItemForm(ModelForm):
    class Meta:
        model = Item
        fields = ['item_name', 'price', 'main_image'
                  'description', 'quantity']

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Item
from .forms import ListItemForm


def list(request):
    if request.method == 'POST':
        form = ListItemForm(request.POST)
        if form.is_valid():
            itemName = form.cleaned_data['item_name']
            price = form.cleaned_data['price']
            desc = form.cleaned_data['description']
            quan = form.cleaned_data['quantity']
            main_img = form.cleaned_data['main_image']
            current_user = request.user
            model_instance = Item(creator=current_user, item_name=itemName, price=price,
                                  description=desc, quantity=quan, main_image=main_img)
            model_instance.save()
            return HttpResponseRedirect('/success/')
    else:
        form = ListItemForm()
    return render(request, 'store/add_listing.html', {'form': form})


def success(request):
    return render(request, 'store/success.html')

Rest of the fields of models you can customize very easily in the view.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunderam Dubey