models.py
User
class User(AbstractUser):
pass
Listings
class Listings(models.Model):
user = models.ManyToManyField(User)
title = models.CharField(max_length=64)
description = models.TextField(max_length=128)
starting_bid = models.PositiveIntegerField()
image_url = models.URLField(blank=True, null=True)
category = models.CharField(max_length=64, blank=True, null=True)
def __str__(self):
return f'({self.user.id}): {self.title}: description: {self.description}, start_bid: {self.starting_bid}, category: {self.category}'
forms.py
ListingForm
class ListingForm(ModelForm):
class Meta:
model = Listings
fields = ['title', 'description',
'starting_bid', 'image_url', 'category']
views.py
create
def create(request):
if request.method == 'POST':
if request.user.is_authenticated:
print('user is authenticated')
form = ListingForm(request.POST)
if form.is_valid():
form.save()
form.user.add(form) # issue here
print('form saved')
return HttpResponseRedirect(reverse('index'))
else:
print('form not saved')
return render(request, 'auctions/create.html', {'form': form})
else:
print('user is not authenticated')
return render(request, 'auctions/create.html', {'form': ListingForm()})
Issue
- at first
create
method stored data, usingform.save()
- when checked
object
forListings
, could not founduser
property
e.g. li = Listing.objects.all() returned objects but no user property is there- now trying to : (first)saveform and then (second)Add form to user [inside create(request)] like described here
- create def should save/store formData user wise
- It gives
AttributeError: 'ListingForm' object has no attribute 'user'
- where changes need ?