我使用Django 1.9。我创建了一个视图来添加一个新对象并且它可以工作,但是当创建一个视图来编辑对象时,我有两个不同的问题:
Exception Type: NameError
和Exception Value: name 'album' is not defined
相关的错误 - &gt ; mod_artist form = AlbumForm(instance=album)
Exception Type:
UnboundLocalError
和Exception Value: local variable 'artist' referenced before assignment
涉及 - > mod_artist form = ArtistForm(instance=artist)
我的views.py
文件是
from django.shortcuts import render, redirect, get_object_or_404
from .forms import *
from .models import *
def mod_album(request):
if request.method == "POST":
form = AlbumForm(request.POST, instance=album)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('http://127.0.0.1:8000/')
else:
form = AlbumForm(instance=album)
return render(request,'polls/mod_album.html',{'form':form})
def mod_artist(request):
if request.method == 'POST':
form = ArtistForm(request.POST, instance=artist)
if form.is_valid():
artist = form.save(commit=False)
artist.author = request.user
artist.save()
return redirect('http://127.0.0.1:8000/')
else:
form = ArtistForm(instance=artist)
return render(request,'polls/mod_artist.html',{'form':form})
我的index.html
文件是
...
<body>
<div class="container-fluid">
<div class="header">
<div>
<h1>personal library</h1>
</div>
<div id="wrap-nav">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active"><a href="new_album" class="navbar-link">+ add album</a></li>
<li class="active"><a href="mod_album" class="navbar-link">- edit album</a></li>
<li class="active"><a href="new_artist" class="navbar-link">+ add artist</a></li>
<li class="active"><a href="mod_artist" class="navbar-link">- edit artist</a></li>
<li class="active"><a href="result" class="navbar-link">view the list of albums</a></li>
</ul>
</div>
</div>
</nav>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
{% for album in albums %}
<ul>
<li>Album name: {{album.name}}</li>
<li>Artist: {{album.artist}}</li>
<li>Genre: {{album.genre}}</li>
<li>Songs: , </li>
<li>Vote: {{album.vote}}</li>
</ul>
<hr />
{% endfor %}
</div>
<div class="col-xs-6 col-md-6">
{% for artist in artists %}
<ul>
<li>Artist name: {{artist.name}}</li>
</ul>
<hr />
{% endfor %}
</div>
</div>
</div>
</body>
...
我的urls.py
文件是
from django.conf.urls import url
from . import views
urlpatterns=[
...
url(r'^new_album/$', views.new_album, name='new_album'),
url(r'^mod_album/$', views.mod_album, name='mod_album'),
url(r'^new_artist/$', views.new_artist, name='new_artist'),
url(r'^mod_artist/$', views.mod_artist, name='mod_artist'),
]
和我的forms.py
文件是
from django import forms
from .models import *
class AlbumForm(forms.ModelForm):
class Meta:
model = Album
fields = ['name','artist','year','genre','vote']
class ArtistForm(forms.ModelForm):
class Meta:
model = Artist
fields = ['name']
感谢我们的时间。