python - request.method == 'POST' is not working in Django -
i created form in template insert data in database form not working.when submitted form nothing happened.please review code , give me suggestion.
add.html template file:
<h2>add article</h2> <form action="" method="post"> {% csrf_token %} <label>title</label> <input type="text" name="title" placeholder="enter title"> <label>category</label> <select name="cate"> <option value="">select category</option> {% cat in %} <option value="{{ cat.cate }}">{{ cat.cate }} </option> {% endfor %} </option> </select> <label>discription</label> <textarea name="desc" rows="15"> </textarea> <input type="submit" value="submit" class="btn btn-default"> </form>
i created 2 views.in first view rendered categories add in form select menu , 2nd view handling form
views.py
from django.shortcuts import render, redirect .models import article, category def get_category(request): = category.objects.all() context = { 'get':get } return render(request, 'blog/add.html', context) def add(request): if request.method == 'post': title = request.post['title'] cate = request.post['cat'] desc = request.post['desc'] art = article(title=title, disc=desc, cat=cate) art.save() return redirect('blog/index.html') else: return render(request, 'blog/add.html')
models.py
from django.db import models class category(models.model): cate = models.charfield(max_length=100) def __str__(self): return self.cate class article(models.model): title = models.charfield(max_length=250) disc = models.textfield() cat = models.foreignkey(category, verbose_name="category") posted = models.datetimefield(auto_now_add=true, editable=false) updated = models.datetimefield(auto_now=true) def __str__(self): return self.title
urls.py
from django.conf.urls import url .import views app_name = 'blog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^add/$', views.get_category, name='category'), url(r'^add/$', views.add, name='add'), ]
in case every time action go get_category, because django find first match urls , use action.
you can create 1 function case: in views.py
def category(request): if request.method == 'post': title = request.post['title'] # update start cat = request.post['cat'] cate = category.objects.get(pk=cat) # update end desc = request.post['desc'] art = article(title=title, disc=desc, cat=cate) art.save() return redirect('blog/index.html') = category.objects.all() context = { 'get':get } return render(request, 'blog/add.html', context)
in urls.py
urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^add/$', views.get_category, name='category'), # !! comment or remove last urls # url(r'^add/$', views.add, name='add'), ]
i edit if , rebuild logic django forms better.
wiki
Comments
Post a Comment