2015-05-30 155 views
0

現在已經讀了好幾個小時了。仍然不知道這是如何工作的。 我試圖在django中驗證一個簡單的用戶配置文件表單,但函數總是返回 - uhm - 什麼都沒有(?)...即使我嘗試打印出form.is_valid()也沒有任何回報。django modelform.is_valid()沒有結果,沒有錯誤,什麼都沒有

下面的代碼,也許有人有任何想法:

FORMS.PY

class UserForm(ModelForm): 
class Meta: 
    model = User 
    fields = ['username', 'password', 'email', 'first_name', 'last_name'] 

def __init__(self, instance): 
    super(UserForm, self).__init__() 
    self.fields['username'].widget.attrs['readonly'] = True 
    self.fields['password'].widget = forms.PasswordInput() 
    for field in self.fields: 
     self.fields[field].widget.attrs['class'] = 'form-control' 
     self.fields[field].widget.attrs['value'] = getattr(instance, field) 

class UserDataForm(ModelForm): 
class Meta: 
    model = UserProfile 
    fields = ['picture', 'academicDiscipline', 'studentNumber', 'location'] 

def __init__(self, instance): 
    super(UserDataForm, self).__init__() 
    for field in self.fields: 
     if field != 'picture': 
      self.fields[field].widget.attrs['class'] = 'form-control' 
      self.fields[field].widget.attrs['value'] = getattr(instance, field) 

VIEWS.PY

curUser = User.objects.get(pk = request.user.id) 
curUserProfile = curUser.userprofile 
success_msg, error_msg = None, None 

if request.method == 'POST': 
    user = User.objects.get(username__exact = request.POST['username']) 
    userProfile = None 
    user.email = request.POST['email'] 
    user.first_name = request.POST['first_name'] 
    user.last_name = request.POST['last_name'] 
    userForm = UserForm(user) 
    if userForm.is_valid(): 
     user = userForm.save() 
     user.save() 
     success_msg = 'Benutzerdaten wurden erfolgreich aktualisiert.' 
     userProfile = user.userprofile 
     userProfile.academicDiscipline = request.POST['academicDiscipline'] 
     userProfile.studentNumber = request.POST['studentNumber'] 
     userProfile.location = request.POST['location'] 
     userDataForm = UserDataForm(userProfile) 
     if userDataForm.is_valid(): 
      userDataForm.save() 
      userDataForm = userDataForm 
      success_msg = 'Benutzerdaten wurden erfolgreich aktualisiert.' 
     else: 
      error_msg = "userProfileData failure" 
    else: 
     error_msg = 'userData failure' 

    context = { 
     'active_page' : 'settings', 
     'nav': Nav.nav, 
     'success_msg': success_msg, 
     'error_msg': error_msg, 
     'userForm': UserForm(curUser), 
     'userDataForm': UserDataForm(curUserProfile) 
    } 
    return render(request, 'settings.html', context) 
else: 
    context = { 
     'active_page' : 'settings', 
     'nav': Nav.nav, 
     'userForm': UserForm(curUser), 
     'userDataForm': UserDataForm(curUserProfile) 
    } 
    return render(request, 'settings.html', context) 

SETTINGS.HTML

