[英]How update models modelforms and django
i have a problem when i try update the data for model usuario 当我尝试为模型usuario更新数据时遇到问题
this is my model 这是我的模特
class Usuario(models.Model):
user = models.ForeignKey(User)
nombres = models.CharField(max_length = 50)
correo = models.EmailField()
class Meta:
db_table = u'utp_users'
def __str__(self):
return str(self.nombres.encode('utf-8') )
this is mi form. 这是mi形式。 py py
class UsuarioForm(forms.ModelForm):
class Meta:
model = Usuario
fields = ['nombres','correo']
my url 我的网址
url(r'^menu/update/(?P<usuario_id>\d+)$', 'utpapp.views.update'),
this my view update 这是我的观点更新
@login_required(login_url='/')
def update(request,usuario_id):
form = UsuarioForm(request.POST)
if form.is_valid():
user = Usuario.objects.get(pk=usuario_id)
form = UsuarioForm(request.POST, instance = user)
form.save()
return redirect('/menu/')
else:
user = Usuario.objects.get(pk = usuario_id)
form = UsuarioForm(instance=user)
return render_to_response('form.html',{ 'form':form }, context_instance=RequestContext(request))
and the template i am do this 和我做的模板
<a title="Editar informacion" href="/menu/update/{{usuario.id}}"><img src="/media/imagenes/usuario.png" class=" col-xs-3 col-md-7 quitar-float" alt="Editar informacion" ></a>
the problem is when i select the option update i get the this msj "Page not found (404)" 问题是当我选择选项更新时,我得到此msj“找不到页面(404)”
but i change in template href {{usuario.id}} for {{user.id}} is work but with user different what is the problem ?? 但是我更改了{{user.id}}的模板href {{usuario.id}},但是可以与用户不同,这是什么问题?
您忘记将usuario
变量传递给模板。
Try this, you need to pass usuario
as context to the template, and you can much simplify the code (especially the form for GET/POST, they are basically the same form, so don't repeat it) as like: 尝试此操作,您需要将usuario
作为上下文传递给模板,并且可以大大简化代码(尤其是GET / POST的形式,它们基本上是相同的形式,因此不再重复),如下所示:
from django.shortcuts import get_object_or_404
@login_required(login_url='/')
def update(request,usuario_id):
user = get_object_or_404(Usuario, pk=usuario_id)
form = UsuarioForm(request.POST or None, instance=user)
if request.method == 'POST' and form.is_valid():
form.save()
return redirect('/menu/')
# you need to pass `usuario` as part of the context to template
# so you can access usuario.id in template
return render_to_response('form.html',{ 'form':form, 'usuario': user }, context_instance=RequestContext(request))
Also make sure you have a url
route for /menu/
, or else redirect
will get you 404
. 还要确保您具有/menu/
的url
路由,否则redirect
将使您获得404
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.