将参数转换为字符串

时间:2015-05-15 09:47:42

标签: python django django-views

以前从未使用过Struct。当雇用开发人员进行某些工作时,他使用了这个,但它不起作用。开发人员没有回答......请问有人可以帮忙解决问题吗?

views.py开始,您可以在Struct() argument 1 must be string, not unicode中看到错误'InvId': str(struct.unpack('=H', urandom(2))[0]),。那么,如何将其转换为字符串?

@login_required
def userprofile(request, username):

    extra_context = dict()

    if request.POST:
        user_form = UserForm(request.POST, instance=request.user)
        user_profile = UserProfileForm(request.POST, request.FILES,
                                       instance=request.user.profile)
        if user_form.is_valid():
            user_form.save()
        if user_profile.is_valid():
            user_profile.save()
    else:
        user_form = UserForm(
            instance=request.user,
            initial={
                'first_name': request.user.first_name,
                'last_name': request.user.last_name,
                'email': request.user.email,
            })
        user = request.user
        profile = user.profile
        user_profile = UserProfileForm(instance=profile)

    extra_context['user_form'] = user_form
    extra_context['user_profile'] = user_profile
    extra_context['robo_form'] = RobokassaForm(initial={
        'UserId': request.user.id,
        'OutSum': 1000,
        'InvId': struct.unpack('=H', urandom(2))[0],
        'Email': request.user.email,
    })

    return render_to_response('profile.html', extra_context, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

struct.unpack('=H', urandom(2))[0]只是愚蠢。只需以可读的方式生成一个整数:

'InvId': random.randrange(2**16),