Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : ModelForm with conditions

I'm trying to create a form variable. As default Player have the level 0 and he can just change is name. Later when he is level 1, he can change is name and is avatar. When he is level 3, he can change is name, is avatar and is job. Etc...

Models.py:

class Player(models.Model):
    level = models.SmallIntegerField(default=0) 
    name = models.CharField(max_length=50)
    avatar = models.URLField(default='http://default-picture.com/01.png')
    job =  models.TextField(null=True)

Fomrs.py:

class ProfileForm(forms.ModelForm):

class Meta:
    model = Player
    fields = ['name', 'avatar', 'job']
    widgets = {
        'name': forms.TextInput(),
        'avatar': forms.TextInput(),
        'job': forms.Textarea(),
    }

Views.py:

def game(request, id):
    user = get_object_or_404(Player, id=id)
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return HttpResponse('Success')
    else:
        form = ProfileForm(instance=user)
    return render(request, "page/template.html",
            {'form': form})

Template.html:

{{ form }}

It's possible to add condition for the render of the form before send it to the render engime ? Or I need to do it in my Template with conditions ?

I just when to allow the instanced object to have more or less positibilies in terms of one of these parameters (in the exemple is the level of the player).

like image 366
Buky Avatar asked Mar 24 '17 13:03

Buky


1 Answers

You can overwrite the form's __init__ method to remove or disable fields conditionally:

class ProfileForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.level < 3:
            self.fields['job'].disabled = True # still displays the field in the template
            # del self.fields['job'] # removes field from form and template
        if self.instance and self.instance.level < 1:
            self.fields['avatar'].disabled = True
like image 200
Martin Bierbaum Avatar answered Sep 21 '22 10:09

Martin Bierbaum