HttpRequest after form method in django? - python

I'm new in django, and I can't to figure out how to redirect site to main page after submit.
I read here, and in others places that I need to return HttpResponseRedirect in method.
But my form looks that:
#login_required
##staff_member_required
def hero_detail_create_view(request):
#creating by form
form = HeroCreateModelForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
slugCreate = str.lower(form.cleaned_data.get('name') + "-" + form.cleaned_data.get('nickname'))
obj.slug = slugCreate.replace(" ","")
obj.user = request.user
obj.save()
form = HeroCreateModelForm()
template_name='form.html'
context = {'form':form}
return render(request, template_name, context)
It's creating a hero. And I need to redirect to main page after submit.
How can I do that? I can't just add second return. I tried create new method to redirect, and put in instide this, but of course it didn't wokrs.
My form html:
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1>{{ title }}</h1>
{% endif %}
<form method='POST' action='.'> {% csrf_token %}
{{ form.as_p }}
<button type='submit'>Send</button>
</form>
{% endblock %}

#login_required
def hero_detail_create_view(request):
# creating by form
form = HeroCreateModelForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
slugCreate = str.lower(form.cleaned_data.get("name") + "-" + form.cleaned_data.get('nickname'))
obj.slug = slugCreate.replace(" ","")
obj.user = request.user
obj.save()
return redirect("home.html")
template_name="form.html"
context = {"form":form}
return render(request, template_name, context)

You can redirect after saving the object like this:
obj.user = request.user
obj.save()
return redirect('you_main_page_url')
And don't call your form after saving the object

With handling the get request, you can do the following way:
#login_required
def hero_detail_create_view(request):
if request.method == "POST":
form = HeroCreateModelForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
slugCreate = str.lower(form.cleaned_data.get('name') + "-" + form.cleaned_data.get('nickname'))
obj.slug = slugCreate.replace(" ","")
obj.user = request.user
obj.save()
return redirect('your_home_page')
else:
form = HeroCreateModelForm()
return render(request, 'form.html', {'form':form})

Related

Field value is not displayed for editing in the form Django?

views.py
dicfacultets = DicFacultets.objects.all()
disfacultetsedit = DicFacultets.objects.get(id=id)
form = FacultetsForm(request.POST, instance=disfacultetsedit)
if request.method == 'GET':
return render(request, 'tao/dicfacultetsedit.html', {'dicfacultets': dicfacultets,
'form': FacultetsForm(),
})
else:
try:
if form.is_valid():
disfacultetsedit = form.save(commit=False)
title = request.POST.get('title')
disfacultetsedit.title = title
disfacultetsedit.save()
return redirect('dicfacultets')
except TypeError:
return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets,
'error': 'error',
'form': form,
})
return render(request, 'tao/dicfacultets.html', {'dicfacultets': dicfacultets, })
html
{% for fac in dicfacultets %}
...
# *call modal window for editing*
<a href="facultetsedit/{{ fac.id }}" class="on-default edit-row" data-toggle="modal"
data-target="#facultetsedit{{fac.id}}"><i class="fa fa-pencil"></i></a>
# next call form method="POST" action="{% url 'facultetsedit' id=fac.id %}"> {{ form }} form in modal window
when a modal window is called, the field is empty, but editing and saving work

form not display on html, django

I tried to make a blog that allows user posts, store the posts in the db along with the posted date time and the person who posted it.
My problem is that I somehow cannot load the {{form}} to my UI, which makes my form invalid and I just don't know why it doesn't show up the input text box.
I'm not sure if I need a get_post function, but I'll just put it in views.py. (I havnt write the html of that part yet. Just need to see the form first.)
I'm pretty new to Django, can somebody pls help me with this!!! Thanks!
Below are my files.
blog.html file:
{% block posts %}
<div>
<span>New Post: </span>
<form method="post" action="{% url 'posts' %}" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{form}}
<!--not showing in UI-->
</table>
<input id="id_post_button" type="submit" value="Submit" /><br>
</form>
<div>
{% endblock %}
urls.py
urlpatterns = [
path('posts', views.post_action, name='posts'),
path('post/<int:id>', views.get_post, name='post'),
]
Models.py
class PostModel(models.Model):
user_id = models.IntegerField()
post_input_text = models.CharField(max_length=100)
post_profile = models.CharField(max_length=30)
post_date_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return 'id=' + str(self.user_id) + ", post_date_time=" + self.post_date_time + ", post_input_text=" + self.post_input_text + ", post_profile=" + self.post_profile
Views.py:
#login_required
def post_action(request):
print("----post action---")
context = {}
if request.method == "GET":
context['form'] = CreatePost()
context['posts']= PostModel.objects.get(user_id = request.user.id)
return render(request, "socialnetwork/blog.html", context)
form = CreatePost(request.POST, request.FILES)
if not form.is_valid():
print("not valid ~~~~~~~~")
context['form'] = form
context['posts'] = PostModel.objects.get(user_id = request.user.id)
return render(request, "socialnetwork/blog.html", context)
post_input_text = form.cleaned_data.get("post_input_text")
post_date_time = form.cleaned_data.get("post_date_time")
post_profile = form.cleaned_data.get("post_profile")
obj = PostModel.objects.get(
user_id = request.user.id,
)
obj.post_input_text = form.cleaned_data.get("post_input_text")
obj.post_date_time = form.cleaned_data.get("post_date_time")
obj.post_profile = form.cleaned_data.get("post_profile")
obj.save()
form = CreatePost() #refresh the form to original state
context['form'] = form
context['posts'] = obj
return render(request, "socialnetwork/blog.html", context)
def get_post(request, id):
item = get_object_or_404(PostModel, id=id)
print('Picture #{} fetched from db: {} (type={})'.format(id, item.post_input_text, item.post_profile, item.post_date_time))
if not item.post_input_text:
raise Http404
return HttpResponse(item.post_input_text)
forms.py
class CreatePost(forms.Form):
post_input_text = forms.CharField(max_length=100)
post_profile = forms.CharField(max_length=30)
post_date_time = forms.DateTimeField()
Update the template with {{ form.as_table }}, instead of {{form}}

