2017-04-08 70 views
0

我有一個自定義的Django用戶架構來管理角色或用戶類型[]:傳倍數Django的形式在上下文中的模板

  • StudentProfile
  • ProfessorProfile
  • ExecutiveProfile

由於我的AbstractBaseUser模型的一部分保持如此:

class User(AbstractBaseUser, PermissionsMixin): 

    email = models.EmailField(unique=True) 
    username = models.CharField(max_length=40, unique=True) 
    slug = models.SlugField(max_length=100, blank=True) 
    is_student = models.BooleanField(default=False) 
    is_professor = models.BooleanField(default=False) 
    is_executive = models.BooleanField(default=False) 

    other fields ... 

我有get_student_profile(),get_professor_profile()get_executive_profile()獲取配置文件用戶數據的方法。

我重寫save()方法在我的自定義模型User保存配置數據時is_student或is_professor或is_executive都在此刻被檢查創建一個用戶,其數據將被保存在相應的療法型號:

class StudentProfile(models.Model): 
    user = models.OneToOneField(User,on_delete=models.CASCADE) 
    slug = models.SlugField(max_length=100,blank=True) 
    origin_education_school = models.CharField(max_length=128) 
    current_education_school = models.CharField(max_length=128) 
    extra_occupation = models.CharField(max_length=128) 

class ProfessorProfile(models.Model): 
    CATHEDRAL_PROFESSOR = 'CATHEDRAL' 
    RESEARCH_PROFESSOR = 'RESEARCH' 
    INSTITUTIONAL_DIRECTIVE = 'DIRECTIVE' 

    OCCUPATION_CHOICES = (
     (CATHEDRAL_PROFESSOR, 'Cathedral Professor'), 
     (RESEARCH_PROFESSOR, 'Research Professor'), 
     (INSTITUTIONAL_DIRECTIVE, 'Institutional Directive'), 
    ) 
    user = models.OneToOneField(User,on_delete=models.CASCADE) 
    slug = models.SlugField(max_length=100,blank=True) 
    occupation = models.CharField(max_length=255,blank = False) 

class ExecutiveProfile(models.Model): 
    user = models.OneToOneField(User,on_delete=models.CASCADE) 
    slug = models.SlugField(max_length=100, blank=True) 
    occupation = models.CharField(max_length=255,blank = False) 
    enterprise_name = models.CharField(max_length=255,blank = False) 

我有形式給每個用戶的配置文件

class UserUpdateForm(forms.ModelForm): 
    class Meta: 
     widgets = {'gender':forms.RadioSelect,} 
     fields = ("username", "email", "is_student",   "is_professor", "is_executive",) 
     model = get_user_model() #My model User 

class StudentProfileForm(forms.ModelForm): 
    class Meta: 
     model = StudentProfile 
     fields = ('origin_education_school',current_education_school', 
      'extra_occupation') 

class ProfessorProfileForm(forms.ModelForm): 
    class Meta: 
     model = ProfessorProfile 
     fields = ('occupation',) 

class ExecutiveProfileForm(forms.ModelForm): 
    class Meta: 
     model = ExecutiveProfile 
     fields = ('occupation', 'enterprise_name', 'culturals_arthistic','ecological') 

我有這樣的URL來訪問用戶簡檔的

url(r"^profile/(?P<slug>[\w\-]+)/$", 
     views.AccountProfilesView.as_view(
      model=ProfessorProfile), 
      name='profile' 
    ), 

在我AccountProfilesView我管理的配置文件的形式,並將它們發送到模板

