Django block user from modifying a Form input

Asked 2 months ago
Viewed 6 times

I have a instance Form that is showing the user his Profile Data, the user can update some of his profile settings by modifying the input and clicking the update button.

But I don't want the user to be allowed to change all the profile data, such as the subscriptions Charfields Data. How can I do that?

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    telegramusername = models.CharField(max_length=50, default=None)
    subscription = models.CharField(max_length=50, default=None)
    numberofaccount = models.CharField(max_length=50, default=None)

    def __str__(self):
        return self.telegramusername

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        labels = {
            "telegramusername": "Telegram Username",
            "subscription": "Subscription Plan",
            "numberofaccount": "Number of MT5 Account"

        fields = ["telegramusername", "subscription", "numberofaccount"]

def dashboard(request):

    profile_data = Profile.objects.get(user=request.user)
    profile_form = ProfileForm(request.POST or None, instance=profile_data)

    if profile_form.is_valid():

    context = {
        'profile_form': profile_form


    return render(request, "main/dashboard.html", context)

asked 2 months ago

Correct Answer

You can set the readonly attribute in the form constructor

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile

    def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.fields['subscription'].widget.attrs['readonly'] = True
answered 2 months ago