Rokas
Rokas

Reputation: 125

not show field in form if user is authenticated

I do not want to show one form field if user is authenticated.

I tried if not request.user.is_authenticated(): but it's not working.

def create_event(request):
    if not request.user.is_authenticated():
        CreateEventForm.base_fields['owner_email'] = forms.EmailField(required=True)
    event_form = CreateEventForm(request.POST or None, prefix='event')
    context = {
        'event_form': event_form,
    }
    if event_form.is_valid():
        event = event_form.save(commit=False)
        if request.user.is_authenticated():
            event.registered_owner = request.user
        else:
            event.owner_email = event_form.cleaned_data.get('owner_email')
        event = event_form.save()
        return HttpResponseRedirect('/event-%s' %event.id)
    return render(request, 'create_event.html', context)

Form in forms.py

class CreateEventForm(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['title', 'description', 'location', 'duaration', 'private']

Upvotes: 0

Views: 194

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

You should never modify base_fields; that's a class attribute, so once you add something to it, it's present for all form instances until you explicitly remove it.

Instead, move this logic into the __init__ method for the form itself.

class CreateEventForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        is_authenticated = kwargs.pop('is_authenticated', False)
        super(CreateEventForm, self).__init__(*args, **kwargs)
        if is_authenticated:
            self.fields['owner_email'] = forms.EmailField(required=True)

Now in your view you need to pass that parameter to the form:

event_form = CreateEventForm(request.POST or None, prefix='event', is_authenticated=request.user.is_authenticated())

Upvotes: 4

Related Questions