2012-04-04 2 views
0

2 가지 유형의 사용자가 투자자 및 관리자입니다. 어떤 사용자 (투자자)는 investor_type을 정리할 수 있어야하고 다른 사람 (관리자)은 ... 나는 하나의 형식 만 가져야합니다. UserInfoForm. 관리자 사용자가 해당 입력란을 작성할 수 없도록하는 간단한 방법이 있는지 궁금합니다.[vanilla django] 양식 내에서 필드를 제외하는 방법은 무엇입니까?

내 템플릿에서 관리자가 investor_type 필드를 볼 수 없도록 성공적으로 관리했습니다. 그러나 UserInfoForm을 제출하면 템플릿에 investor_type This field is required.이 표시됩니다.

몇 가지 방법이 있습니까? 필수 = 투자자에게만 필요합니까?

class UserInfoForm(forms.Form): 
    choices = (('0', "Foundation"), ('1', "Financial/Bank"), ('2', "Pension"), ('3', "Endowment"),\ 
       ('4', "Government Pension"), ('5', "Family Office"), ('6', "Insurance Co."),\ 
       ('7', "Corporation"), ('8', "Fund of Funds"), ('9', "Fund Manager"), ('10', "Asset Manager"), ('11', "Fundless Sponsor")) 

    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'input-text'}), max_length=30) 
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'input-text'}), max_length=30) 
    email = forms.EmailField(widget=forms.TextInput(attrs={'class':'input-text'})) 
    about = forms.CharField(widget=forms.Textarea(attrs={'class':'input-text'}), required=False) 
    country = forms.CharField(max_length=50, widget=forms.Select(choices=countries.COUNTRIES)) 
    avatar = forms.ImageField(required=False) 
    investor_type = forms.CharField(max_length=4, widget=forms.Select(choices=choices)) 


def save(self, user, type): 
    if type == 'manager': 
     profile = ManagerProfile.objects.get(user=user) 
    else: 
     profile = InvestorProfile.objects.get(user=user) 
     # // Tried this... 
     if profile.investor_type != self.cleaned_data['investor_type']: 
      profile.investor_type = self.cleaned_data['investor_type'] 
      profile_edited = True 
     # // Failed 
    user_edited = False 
    if user.first_name != self.cleaned_data['first_name']: 
     user.first_name = self.cleaned_data['first_name'] 
     user_edited = True 
    if user.last_name != self.cleaned_data['last_name']: 
     user.last_name = self.cleaned_data['last_name'] 
     user_edited = True 
    if user.email != self.cleaned_data['email']: 
     user.email = self.cleaned_data['email'] 
     user_edited = True 
    if user_edited: 
     user.save() 
    profile_edited = False 
    if profile.about != self.cleaned_data['about']: 
     profile.about = self.cleaned_data['about'] 
     profile_edited = True 
    if profile.country != self.cleaned_data['country']: 
     profile.country = self.cleaned_data['country'] 
     profile_edited = True 
    if profile_edited: 
     profile.save() 
    if self.cleaned_data['avatar']: 
     avatar = self.cleaned_data['avatar'] 
     avatar.name = user.username + '.' + avatar.name.split('.')[-1] 
     profile.avatar.save(avatar.name, avatar) 

나는 시도했습니다. investor_type = forms.CharField(max_length=4, required=False, widget=forms.Select(choices=choices), initial='0'), 작동하지 않았습니다.

Views.py :보기 내에서 시도했지만 실패했습니다.

@login_required   
def edit_profile(request, profile_type): 
    if profile_type == 'investor': 
     profile = InvestorProfile.objects.get(user=request.user) 
    elif profile_type == 'manager': 
     profile = ManagerProfile.objects.get(user=request.user) 
    context = base_context(request) 
    if request.method == 'POST': 
     notify = "You have successfully updated your profile." 
     user_info_form = UserInfoForm(request.POST, request.FILES) 
     if user_info_form.is_valid(): 
      user_info_form.save(request.user, profile_type) 
      return HttpResponseRedirect(request.POST.get('next', '/profile/' + profile_type + '/' + request.user.username + '/')) 
    else: 
     initial = {} 
     initial['first_name'] = request.user.first_name 
     initial['last_name'] = request.user.last_name 
     initial['email'] = request.user.email 
     initial['about'] = profile.about 
     initial['country'] = profile.country 
     initial['about'] = profile.about 
     # // Tried this ... 
     if profile_type == 'investor': 
      initial['investor_type'] = profile.investor_type 
     elif profile_type == 'manager': 
      profile.investor_type.required = False 
     # // Failed 
     user_info_form = UserInfoForm(initial=initial) 
    context['user_info_form'] = user_info_form 
    context['profile_type'] = profile_type 
    context['profile'] = profile 
    return render_to_response('edit/profile.html', context, context_instance=RequestContext(request)) 

감사합니다. 미리 감사드립니다. 그러면, 사용자의 유형을 확인하는 양식 깨끗한 방법을 만들

required=False 

:

+0

투자자 유형에 required = False를 설정하면 어떻게됩니까? – joshcartme

+0

어떤 라인에서 예외가 발생 했습니까? 또한 내 대답을 살펴보고 도움이되는지 확인하십시오. 필자는 전역 적으로 required = False로 설정하고 clean 메소드를 사용하는 것이 더 나은 접근 방법이라고 생각합니다. – joshcartme

답변

2

난에 투자 유형을 설정합니다. 그것의 투자자와 그들이 investor_type을 지정하지 않은 경우 오류가 발생합니다. 매니저라면 끝내 줘. https://docs.djangoproject.com/en/dev/topics/db/models/#field-options

체크 아웃 양식의 청소 방법에 대한이 문서 :

당신은 또한 당신의 프로필 모델 investor_type 공백과 null이 될 수 있는지 확인해야합니다. https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

+0

AttributeError가 발생 했습니까? 그러나 나는 그것을 발견했다. 감사합니다. – Modelesq

관련 문제