0

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?

models.py

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

forms.py

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

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

views.py

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():
        print("worked")
        profile_form.save()

    context = {
        'profile_form': profile_form

    }

    return render(request, "main/dashboard.html", context)
tiberhockey
  • 576
  • 5
  • 22

3 Answers3

0

You can set the readonly attribute in the form constructor

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

    def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.fields['subscription'].widget.attrs['readonly'] = True
Chris Curvey
  • 9,738
  • 10
  • 48
  • 70
  • Thanks for the reply but it not working, the user can still modify the "subscription" input and update the data – tiberhockey Sep 25 '22 at 21:47
  • 1
    Please check this https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot/34538169#34538169 answer it has multpile ways yo do it may be this will help. – Ashish Nautiyal Sep 26 '22 at 05:52
0

Define only the fields you want to edit in Meta.fields as follows:

fields = ["telegramusername", "numberofaccount"]
gypark
  • 251
  • 1
  • 8
0

I made it work by adding this line of code inside my form

subscription = forms.CharField(disabled=True)

forms.py

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

        fields = ["telegramusername", "subscription", "numberofaccount"]
tiberhockey
  • 576
  • 5
  • 22