2017-12-18 11 views
0

ユーザーのプロファイルを更新するフォームを作成しましたが、実行するとエラーは発生しませんが、ページを開くときにヘッダーが表示されますが、UpdateBioFormは表示されません。第二に、誰かの伝記を保存するために大きなテキストボックスを作成する方法が不思議でした。Django - Modelformはレンダリングされません

Models.py

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    biography = models.CharField(max_length = 255, default = '') 
    city = models.CharField(max_length=100, default = '') 
    website = models.URLField(default='') 
    image = models.ImageField(upload_to='profile_image', blank=True) 

    def setdefault(self, default_path='/profile_image/Default.jpg'): 
     if self.image: 
      return self.image 
     return default_path 

    def __str__(self): 
     return self.user.username 

Forms.Py

class UpdateBioForm(forms.ModelForm): 

    class Meta: 
     model = UserProfile 
     fields = (
      'biography', 
      'city', 
      'website' 
     ) 

    def save(self, commit=True): 
     savedBio = super(UpdateBioForm, self).save(commit=False) 
     savedBio.biography = self.cleaned_data['biography'] 
     savedBio.city = self.cleaned_data['city'] 
     savedBio.website = self.cleaned_data['website'] 

     if commit: 
      savedBio.save() 

     return savedBio 

Views.py

def update_bio(request): 
    if request.method == 'POST': 
     form = UpdateBioForm(request.POST, instance=request.user) 

     if form.is_valid(): 
      form.save() 
      return redirect('/') 
    else: 
     form = UpdateBioForm(instance=request.user) 
    args = {'form':form} 
    return render(request, 'accounts/update_bio.html') 

urls.py

url(r'^profile/updatebio/$',views.update_bio, name='update_bio'), 

{% extends 'base.html' %} 

{% block body %} 
<div class="container"> 
    <h1>Update Biography</h1> 
    <form method="post"> 
     {% csrf_token %} 
     {{ form.as_p }} 
     <button type="submit">Submit</button> 
    </form> 
</div> 
{% endblock %} 
+0

なぜ、フォームの 'save()'メソッドをオーバーライドしますか? –

答えて

1

update_bio.htmlあなたのrender()メソッドに任意のコンテキストを渡していません - あなたはargsを定義するが、その変数に何もしません。それを次のように変更してください:

args = {'form':form} 
return render(request, 'accounts/update_bio.html', context=args) # <-- You're missing context 
+0

はい、これは機能しました。私は一つの言葉が欠けているとは信じられません。しかし、伝記行は一行で表示され、入力することができます。どのように大きなテキストボックスを得ることができますか? – lordVader

+0

テキストボックスの問題への回答については、この質問をご覧ください:https://stackoverflow.com/questions/8761106/how-can-i-get-a-textarea-from-modelmodelform – solarissmoke

関連する問題