class AccountProfilesView(LoginRequiredMixin, UpdateView): 
    # All users can access this view 
    model = get_user_model() 
    success_url = reverse_lazy('dashboard') 
    template_name = 'accounts/profile_form.html' 
    fields = '__all__' 

    def get_context_data(self, **kwargs): 
     context = super(AccountProfilesView, self).get_context_data(**kwargs) 
     user = self.request.user 

     if not self.request.POST: 
      if user.is_student: 
       profile = user.get_student_profile() 
       context['userprofile'] = profile 
       context['form_student'] = forms.StudentProfileForm() 
      elif user.is_professor: 
       profile = user.get_professor_profile() 
       context['userprofile'] = profile 
       context['form_professor'] = forms.ProfessorProfileForm() 
       print ("profesor form is", context['form_professor']) 
      elif user.is_executive: 
       profile = user.get_executive_profile() 
       context['userprofile'] = profile 
       context['form_executive'] = forms.ExecutiveProfileForm() 
      elif user.is_student and user.is_professor and user.is_executive: 
       student_profile = user.get_student_profile() 
       professor_profile = user.get_professor_profile() 
       executive_profile = user.get_executive_profile() 
       context['student_profile'] = student_profile 
       context['professor_profile'] = professor_profile 
       context['executive_form'] = executive_profile 

       student_form = forms.StudentProfileForm() 
       professor_form = forms.ProfessorProfileForm() 

       executive_form = forms.ExecutiveProfileForm() 

       context['form_student'] = student_form 
       context['form_professor'] = professor_form 
       context['form_executive'] = executive_form 
     return context 

    def post(self, request, *args, **kwargs): 
     self.object = self.get_object() 
     context = super(AccountProfilesView, self).post(request, *args, **kwargs) 
     user = self.request.user 
     if user.is_student: 
      context['form_student'] = forms.StudentProfileForm(self.request.POST) 
     elif user.is_professor: 
      context['form_professor'] = forms.ProfessorProfileForm(self.request.POST) 
     elif user.is_executive: 
      context['form_executive'] = forms.ExecutiveProfileForm(self.request.POST) 

     elif user.is_student and user.is_professor and user.is_executive: 
      context['form_student'] = forms.StudentProfileForm(self.request.POST) 
      context['form_professor'] = forms.ProfessorProfileForm(self.request.POST) 
      context['form_executive'] = forms.ExecutiveProfileForm(self.request.POST) 

     return context 

    def form_valid(self, form): 
     context = self.get_context_data(form=form) 
     user = self.request.user 
     user = form.save() 
     if user.is_student: 
      student = context['form_student'].save(commit=False) 
      student.user = user 
      student.save() 
     elif user.is_professor: 
      professor = context['form_professor'].save(commit=False) 
      professor.user = user 
      professor.save() 
     elif user.is_executive: 
      executive = context['form_executive'].save(commit=False) 
      executive.user = user 
      executive.save() 

     elif user.is_student and user.is_professor and user.is_executive: 
      student = context['form_student'].save(commit=False) 
      student.user = user 
      student.save() 

      professor = context['form_professor'].save(commit=False) 
      professor.user = user 
      professor.save() 

      executive = context['form_executive'].save(commit=False) 
      executive.user = user 
      executive.save() 
     return super(AccountProfilesView, self).form_valid(form) 

發生什麼事是,在get_context_data()方法context['form_professor'] = forms.ProfessorProfileForm()context['form_executive'] = forms.ExecutiveProfileForm()已不傳遞到模板

當我創建具有學生檔案(is_student)或教授檔案(is_professor)或具有執行檔案(is_executive)的用戶都可以正常工作,這意味着,將用戶檔案分開(只有一個用戶ofile)渲染表單配置文件根據字段顯示錶單以分別進行配置文件。

在這個意義上說,在get_context_data()部分,下面的代碼工作,並通過形成相應:

if user.is_student: 
    profile = user.get_student_profile() 
    context['userprofile'] = profile 
    context['form_student'] = forms.StudentProfileForm() 
elif user.is_professor: 
    profile = user.get_professor_profile() 
    context['userprofile'] = profile 
    context['form_professor'] = forms.ProfessorProfileForm() 
    print ("profesor form is", context['form_professor']) 
elif user.is_executive: 
    profile = user.get_executive_profile() 
    context['userprofile'] = profile 
    context['form_executive'] = forms.ExecutiveProfileForm() 

但是,當我創建具有三個配置文件檢查(is_studentis_professoris_executive)的用戶只要通過context['form_student'] = forms.StudentProfileForm()

我在我顯示數據模板:

