caldf
caldf

Reputation: 71

Form required field in django model forms

i have a model form however I'm struggling to set one field as required without changing the model itself. Is there a way of making the location field mandatory without changing models.py when the user submits the form?

modelys.py

class Profile(models.Model):
    user = models.OneToOneField(User)
    location = models.CharField(max_length=120, null=True, blank=True)
    picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
    gender = models.CharField(max_length=120, null=True, choices=GENDER, blank=True)
    bio = models.CharField(max_length=1000, null=True, blank=True)
    home_university = models.CharField(max_length=50, null=True, blank=True)

my forms.py

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [
            "location",
            "picture",
            "bio",
            "gender",
            "home_university",
            ]

and my views.py

@login_required
def profile_complete(request):
    profile, created = Profile.objects.get_or_create(user=request.user)
    form = ProfileForm(request.POST or None, request.FILES or None, instance=profile)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        return redirect("home")
    context = {
        "form": form,

                }
    return render(request, "profiles/profile_complete.html", context)

Upvotes: 1

Views: 5494

Answers (2)

Ahmed
Ahmed

Reputation: 11

For general knowledge, I had the same problem, I solve it as follow, in Django 4.0 you can add "required" in widgets in the Meta class

so your forms.py will be:

class ProfileForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = [
        "location",
        "picture",
        "bio",
        "gender",
        "home_university",
        ]
    widget = {
        "location":forms.TextInput(attrs={"required": True})
        }

Upvotes: 1

Navid Zarepak
Navid Zarepak

Reputation: 4208

You can use these options:

1 - init function:

class ProfileForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        # Making location required
        self.fields['location'].required = True

    class Meta:
        model = Profile
        fields = [
            "location",
            "picture",
            "bio",
            "gender",
            "home_university",
            ]

2 - by redefining the field:

class ProfileForm(forms.ModelForm):
    location = forms.CharField(max_length=120, required=True)

    class Meta:
        model = Profile
        fields = [
            "location",
            "picture",
            "bio",
            "gender",
            "home_university",
            ]

In your case there would be no problem because your model is null=True and you're setting the field to required but if you do this for some other model field with null=False and override the field in ModelForm to required=False, then you have to provide a value in your form or view before you save it to database otherwise you will get an error.

Upvotes: 9

Related Questions