Home > Blockchain >  How do i pre-populate Django ModelForm fields
How do i pre-populate Django ModelForm fields

Time:10-11

enter image description here

This form requires a student to login before filling it out. I want the input field with placeholder Enter Your Username to be pre-populated with the username of the individual filling it out.

Here is my models.py

class User_detail(models.Model):
    username = models.CharField(max_length=255, default="")
    first_name = models.CharField(max_length=255, default="")
    last_name = models.CharField(max_length=255, default="")
    email = models.EmailField(max_length=255, default="")
    date_of_birth = models.DateField(null=False, blank=False, default="")
    gender = models.CharField(max_length=50, choices=GENDER, default="")
    tel = PhoneNumberField()

    def __str__(self):
        return self.email

Here is my views.py

from django.contrib.auth.decorators import login_required
from .forms import *

def signin(request):
    if request.user.is_authenticated:
        return redirect(profile)
    if request.method == "POST":
        form = Signin(request.POST)
        if form.is_valid():
            username = request.POST["username"]
            password = request.POST["password"]

            user = auth.authenticate(username=username, password=password)

            if user is not None:
                auth.login(request, user)
                return redirect("profile")
            else:
                messages.error(request, "Invalid credentials")
                return redirect("signin")
    else:
        form = Signin()
        return render(request, "accounts/login.html", {"form": form})


@login_required(login_url="signin")
def user(request):
    if request.method == "POST":
        form = Userdetail(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.save()
            messages.success(request, "You Have Successfully updated your details")
            return render(request, "thanks.html")
    else:
        form = Userdetail()
    return render(request, "accounts/User details.html", {"form": form})


Here is my Forms.py

class Signin(forms.Form):
    username = forms.CharField(
        max_length=255,
        widget=forms.TextInput(attrs={"placeholder": "Enter Your Userame"}),
    )
    password = forms.CharField(
        max_length=255,
        widget=forms.PasswordInput(
            attrs={"placeholder": "Enter Your Password", "id": "password"}
        ),
    )


class Userdetail(forms.ModelForm):
    class Meta:
        model = User_detail
        fields = "__all__"
        widgets = {
            "first_name": forms.TextInput(
                attrs={"placeholder": "Enter Your First Name"}
            ),
            "last_name": forms.TextInput(attrs={"placeholder": "Enter Your Last Name"}),
            "other_name": forms.TextInput(attrs={"placeholder": "Enter Other Names"}),
            "email": forms.EmailInput(
                attrs={"placeholder": "Enter Your E-mail Address"}
            ),
            "date_of_birth": forms.DateInput(attrs={"type": "date"}),
            "gender": forms.RadioSelect(attrs={"type": "radio", "class": "gender"}),
            "tel": forms.TextInput(attrs={"placeholder": "Enter Your Phone Number"}),
            'username':forms.TextInput(attrs={'placeholder': 'Enter Your Username'}),
        }

    def clean(self):
        super(Userdetail, self).clean()
        tel = self.cleaned_data.get("tel")
        email = self.cleaned_data.get("email")

        for instance in User_detail.objects.all():
            if instance.email == email:
                self.errors[""] = self.error_class(["E-mail already in use"])
            elif instance.tel == tel:
                self.errors[""] = self.error_class(["Phone Number already Exists"])

So what i am basically trying to achieve is that i want the username input field to be pre-poulated by username of the student that login to fill the form.

CodePudding user response:

You can use the initial argument for the form to set up default field values (see docs). So something like this should work:

def user(request):
else:
    form = Userdetail(initial = {'username': request.user.username})
  • Related