{% extends 'layout.html' %} 
{% load bootstrap3 %} 
{% block title_tag %}Accounts | Profile | iHost {{ block.super }}{% endblock %} 
{% block body_content %} 
<div class="container"> 
    <h1>My Profile</h1> 
    <form method="POST"> 
     {% csrf_token %} 

     # I ask for user profile of a separate way 

     # Student Profile User 
     {% if userprofile.user.is_student %} 
     <br/><hr> 
      Student form 
      {% bootstrap_form form_student %} 
     {% endif %} 

     # Professor Profile User 
     {% if userprofile.user.is_professor %} 
      {{ form_professor.as_p }} 
     {% endif %} 

     # Executive Profile User  
     {% if userprofile.user.is_executive %} 
      {{ form_executive.as_p }} 
      {% comment %} {% bootstrap_form form_executive %}{% endcomment %} 
     {% endif %} 

     # I ask for an user with three profiles 

     {% if userprofile.user.is_student %} 
     <br/><hr> 
     Student form 
      {% if userprofile.user.is_professor %} 
       {% if userprofile.user.is_executive %} 
        {% bootstrap_form form_student %} 
        <br/><hr> 
        Professor form does not arrive 
        {{ form_professor.as_p }} 
        {% comment %} {% bootstrap_form form_professor %}{% endcomment %} 
        <br/><hr> 
        Executive form does not arrive 
        {{ form_executive.as_p }}  
        {% comment %} 
        {% bootstrap_form form_student %} 
        {% bootstrap_form form_professor %} 
        {% endcomment %}   
       {% endif %} 
      {% endif %} 
     {% endif %} 
<br /><br /><br /> 

     <input type="submit" value="Save Changes" class="btn btn-default"> 
    </form> 
</div> 

{% endblock %} 

當我用三個配置文件登錄用戶時,我渲染配置文件表單時,出現與呈現的表單相關的此行爲。 form_professor和form_executive不renderized

enter image description here

通過這個原因,我認爲,教授和行政形式情況下,並沒有被傳遞到模板,

這也得到驗證,因爲如果我刪除評論並使用我的模板django-bootstrap3應用程序,我不能讓form_professorform_executive情況下形成

  • form_professor沒有到達模板 enter image description here

  • form_executive不到達模板 enter image description here

另外,雖然我覺得這樣我可以在我的模板進行更好的條件邏輯。

這裏發生了什麼事。 我的想法是可以根據配置文件向用戶在一個模板中呈現配置文件表單。

我非常感謝他們的支持。


UPDATE


根據下@Rohan答案,這是真的,在el ... if語句是問題的根源。現在這些表格呈現良好。

AccountProfilesView住宿的是這樣的:

class AccountProfilesView(LoginRequiredMixin, UpdateView): 
    # All users can access this view 
    model = get_user_model() 
    #success_url = reverse_lazy('dashboard') 
    template_name = 'accounts/profile_form.html' 
    fields = '__all__' 

    def get_context_data(self, **kwargs): 
     context = super(AccountProfilesView, self).get_context_data(**kwargs) 
     user = self.request.user 

     if not self.request.POST: 
      if user.is_student: 
       profile = user.get_student_profile() 
       context['userprofile'] = profile 
       context['form_student'] = forms.StudentProfileForm() 
      if user.is_professor: 
       profile = user.get_professor_profile() 
       context['userprofile'] = profile 
       context['form_professor'] = forms.ProfessorProfileForm() 
       print ("profesor form is", context['form_professor']) 
      if user.is_executive: 
       profile = user.get_executive_profile() 
       context['userprofile'] = profile 
       context['form_executive'] = forms.ExecutiveProfileForm() 
     return context 

    def post(self, request, *args, **kwargs): 
     self.object = self.get_object() 
     context = super(AccountProfilesView, self).post(request, *args, **kwargs) 
     user = self.request.user 
     if user.is_student: 
      context['form_student'] = forms.StudentProfileForm(
       self.request.POST) 
     if user.is_professor: 
      context['form_professor'] = forms.ProfessorProfileForm(
       self.request.POST) 
     if user.is_executive: 
      context['form_executive'] = forms.ExecutiveProfileForm(
       self.request.POST) 
     return context 

    def form_valid(self, form): 
     context = self.get_context_data(form=form) 
     user = self.request.user 
     user = form.save() 
     if user.is_student: 
      student = context['form_student'].save(commit=False) 
      student.user = user 
      student.save() 
     if user.is_professor: 
      professor = context['form_professor'].save(commit=False) 
      professor.user = user 
      professor.save() 
     if user.is_executive: 
      executive = context['form_executive'].save(commit=False) 
      executive.user = user 
      executive.save() 
     return super(AccountProfilesView, self).form_valid(form) 

    def get_success_url(self): 
     return reverse('dashboard') 

