使用djang在数据库中保存值

2024-10-01 19:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自定义表单,每当我获取要保存在数据库中的表单值时,它就会显示一个错误(applicationform()获得了意外的关键字参数“job_title”),并且这些值不会保存在表中。在

在视图.py:-

def applicationvalue(request):
    if request.method == 'POST':

            getjobtitle = request.POST['jobtitle']


            getintable = applicationform(job_title=getjobtitle)
            getintable.save()

            print getjobtitle
            return HttpResponse(getintable)

    else:
        return render_to_response('registration/applicationform.html')

我的表格是:

^{pr2}$

每当我从表单获取值以将值保存在表字段“job_title”中时,它将显示一个错误:

applicationform()获得意外的关键字参数“job\u title”


Tags: py视图数据库表单参数returntitlerequest
2条回答

将html中的input字段名更改为job_title

<input name="job_title" type="text" id="u_jobtitle" class="input-xlarge" value=" " />
      -^ changed 

然后在视图中做

^{pr2}$

如果您使用相同的表单来呈现html而不是手工编码它,这会更好。在

applicationform构造函数应将request.POST作为参数。 但在我看来,你没有以“正确”的方式使用django表单。我认为你的观点不符合django使用形式的哲学。在

在您的情况下,您应该有一个模型:

from django.db import models

class Application(models.Model):
    job_title = models.CharField(max_length=100)

基于此模型,可以声明一个ModelForm:

^{pr2}$

然后您可以在视图中使用此窗体

def applicationvalue(request):
    if request.method == 'POST':

        form = ApplicationForm(request.POST)
        if form.is_valid():
            #This is called when the form fields are ok and we can create the object
            application_object = form.save()

            return HttpResponse("Some HTML code") # or HttResponseRedirect("/any_url")

    else:
        form = ApplicationForm() 

    #This called when we need to display the form: get or error in form fields
    return render_to_response('registration/applicationform.html', {'form': form})

最后,您应该有一个registration/applicationform.html模板,它类似于:

{% extends "base.html" %}

{% block content %}
<form action="" method="post">{% csrf_token %}
   <table>
      {{form.as_table}}
   </table>
   <input type="submit" value="Add">
</form>
{% endblock %}

我希望有帮助

相关问题 更多 >

    热门问题