<form action="{% url 'twittur:settings' %}" method="post"> 
{% csrf_token %} 

    {{ userForm.non_field_errors }} 
    {{ userDataForm.non_field_errors }} 

    <div class="post" id="profilbild"> 

     <h4>Profilbild auswählen</h4> 

     <div class="col-xs-12 form-group"> 
      <div class="col-xs-12 text-center" style="vertical-align: bottom !important;"> 
       <img src="/picture/{{ user.picture }}" class="img-thumbnail" style="width: 100px;"> 
       <img src="/picture/{{ user.picture }}" class="img-thumbnail" style="width: 75px; margin-top: 26px;"> 
       <img src="/picture/{{ user.picture }}" class="img-thumbnail" style="width: 50px; margin-top: 50px;"> 
       <p class="help-block">Aktuelles Profilbild (100px, 75px, 50px). {{ user.picture }}</p> 
      </div> 
      <label class="form-label" for="avatarInput">Profilbild aktualisieren</label> 
      {{ userDataForm.picture }} 
      {{ userDataForm.picture.errors }} 
      <!--<input id="avatarInput" name="picture" type="file">--> 
     </div> 

    </div> 

    <div class="post" id="account"> 

     <h4>Accountverwaltung</h4> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="usernameInput">Username</label> 
      <!--<input name="userID" type="hidden" value="{{ user.id }}" />--> 
      {{ userForm.username }} 
      <!--<input class="form-control" id="usernameInput" name="username" type="text" value="{{ user.username }}" disabled />--> 
      <p class="help-block">Der Username kann nicht ver&auml;ndert werden.</p> 
      {{ userForm.username.errors }} 
     </div> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="emailInput">E-Mail</label> 
      {{ userForm.email }} 
      {{ userForm.email.errors }} 
      <!--<input class="form-control" id="emailInput" name="email" type="email" value="{{ user.email }}" />--> 
     </div> 

     <div class="col-xs-12 col-sm-6 form-group"> 
      <label class="control-label" for="pw1Input">Passwort</label> 
      {{ userForm.password }} 
      {{ userForm.password.errors }} 
      <!--<input class="form-control" id="pw1Input" name="password" type="password" value="{{ user.password }}" />--> 
     </div>  
     <div class="col-xs-12 col-sm-6 form-group pull-right"> 
      <label class="control-label" for="pw2Input">Passwort bestätigen</label> 

      {{ userForm.password.errors }} 
      <!--<input class="form-control" id="pw2Input" type="password" value="{{ user.password }}" />--> 
     </div> 

    </div> 

    <div class="post" id="daten"> 

     <h4>Pers&ouml;nliche Daten</h4> 

     <div class="col-xs-12 col-sm-6 form-group"> 
      <label class="control-label" for="vornameInput">Vorname</label> 
      {{ userForm.first_name }} 
      {{ userForm.first_name.errors }} 
      <!--<input class="form-control" id="vornameInput" name="vorname" type="text" value="{{ user.first_name }}" />--> 
     </div>  
     <div class="col-xs-12 col-sm-6 form-group pull-right"> 
      <label class="control-label" for="nachnameInput">Nachname</label> 
      {{ userForm.last_name }} 
      {{ userForm.last_name.errors }} 
      <!--<input class="form-control" id="nachnameInput" name="nachname" type="text" value="{{ user.last_name }}" />--> 
     </div> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="studiengangInput">Studiengang</label> 
      {{ userDataForm.academicDiscipline }} 
      <!--<input class="form-control" id="studiengangInput" name="studiengang" type="text" value="{{ user.academicDiscipline }}" />--> 
      <p class="help-block">Über deinen Studiengang wirst Du bestimmten Gruppen zugeordnet.</p> 
      {{ userDataForm.academicDiscipline.errors }} 
     </div> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="matrikelNummerInput">Matrikel-Nummer</label> 
      {{ userDataForm.studentNumber }} 
      <!--<input class="form-control" id="matrikelNummerInput" name="matrikelnummer" type="number" value="{{ user.studentNumber }}" />--> 
      <p class="help-block">Über deine Matrikel-Nummer kannst Du eindeutig als Student der TU Berlin identifiziert werden.</p> 
      {{ userDataForm.studentNumber.errors }} 
     </div> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="wohnortInput">Wohnort</label> 
      {{ userDataForm.location }} 
      {{ userDataForm.location.errors }} 
      <!--<input class="form-control" id="wohnortInput" name="wohnort" type="text" value="{{ user.location }}" />--> 
     </div> 

    </div> 

    <div class="post" id="seite"> 

     <h4>Seiteneinstellungen</h4> 

     <div class="col-xs-12 form-group"> 
      <label class="control-label" for="stdSafetylevelSelect">Standard-Sicherheitsstufe</label> 
      <select class="form-control" id="stdSafetylevelSelect" name="safety"> 
       <option>public</option> 
       <option>Uni</option> 
       <option>Fakultät</option> 
       <option selected>Studiengang</option> 
      </select> 
     </div> 

    </div> 

    <div class="post" id="delete"> 

     <h4>Account vollst&auml;ndig l&ouml;schen</h4> 

     <div class="col-xs-12 form-group text-center"> 
      <p class="help-block">&Uuml;ber diesen Button kannst Du deinen Account vollst&auml;ndig von unserer Plattform entfernen. Zur Best&auml;tigung der L&ouml;schung erh&auml;lst Du eine E-Mail an deine uns bekannte E-Mail Adresse.</p> 
      <button type="button" class="btn btn-primary text-center" id="deleteButton">Account löschen</button> 
     </div> 

    </div> 

    <div class="col-xs-12 form-group text-center"> 
     <button type="submit" class="btn btn-primary" id="submitSettButton">Speichern</button> 
     <button type="reset" class="btn btn-default" id="resetSettButton">Zur&uuml;cksetzen</button> 
    </div> 

</form> 

我絕對沒有線索如何處理它。所以我會很感激每一種幫助!

迎接

回答

1

你永遠不POST數據傳遞到形式:所以它仍然綁定,並通過驗證不走。您需要做userDataForm = UserDataForm(request.POST, instance=userProfile)

更糟糕的是,您已經明確定義了表單的方法,因此它們甚至不接受除實例之外的任何參數 - 因此無法用數據填充。另外,他們實際上吞下了instance的參數,並且不會將它傳遞給超類,所以它被有效地忽略。你應該像這樣定義它們:

def __init__(self, *args, **kwargs): 
    instance = kwargs.get('instance') 
    super(UserDataForm, self).__init__(*args, **kwargs) 
+0

哇,非常感謝!這樣可行。還要感謝@YPCrumble。之前嘗試過,但沒有工作。現在我剩下一個概率了。我無法啓動userForm。 'userDataForm = UserDataForm(instance = curUserProfile)'工作正常,而'userForm = UserForm(instance = curUser)'不顯示任何表單域。雖然'curUser = User.objects.get(pk = request.user.id)'是'curUserProfile = curUser.userprofile' ...也許這是某種與表單衝突的類型? forms.py中的表單現在幾乎是相同的。有任何想法嗎? –

+0

好的,忘了吧。在行尾有''',破壞了userForm ...再次感謝! –

0

您需要通過直接傳遞request.POST給它實例化視圖窗體 - 你傳遞一個用戶模型實例。

嘗試:userForm = UserForm(request.POST)

相關問題