Django edit comment

So i want to do a edit existing comment, but it gives me this error
ValueError at /episode/Dragon-Ball-Super/edit/11
The view home.views.edit_comment didn't return an HttpResponse object. It returned None instead.
edit_comment
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm(request.POST, instance=comment.user)
if request.method == 'POST' or 'NONE':
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
else:
form = CommentForm()
context = {'form': form}
return render(request, 'home/edit-comment.html', context)
urls.py
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'),
re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'),
re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'),
]
link under existing comment
{% if comment.user == request.user.userprofile %}
<h6 class="small comment-meta">
Edit
Delete</h6>
{% endif %}
models.py
class Comment(models.Model):
anime = models.ForeignKey(Anime, on_delete=models.CASCADE)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
edit-comment.html
{% extends 'base/base.html' %}
{% block head %}
<title>Edit Comment</title>
{% endblock %}
{% block content %}
<h2>Edit Comment</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
You are handling only the POST request. GET request will be placed the first time when you load the form.
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST, instance=comment.user)
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
return render(request, 'home/edit-comment.html', {'form':form})

How to Insert multiple data in django to django form?

I want to insert multiple row into my database from form2. Below are my codes
first model.py
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID=models.CharField(max_length=5,blank=True,null=True)
second model.py
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.ForeignKey(DataPribadiSiswa,blank=True, null=True)
SekolahNama=models.CharField(max_length=50,blank=True,null=True)
SekolahThMasuk=models.CharField(max_length=4,blank=True,null=True)
SekolahThKeluar=models.CharField(max_length=4,blank=True,null=True)
SekolahKet=models.TextField(blank=True,null=True)
views.py
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2, fields=('SekolahID','SiswaID_FK','SekolahNama','SekolahThMasuk','SekolahThKeluar','SekolahKet'))
if request.method == 'POST':
if form.is_valid():
siswa_instance = form.save()
form2 = FormSet2(request.POST, instance=siswa_instance)
if form2.is_valid():
form2.save()
return redirect('index')
else:
formall={}
formall['form'] = datasiswa()
formall['form2'] = riwayatsekolah()
return render(request, 'siswa/tambah_siswa.html', formall)
and this is my template
<form action="" method="post">
{% csrf_token %}
<table >
{{ form2.management_form }}
{{ form2.as_table }}
</table>
</form>
How to insert multiple row from form2 into database? when i run this code, it just insert one row.
To simplify working with related objects you can use Inline formsets
You can implement it this way:
from django.forms import inlineformset_factory
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2)
Now in view try this:
def tambah_siswa(request):
form = datasiswa(request.POST or None)
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2, fields=('SekolahID','SiswaID_FK','SekolahNama','SekolahThMasuk','SekolahThKeluar','SekolahKet'))
if request.method == 'POST':
if form.is_valid():
siswa_instance = form.save()
form2 = FormSet2(request.POST or None, instance=siswa_instance)
if form2.is_valid():
form2.save()
return redirect('index')
form2 = FormSet2(request.POST or None)
formall={}
formall['form'] = form
formall['form2'] = form2
return render(request, 'siswa/tambah_siswa.html', formall)
And in template:
{{ form2.management_form }}
{{ form2.as_table }}
or
{{ form2.management_form }}
{% for frm in form2 %}
{{ frm.as_table }}
{% endfor %}

Take In Input from User and Display the same input on the same page

Hi i am trying to create a post form in django where the user creates a post and the post is displayed back to them on the same page so far i have been unsuccessful. My articles display on the page but the form to post articles doesnt only the submit button shows.
views.py
def articles(request):
args = {}
args.update(csrf(request))
args ['posts'] = post.objects.filter(user = request.user)
args ['full_name'] = User.objects.get(username = request.user.username)
return render_to_response('articles.html', args)
def article(request, post_id=1):
return render(request, 'article.html',
{'post': post.objects.get(id=post_id) })
def create(request):
if request.POST:
form = PostForm(request.POST, request.FILES)
if form.is_valid():
a = form.save(commit=False)
a.user = User.objects.get(username = request.user.username)
a.save()
messages.add_message(request, messages.SUCCESS, "You Article was added")
return HttpResponseRedirect('/posts/all')
else:
form = PostForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('articles.html', args)
articles.html
<form action="/posts/create/" method="post" enctype="multipart/form-data">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" name="submit" value="Create Article">
</form>
{% if posts.count > 0 %}
{% for post in posts %}
<div>
<h2>{{full_name}}</h2>
<p>{{ post.body|lower|truncatewords:50 }}</p>
<p>{{post.likes}} people liked this article</a></p>
</div>
{% endfor %}
{% else %}
<p>None to show!</p>
{% endif %}
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^create/$', 'posts.views.articles'),
url(r'^get/(?P<post_id>\d+)/$', 'posts.views.article'),
url(r'^create/$', 'posts.views.create'),
url(r'^like/(?P<post_id>\d+)/$', 'posts.views.like_article'),
url(r'^article/(?P<post_id>\d+)/$', 'posts.views.add_comment'),
)
First off you aren't passing the form to the template in articles(). You need to have something along the lines of:
args['form'] = YourForm()
In your first view function. Also, in your create view you do this:
a.user = User.objects.get(username = request.user.username)
Which does an unnecessary database lookup of the user again, you can just do this to be clearer and faster:
a.user = request.user

Categories

Resources