但是現在,當我想保存形式的三個配置文件部署的產品,我得到這個錯誤信息。

File "/home/bgarcial/workspace/ihost_project/accounts/views.py", line 181, in post 
    context['form_student'] = forms.StudentProfileForm(self.request.POST) 
    File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/http/response.py", line 142, in __setitem__ 
    value = self._convert_to_charset(value, 'latin-1', mime_encode=True) 
    File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/http/response.py", line 115, in _convert_to_charset 
    raise BadHeaderError("Header values can't contain newlines (got %r)" % value) 
django.http.response.BadHeaderError: Header values can't contain newlines (got '<tr><th><label for="id_origin_education_school">Origin education institute:</label></th><td><input id="id_origin_education_school" maxlength="128" name="origin_education_school" type="text" value="Universidad CES, Escuela de Ingeniería" required /></td></tr>\n<tr><th><label for="id_current_education_school">Current education institute:</label></th><td><input id="id_current_education_school" maxlength="128" name="current_education_school" type="text" value="Universidad CES" required /></td></tr>\n<tr><th><label for="id_extra_occupation">Extra occupation:</label></th><td><input id="id_extra_occupation" maxlength="128" name="extra_occupation" type="text" value="Networker" required /></td></tr>') 
[08/Apr/2017 16:45:05] "POST /accounts/profile/milena/ HTTP/1.1" 500 108439 

有當表格將被渲染。我一定要填寫這個表格與POST方法輸入的數據有些不方便,這個錯誤發生,這個畫面我得到:

enter image description here

回答

1

它在get_context_data函數中的python代碼的問題。您不應使用if..elif..添加所需的表格。如果用戶擁有所有個人資料,則只需輸入第一個if即可添加學生資料表單。

因此,您應該爲所有類型的配置文件單獨使用if語句。在這種情況下,您不需要最後的ifand ing適用於所有類型。

所以更改您的代碼

if user.is_student: 
    profile = user.get_student_profile() 
    context['userprofile'] = profile 
    context['form_student'] = forms.StudentProfileForm() 

#NOTE: no elif, only if 
if user.is_professor: 
    profile = user.get_professor_profile() 
    context['userprofile'] = profile 
    context['form_professor'] = forms.ProfessorProfileForm() 
    print ("profesor form is", context['form_professor']) 

if user.is_executive: 
    profile = user.get_executive_profile() 
    context['userprofile'] = profile 
    context['form_executive'] = forms.ExecutiveProfileForm() 

# NO need for last if user.is_student and user.is_professor and user.is_executive: 
+0

這是真的,在'EL ... if'語句是問題的根源。現在這些表格呈現良好。我的道歉,這是一個新手的錯誤。在這一刻,我的表格不會保存在數據庫中。我認爲Django明確表示要在'request.POST'實例中呈現並保存哪種形式。請在我的原始問題中檢查您的**我的**更新**。我很欣賞你的方向。 – bgarcial

+1

@bgarcial,我不確定那個錯誤。對新問題發佈新問題的良好做法。 – Rohan

+0

你有理由。這個錯誤我已經解決,但創建另一個問題,我發佈在其他問題。請讓我與你分享這個新問題,以防萬一你能支持我。 http://stackoverflow.com/q/43314269/2773461 – bgarcial

相關問題