django在随后的提交中添加引号

时间:2016-10-17 00:33:50

标签: django

这里的目标是:当用户提交表单时,使用一个视图将提交的数据发送到数据库,然后重定向回到表单,但预先填充了数据。这主要是工作,但关于我的实现的一些事情是在字符串周围包含额外的引号。现在,我只是使用超简单的形式,顺便说一句。我输入Billy,然后预先弹出:"Billy",如果我再次点击提交,它会返回:"\"Billy\"",然后是"\"\\\"Billy\\\"\"",依此类推(如就我所测试而言,无论如何。

相关观点是:

def editUsers(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = usersForm(request.POST)
        # check whether it's valid:
        # process the data in form.cleaned_data as required
        # redirect to a new URL:
        name = json.dumps(form.data['user_name'])
        request.session['editUserName'] = name

        # call out to limboLogic.py to update values

        test = name
        return redirect('../users')
    # if a GET (or any other method) we'll create a blank form
    else:
        return redirect('../users')

from .forms import *

def users(request):
    form = None

    if 'editUserName' not in request.session:
        # create a blank form
        form = usersForm()
    else:
        # form = equipmentForm(initial='jim') - used to make sure I was branching the if/else correctly
        form = usersForm(initial={'user_name':request.session['editUserName']}, auto_id=False) #limboLogic.GetUserInfo(name))
    return render(request, 'limboHtml/UserManagement.html', {'form': form})

形式简单:

class usersForm(forms.Form):
    user_name = forms.CharField(label='New User\'s  name', max_length=100)

,模板是:

{% extends "base.html" %}

{% block content %}
 <div class="row">
    <p>This is the user management page</p><br>
    <form action="/edit/users.html" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="OK">
    </form>
    <br><p class="bold">This is below the form</p>
  </div>
{% endblock %}

想法?

1 个答案:

答案 0 :(得分:0)

我不能完全说出这里的内部情况,但问题涉及到我使用的是json类。我使用this site作为指南并设法解决问题。请注意,关键方面是在第二个if:

name = form.cleaned_data['user_name']工作正常,

name = json.dumps(form.data['user_name'])

现在的整个功能:

def editUsers(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = usersForm(request.POST)
        # check whether it's valid:
        # process the data in form.cleaned_data as required
        # redirect to a new URL:
        if form.is_valid():
            name = form.cleaned_data['user_name']
            # name = json.dumps(form.data['user_name'])
            request.session['editUserName'] = name

            # call out to limboLogic.py to update values

            test = name
            return redirect('../users')
    # if a GET (or any other method) we'll create a blank form
    return redirect('../users')