Reputation: 435
I'm new to Django. I'm having an issue where I can't save my model in the 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. 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:
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. I'm sure I'm doing wrong that's easy to fix, but I'm a noobie. :D
Upvotes: 3
Views: 6005
Reputation: 29794
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
:
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
. 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.
Hope this helps!
Upvotes: 7