获取forms.py的用户对象

时间:2014-12-01 08:46:34

标签: python django

我有一个名为个人资料的应用,它只利用了django-registration-redux模块。我正在尝试创建一个允许用户使用其中已有的信息进行编辑的表单,但它不会显示出来。我可以在没有信息的情况下显示它,但不会显示已存在的配置文件信息。

urls.py

from django.conf.urls import url
from profiles import views

urlpatterns = [
    url(r'^(?P<username>[-\w]+)/$', views.single, name='profile_single'),
    url(r'^(?P<username>[-\w]+)/edit/$', views.edit, name="profile_edit"),
] 

views.py

def edit(request, username):
    instance = Profile.objects.get(user=username)
    # It would be good to have an in depth understanding of what the actual request module does
    if request.user == instance.user:
        form = ProductForm(request.POST or None, instance = instance)

    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.slug = slugify(form.cleaned_data['title'])
        profile.save()
        return HttpResponseRedirect('/user/%s'%(user.username))
    return render_to_response("profiles/edit.html", locals(), context_instance=RequestContext(request))

我收到的错误是:

  

异常值:基数为10的int()的文字无效:&#39; admin&#39;

1 个答案:

答案 0 :(得分:5)

您需要检查username模型的User字段。

为此,请替换以下行:

instance = Profile.objects.get(user=username)

使用:

instance = Profile.objects.get(user__username=username)