how to store data user wise

:one: 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}'

:two: forms.py

  • ListingForm
class ListingForm(ModelForm):
    class Meta:
        model = Listings
        fields = ['title', 'description',
                  'starting_bid', 'image_url', 'category']

:three: 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()})

:four: Issue

  • at first create method stored data, using form.save()
  • when checked object for Listings , could not found user 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 ?

form.save() returns an instance of the model, so you want to use:

listing = form.save()
listing.user.add(request.user)

Also I’d recommend naming Listing.user to Listing.users so that the field better reflects that it’s a relationship and that there are more than a single user attached to a listing. The reason is because if I saw listing.user, I’d expect it to be a single instance.

thank you for your response