Home > Enterprise >  Get the user instance from a profile model
Get the user instance from a profile model

Time:09-21

Hella everyone, Alright I'm building an ecommerce website and stuck at a certain point, I got two models Seller and Product, as follows:

class Seller(models.Model):
    seller = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=30)
    country = models.CharField(max_length=30)
    phone_number = PhoneNumberField()
    email = models.EmailField(max_length=300)

    def __str__(self):
        return self.seller.username

class Product(models.Model):
    STATUS_CHOICES = [
        ('New', 'New'),
        ('New', 'Used'),
    ]
    image = models.ImageField(default='dev1.jpg', upload_to='images/')
    condition = models.CharField(choices=STATUS_CHOICES, max_length=10)
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.CharField(max_length=15)
    location = models.CharField(max_length=30)
    posted_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Now I have a form to save new Product as:

class SellProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('image', 'condition', 'title', 'description', 'price', 'location', )

The problem is in views.py:

@login_required
def sell(request):
    form = SellProductForm()
    if request.method == 'POST':
        form = SellProductForm(request.POST)
        if form.is_valid():
            print('Ok')
            instance = form.save(commit=False)
            instance.seller = request.user
            instance.save()
            return redirect('index')
    context = {
        'form': form,
    }
    return render(request, 'myapp/sell.html', context)

At the end, I get the ERROR: "Product.seller must be a Seller instance." I understand the demand but I can't get myself to imagine the code and come up with a solution, for I'm giving it a User instance not a seller instance.

CodePudding user response:

Since it is a OneToOneField you can obtain the related Seller model of a User object with user.seller, so in this case:

instance.seller = request.user.seller

This will raise an AttributeError if no Seller is linked to the logged in user.

  • Related