[英]Django how to save model in view
I'm new to Django. 我是Django的新手。 I'm having an issue where I can't save my model in the views.py. 我遇到了一个无法在views.py中保存模型的问题。 The concept is to have an input field where a user can type in a name, then using request.POST.get('attribute_name') I can save my model, but it's not working. 这个概念是有一个输入字段,用户可以在其中键入名称,然后使用request.POST.get('attribute_name')我可以保存我的模型,但它不起作用。 When I print a list of all the objects in that model there's nothing there, even though I don't get an error message during all of this. 当我打印该模型中所有对象的列表时,即使在所有这些过程中我都没有收到错误消息,也没有任何内容。
template: 模板:
<form id="save_form" method="post" action="{% url 'project_view.views.projectz_save' %}">
{% csrf_token %}
<table>
<tr>
<td>Project Name</td>
<td><input name="projectz_name"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
views.py: views.py:
def projectz_save(request):
try:
p = Project(name=request.POST.get('projectz_name'))
p.save()
return redirect('http://www.google.com/')
except:
return redirect('http://www.google.com/')
app urls: 应用网址:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
) )
site urls: 网站网址:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^project_view/', include('project_view.urls')),
I even put in some silly redirect code to google.com just to see if the views.py was even executing, but it's not working, though like I said there are no error messages, the page just refreshes. 我甚至将一些愚蠢的重定向代码添加到google.com只是为了查看views.py是否正在执行,但它不起作用,尽管我说没有错误消息,页面只是刷新。 I'm sure I'm doing wrong that's easy to fix, but I'm a noobie. 我确定我做错了很容易解决,但我是一个noobie。 :D :d
Ok I think maybe I spotted the problem. 好吧,我想也许我发现了问题。 The view
is not executing because you have defined three urls with the exact regex
in your project urls.py
: view
未执行,因为您已在项目urls.py
定义了三个具有完全regex
URL:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.register, name='register'),
url(r'^$', views.projectz_save, name='project_save'),
)
Django match it's urls by iterating over the patterns in the way they appeared so in that file all urls will match index
. Django通过以他们出现的方式迭代模式匹配它的url,因此在该文件中所有url将匹配index
。 That's probably the reason why the page appears to be refreshing. 这可能就是为什么页面看起来令人耳目一新的原因。 Try to modify this a little: 尝试稍微修改一下:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register$', views.register, name='register'),
url(r'^save$', views.projectz_save, name='project_save'),
)
This way you can execute the projectz_save
method in the views.py
if the action
of the form matches the url regex. 这样,如果表单的action
与url正则表达式匹配,则可以在views.py
执行projectz_save
方法。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.