Django - 如何通过视图保存表单值?

时间:2016-11-23 21:48:41

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

您好我正在尝试创建一个只有外键的模型的新实例。 因此我写了两个观点。 在视图" registerfighter"我有一个包含两个表的表。每个都有一个值,战斗机和重量级。我通过radiobuttons选择并提交数据。 但是我得到了

错误:registerfighter_save()缺少2个必需的位置参数:' f'和' w'

帖子信息说明了名称和链接值:

名称:f,价值:' Fightername' 名称:w值:'重量'

我的网址:

url(r'^register/(?P<event_id>\d+)/$', views.registerfighter,
    name='registerfighter'),
url(r'^register/(?P<event_id>\d+)/save/$', views.registerfighter_save,
    name='registerfighter_save'),

我的观点:

def registerfighter(request, event_id):
    event = Event.objects.get(id=event_id)
    t = Team.objects.get(owner=request.user)
    fighter = Fighter.objects.filter(team=t)
    info = EventAdditionalInfo.objects.filter(event=event)

    context = {'event': event, 't': t, 'fighter': fighter, 'info': info}
    return render(request, 'events/registerfighter.html', context)

def registerfighter_save(request, event_id, f, w):
    reg = Registration(
        event=event_id,
        fighter=f,
        weight=w,
        owner=request.user)
    reg.save()
    return HttpResponseRedirect(reverse('events:events'))

我的模板:

<form action="{% url 'events:registerfighter_save' event.id %}" method="post">
{% csrf_token %}
    <table class="table table-bordered">
        <tr>
            <td>
                <table class="table" border=0>
                    <!--- List of all own fighters--->
                    {% for f in fighter %}
                        <tr><td><input type="radio" name="f" value="{{f}}" id="f" /> {{f}}</td></tr>
                    {% endfor %}
                </table>
            </td>
            <td>
                <table class="table">
                    <!--- List of all weightclasses--->
                    {% for i in info %}
                        <tr><td><input type="radio" name="w" value="{{i}}" id="w"/> {{ i.weight }}</td></tr>
                    {% endfor %}
                </table>
            </td>
        </tr>
        <tr>
            <td colspan=2><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>

1 个答案:

答案 0 :(得分:0)

从表单发布的所有值都位于$('#aTable select').each(function(){ console.log(this.options[this.selectedIndex].text); });,以获得<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="aTable"> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> </div>request的值,您必须在f中添加:

w

您的registerfighter_save必须是这样的:

w = request.POST.get("w", "")
w = request.POST.get("f", "")