无法使用函数从一个视图访问变量到另一个视图?

时间:2016-02-04 06:41:41

标签: django python-2.7 django-forms django-templates django-views

我在Django写了一份注册表。我试图将从view1(register_user)成功注册的用户名传递给view2(register_success)。这样用户就可以在注册成功页面上看到他的名字。 以下是2个观点

视图1

def register_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
#Function for retrieving username from the form
            def give_username():
                return form.cleaned_data.get["username"]
            return HttpResponseRedirect('/accounts/register_success')

        else:
             form = UserCreationForm()
    args = {}
    args.update(csrf(request))
    args['form'] = UserCreationForm()
    return render(request,'register.html',args)

视图2

def register_success(request):
    full_name = register_user(request).give_username
    return render (request,'register_success.html',{'full_name':full_name})

register_success.html

{% extends "base.html" %}
{% block content %}
           <h2>Hey {{ full_name }}, Greetings .. You have registered successfully !</h2>
           <p>Click <a href="/accounts/login/">here</a> to login again</p>
{% endblock %}

我没有使用会话来存储变量,因为它可能是一个不好的做法。 因此,在尝试上述代码时,我收到此错误。

AttributeError at /accounts/register_success/
'HttpResponse' object has no attribute 'give_username'
Request Method:     GET
Request URL:    http://127.0.0.1:8000/accounts/register_success/
Django Version:     1.9.2
Exception Type:     AttributeError
Exception Value: 

'HttpResponse' object has no attribute 'give_username'
Exception Location:     /home/harish/django/django/django_test/django_test/views.py in register_success, line 56
Python Executable:  /home/harish/django/django/bin/python
Python Version:     2.7.6
Python Path:    

['/home/harish/django/django/django_test',
 '/home/harish/django/django/local/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg',
 '/home/harish/django/django/lib/python2.7/site-packages/Django-1.9.2-py2.7.egg',
  '/home/harish/django/django/lib/python2.7']
Server time:    Thu, 4 Feb 2016 05:44:16 +0000

我在访问用户名变量时出错了吗?

1 个答案:

答案 0 :(得分:2)

您无法通过从外部视图调用任意变量来访问该视图。您可以将数据作为URL参数或消息传递。

使用网址参数:

def registration(request):
    do_registration()
    return redirect(reverse('registration_success') + '?u=%s' % get_username)

def registration_success(request):
    username = request.GET.get('u', None)
    return render(request, 'my_template', {'username': username})

或通过消息:

from django.contrib.messages import get_messages

def my_view(request):
    # Process your form data from the POST, or whatever you need to do

    # Add the messages, as mentioned above
    messages.add_message(request, messages.INFO, form.cleaned_data['name'])

    return HttpResponseRedirect('/other_view_url/')

def other_view(request):
    storage = get_messages(request)
    name = None
    for message in storage:
        name = message
        break
    return render(request, 'general/other_view.html', {'name': name})

取自this answer的第二个片段。