how to pre-fill a value in django-crispy-form field

Viewed 800

I am trying to make a create function using the model class, the forms.py and then using the django-crispy-forms package. The form has been rendered correctly but I am trying to exclude a particular field as well as prefill it with the current user email. I am already able to exclude it in the forme.py but I don't know how to go about adding the current user email to it.

models.py

class Product(models.Model):
    name = models.CharField(max_length=36)
    price = models.PositiveIntegerField()
    description = models.TextField()
    quantity = models.PositiveIntegerField()
    image = models.ImageField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

forms.py

from django import forms
from .models import *

class AddProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        exclude = ['user']

views.py

def Addproduct(request):

    form = AddProductForm()
    if request.method == 'POST':
        form = AddProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, "Products Added Successfully")
            return redirect('product')

    context = {"form":form}

    return render(request, "core/addproduct.html", context)

addproduct.html

<form method="post">
{% csrf_token %}
<div class="form-row">
  <div class="form-group col-md-4 mb-0">
    {{ form.name|as_crispy_field }}
  </div>
  <div class="form-group col-md-4 mb-0">
    {{ form.price|as_crispy_field }}
  </div>
  <div class="form-group col-md-4 mb-0">
    {{ form.quantity|as_crispy_field }}
  </div>
</div>
{{ form.description|as_crispy_field }}
<div class="form-row">
  <div class="form-group col-md-12 mb-0">
    {{ form.image|as_crispy_field }}
  </div>
</div>
<button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">register supplier</button>
</form>
1 Answers

In your view if the form is valid simply add any field you want to to form.instance:

def Addproduct(request): # Note function names should ideally be in snake_case

    form = AddProductForm()
    if request.method == 'POST':
        form = AddProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user # Assuming you use login_required decorator so request.user would be a user instance (instead of anonymous user instance) if this line runs
            form.save()
            messages.success(request, "Products Added Successfully")
            return redirect('product')

    context = {"form":form}

    return render(request, "core/addproduct.html", context)
Related