0

i have some fields in my django models.

class Product(models.Model):
    user=models.ForeignKey(User)
    product_name = models.CharField(max_length=50)
    product_cost = models.IntegerField(default=0,null=True, blank=True)
    product_description = models.TextField(null=True, blank=True)
    quantity = models.IntegerField(default=0,null=True, blank=True)
    product_image = models.FileField(upload_to='images/',blank=True,null=True,)
    coupon_code = models.CharField(max_length=50)
    time = models.DateTimeField(default=timezone.now)


    def __str__(self):
        return self.product_name or u''

when i use form to save all the data from front end in my database i can do this.

class DocumentForm(forms.ModelForm):


    class Meta:
        model = Product

        fields = ('user','product_name','product_image','product_cost','product_description','product_description','coupon_code')

Problem is this i don't want to allow user to fill user data from front-end.when user save data it save request.user to user. I am new to work with forms so facing some issues. Please help me how can i do this. Thanks in advance.

vikrant
  • 81
  • 3
  • 11

1 Answers1

0

In fields you have to remove user: so it will look like this: class DocumentForm(forms.ModelForm):

class Meta:
    model = Product

    fields = ('product_name','product_image','product_cost','product_description','product_description','coupon_code')

and in your views.py when you save the data from the form you have write something like this:

user = request.user

in this case user will be saved if he is authenticated.

If you want that not authenticated user could fill the form too, you have to change in your model.py Product class from:

user=models.ForeignKey(User) 

to:

user=models.ForeignKey(User, null=True)

then not authenticated user will be NULL.

Zagorodniy Olexiy
  • 2,132
  • 3
  • 22
  • 47