Форум сайта python.su
всем привет,
модель
class Author(models.Model):
salutation = models.CharField(max_length=10)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
class Admin:
pass
def __unicode__(self):
return '%s %s' % (self.first_name, self.last_name)
def author_add (request):
if request.method == 'POST':
form = AuthorForm(request.POST)
if form.is_valid():
new_author = form.save()
return HttpResponseRedirect('/data/ok/')
else:
form = AuthorForm()
return render_to_response('author_form.html', {'form': form})
def author_edit (request, author_id):
author = get_object_or_404(Author, pk=author_id)
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
form.save()
return HttpResponseRedirect('/data/ok/')
else:
form = AuthorForm(instance=author)
return render_to_response('author_form.html', {'form': form})
Офлайн
def author_add (request, author=None):
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
new_author = form.save()
return HttpResponseRedirect('/data/ok/')
else:
form = AuthorForm()
return render_to_response('author_form.html', {'form': form})
def author_edit (request, author_id):
author = get_object_or_404(Author, pk=author_id)
return author_add(request, author )
Офлайн
Спасибо, идея ясна. Переписал так:
def author_add (request, author_id = None):
print "author_add %s"%author_id
if author_id:
author = get_object_or_404(Author, pk=author_id)
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
form.save()
return HttpResponseRedirect('/data/ok/')
else:
form = AuthorForm(instance=author)
else:
if request.method == 'POST':
form = AuthorForm(request.POST)
if form.is_valid():
new_author = form.save()
return HttpResponseRedirect('/data/ok/')
else:
form = AuthorForm()
return render_to_response('author_form.html', {'form': form})
def author_edit (request, author_id):
return author_add(request, author_id)
Офлайн
Насколько мне помнится, параметр instance=author может быть None и не нужны все эти нагромождения.
Офлайн