Set currently logged in user as the user in the model when creating an object in Django

523 Views Asked by At

I've tried to implement the solutions offered by some of the other posts I see on here, but nothing seems to be working. I'm brand new to django and backend in general, so I may just be lacking in skill.

The situation is that I'm letting users generate a listing based on a django model Listings using a ModelForm. Everything seems to be working except for the fact that I can't set the currently logged in user as the user for the listing. I understand that the user is stored in request.user, but I can't seem to set it within my form and I consistently get this error:

IntegrityError at /create

NOT NULL constraint failed: auctions_listings.listing_user_id

Here's the code for my User and Listings model:

class User(AbstractUser):
    pass

class Listings(models.Model):
    title = models.CharField(max_length=64, default="")
    description = models.TextField(default="")
    image = models.URLField(blank=True, null=True)
    initial_bid = models.DecimalField(max_digits=8, decimal_places=2)
    category = models.CharField(max_length=64, default="Misc") 
    listing_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing_user")
    # listing.bid.all()????

and here is my form:

from .models import Listings

class ListingsForm(forms.ModelForm):

    class Meta:
        model = Listings
        exclude = ('listing_user')
        fields = [
            'title',
            'description',
            'image',
            'initial_bid',
            'category'
        ]

Some of the suggestions I've found have figured out that I can excluse the user requirement and then set it myself in my view, but whenever I try to exclude the listing_user, I get hit with this error:

TypeError: ListingsForm.Meta.exclude cannot be a string. Did you mean to type: ('listing_user',)?

Trying what is suggested is no help either.

Finally, here is my view:

def create(request):
    
    form = ListingsForm(request.POST or None)  
    if form.is_valid():
        form.save()
        form = ListingsForm()

    context = {
        'form': form
    }
    return render(request, "auctions/create.html", context)
1

There are 1 best solutions below

1
On BEST ANSWER

exclude should be a list or tuple. You have two options:

exclude = ('listing_user',)
or
exclude = ['listing_user']

forms:

from .models import Listings

class ListingsForm(forms.ModelForm):

    class Meta:
        model = Listings
        exclude = ('listing_user',)
        fields = [
            'title',
            'description',
            'image',
            'initial_bid',
            'category'
        ]

views:

def create(request):
    
    form = ListingsForm(request.POST or None)  
    if form.is_valid():
        form.instance.listing_user = request.user
        form.save()
        form = ListingsForm()

    context = {
        'form': form
    }
    return render(request, "auctions/create.html", context)