Get the user instance from a profile model

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):
        ('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

def sell(request):
    form = SellProductForm()
    if request.method == 'POST':
        form = SellProductForm(request.POST)
        if form.is_valid():
            instance =
            instance.seller = request.user
            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.


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.