简体   繁体   中英

I can't use my django model values in forms.py. I get : name 'user' is not defined

I'm trying to use a value from a django model, but I'm missing something in my code and I can't figure out what it is.

I'm using django 1.11

Do I need the form class to inherit request? In case,how do I do that?

from django import forms
from .models import Profile
from django.contrib.auth.models import User
from django.shortcuts import render

class form(forms.Form):
  department_string = ((user.profile.departnemt_1_number, 'Afd A',), ('2', 'Afd B',),)
  afdeling = forms.ChoiceField(widget=forms.RadioSelect, choices=department_string, initial='1')

I get: Exception Value: name 'user' is not defined

Any help is very appreciated!

You can't define this at that point; there's no user in scope at the point where the form is defined.

You need to override the __init__ method of your form to accept an extra keyword argument from the user and modify the choices appropriately.

class MyForm(forms.Form):
  afdeling = forms.ChoiceField(widget=forms.RadioSelect, initial='1')

  def __init__(self, *args, **kwargs):
     user = kwargs.pop('user')
     super(MyForm, self).__init__(*args, **kwargs)
     self.fields['afdeling'].choices = ((user.profile.departnemt_1_number, 'Afd A',), ('2', 'Afd B',),)

Don't forget to pass the user from the view:

if request.method == 'POST':
       form = MyForm(request.POST, user=request.user)
       ...
    else:
       form = MyForm(request.POST, user=request.user)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM