Django comments. How back to page after validation error - python

Below there is my code. I don't know how to redirect back after some validation errors
Urls.py:
(r'^comments/', include('django.contrib.comments.urls')),
views.py:
def show_episode(request, episode) :
episode = get_object_or_404(Episode, pk=episode)
return render_to_response('episode.html', context_instance=RequestContext(request, {
'episode' : episode,
}))
episode.html:
<div class="subsection">
{% get_comment_form for episode as form %}
<table>
<form action="{% comment_form_target %}" method="post">
{% csrf_token %}
{{ form }}
<tr>
<td colspan="2" style="text-align: center">
<input type="submit" name="submit" value="Post">
<input type="submit" name="preview" value="Preview">
</td>
</tr>
<input type="hidden" name="next" value="{% url episode episode.id %}" />
</form>
</table>
</div>
<div class="subsection">{% render_comment_list for episode %}</div>
I want to come back to this form when there will be some errors.
I try, but I have an error: 'QueryDict' object has no attribute '_meta'
Code:
def comments(request) :
if request.method == 'POST' :
form = CommentForm(request.POST)
if (form.is_valid()) :
form.save()
return HttpResponseRedirect(request.POST['next'])
return HttpResponseRedirect('/')

Do it the other way around: process the form in the same view (that is, set <form action="", this way the user won't lose his inputs (as he would with a redirect).
You can still call the other view via this view, though. ( if request.method == 'POST')
When there was no Error, send a response.redirect to a success view.

Related

How to use multiple forms in Django 2.1?

Sorry for asking similar questions, but other similar questions/answers do not help me with Django 2.
Question:
I have two actions, one is to show some data as a table.
In the second form, I edit this data and will save it as a table using Django in the database. Here is some code:
simple_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
second form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
views.py
def simple_upload(request):
if request.method == 'POST':
...
if request.is_ajax():
return render(request,
'project/simple_upload.html',
{'section': 'project', 'lines': zipped})
return render(request,
'project/list.html',
{'section': 'project', 'lines': zipped})
return render(request, 'project/simple_upload.html')
urls.py:
urlpatterns = [
...
path('', views.simple_upload, name='list'),
...
]
list.html:
...
{% include "project/simple_upload.html" %}
...
In this case, only the first form works, the second one fails.
Question 1: Can I do if request.method == 'POST' and formOne in request.POST:", I try but it does not react at all.
Question2: How can I write two methods and assign them using urls.py?
To show the data in a table, you can try Tables2 in Django, this might make things easier for you
Also in your case, you might need to make different views for different forms, Since both of them make a POST request, it will be difficult to differentiate.
You can easily do that by specifying action attribute in form tag.
Form 1
<form id="form1" method="post" action="view/for/form/1" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile" value="formOne">
<button class="btn btn-primary" type="submit">Upload</button>
</form>
Form 2
<form method="post" action = "view/for/form/2" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="mytable" value="formTwo">
<table class="table" border="1" id="tbl_posts">
<thead>
<tr>
...
</tbody>
</table>
<input type="submit" value="Submit">
</form>
Later you can redirect using json responses to avoid refreshing the page
in your urls.py add
url('view/for/form/2', save_form, name='save'),
in your views.py
def save_form(request):
#your save logic using request.post
return redirect('your/current/url')

Error : NoReverseMatch at /import/group_edit/1/ Reverse for 'confirm-delete' with arguments '('',)'

Error : Error : NoReverseMatch at /import/group_edit/1/ Reverse for 'confirm-delete' with arguments '('',)' not found. 1 pattern(s) tried:
['import\\/confirm_delete\\/(?P<group_id>[0-9]+)\\/$']
This error is from my confirm_delete.html when I want to go to group-edit.html
scenario is: going to a list template of all groups (group_list.html). For each group, you have a href to edit it.
When I click on this, Erro appears not on edit_group.html
Hoping it is clear. Please see code...:-)
changing views parameters but not working. It seems like parameter is not sent to the def confirm_delete.
group_list.html:
{% block page %}
<div class="panel-body">
<table class="table table-bordered table-hover table-striped col-md-3">
<thead class="thead-dark">
<tr class="text-center">
<th>Group Name</th>
<th>Parent Name</th>
</tr>
</thead>
<tbody>
{% for group in groups %}
<tr>
<td scope="row" class="col-md-3">{{ group.group_name|capfirst }}</td>
<td class="col-md-3">{{ group.groupParent_id|capfirst }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
group_edit.html:
{% block page %}
<form method="POST">
{% csrf_token %}
<div class="col-lg-4 col-md-4 col-sm-4 content">
{% bootstrap_form form %}
<button type="submit" class="btn btn-pink pull-right">Save</button>
<button type="reset" class="btn btn-warning pull-left">Delete</button>
</div>
Back to list
</form>
{% endblock %}
confirm_delete.html:
{% block page %}
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ obj }}"?</p>
<input type="submit" value="Confirm" class="btn btn-warning">
Cancel
</form>
{% endblock %}
views.py:
def group_list(request):
groups = Group.objects.all().order_by("-group_name")
return render(request, 'imports/group_list.html', {"groups": groups})
def group_edit(request, group_id):
form = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
form = GroupForm(request.POST, instance=Group.objects.get(group_id=group_id))
if form.is_valid():
form.save()
messages.success(request, 'Group saved') # message for inform user of success - See messages in html file
return redirect(group_list)
return render(request, 'imports/group_edit.html', {
"form": form,
})
def confirm_delete(request, group_id):
obj = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
obj.delete()
messages.success(request, 'Deleted') # message for inform user of success - See messages in html file
return render(request, 'imports/group_list.html')
context = {
"obj": obj
}
return render(request, "imports/confirm_delete.html", context)
urls.py:
path('group_edit/<int:group_id>/', views.group_edit, name='group-edit'),
path('confirm_delete/<int:group_id>/', views.confirm_delete, name='confirm-delete'),
path('group_list/', views.group_list, name='group-list'),
no error and going to edit page (delete is a button in this page)
The form doesn't have a group_id attribute. You can access it via the form's instance:
{% url 'confirm-delete' form.instance.group_id %}
Or you could include group_id in the template context,
return render(request, 'imports/group_edit.html', {
"group_id": group_id,
"form": form,
})
then you can use group_id in the URL tag:
{% url 'confirm-delete' group_id %}

Django : get data and edit in the same form, edit in one place

I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main.
I succeeded to display a form when user click edit button but failed to get data.
this is views.py
#login_required
def update_article(request, article_no):
article = get_object_or_404(Article, no=article_no)
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', no=article.no)
else:
form = ArticleForm(instance=article)
return render(request, 'blog/update_article.html', {'form': form})
urls.py
url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'),
update_article.html
{% extends 'blog/base.html' %}
{% block body %}
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<button type="submit" class="button-primary">submit</button>
</form>
list
{% endblock %}
detail.html
This is part of the page send users to update_article.html
<form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit" class="button-primary">edit</button>
</form>
form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" for="title">{{ field.label_tag }</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
In update_article views
pass article object with form
return render(request, 'blog/update_article.html', {'form': form, 'article': article})
and then form in html page
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<input class="u-full-width" type="text" name="title" value="{{article.title}}"/>
<textarea class="u-full-width" name="content" value="{{article.content}}"></textarea>
<button type="submit" class="button-primary">등록</button>
</form>
I think this would help your problem
also I guess your action link is not valid

How do I render form ChoiceField images next to choices without breaking the form?

I am trying to render the images of the choices next to their respective choice. Attempting to do so will not save the form as valid so I have become lost at what to do. I've tried both methods below and I have no idea why one works and the other doesn't, could I get some tips?
#Form:
class ServerGroupForm(forms.Form):
OPTIONS = (
("pic1", "https://i.imgur.com/tMahp6U.png"),
("pic2", "https://i.imgur.com/b76nwsj.gif"),
("pic3", "https://i.imgur.com/qzEcfyX.png Lover"),
("pic4", "https://i.imgur.com/kdc7UF7.png"),
("pic5", "https://i.imgur.com/ynWJ13W.gif"),
("pic6!", "https://i.imgur.com/goHFWsp.png"),
("pic7", "https://i.imgur.com/b76nwsj.gif"),
("pic8", "https://i.imgur.com/KPgKm79.png"),
("pic9", "https://i.imgur.com/7KtEV1i.png"),
("pic10", "https://i.imgur.com/7KtEV1i.png"),
("pic11", "https://i.imgur.com/FXfo773.png")
)
servergroups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS)
#View:
def sendmessage(msg):
#Other code sends msg to user, not includes so this isn't long
def select_server_group(request):
form = ServerGroupForm(request.POST)
if form.is_valid():
servergroups = form.cleaned_data['servergroups']
sendmessage(msg=servergroups)
return redirect('/')
return render_to_response('webts3/selcectsgroup.html', {'form':form },
context_instance=RequestContext(request))
#HTML: Works but no icons
<section class="login">
<div class="titulo">Create a channel</div>
<form method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" class="btn btn-block btn-danger" value="Submit" style="margin-top: 10px;">
</form>
</section>
#HTML: Icons but not working
<form method='post' action="." enctype="multipart/form-data">{% csrf_token %}>
<table>
{% for x,y in form.fields.servergroups.choices %}
<tr>
<td><input type="checkbox" name="{{ x }}" value="{{ x }}"><img src={{ y }}</img></td>
</tr>
{% endfor %}
</table>
<input type='submit' value='submit'>
</form>
The name attribute of the field should not be {{ x }}. It should be "servergroups".
Note you'd also need to have some logic that determines if the field is already selected, for when for example the form is being redisplayed after validation errors.

Inserting data in postgreSQL database by Django model

i found an error when i insert data to postgres database by django model,when i put csrf package in comment then my oage was found successfully else its shows an forbidden error my code and screen shot is below
here is html file:
{% extends "homepage/index.html" %}
{% block title %}
Contact
{% endblock %}
{% block content %}
This is Contact us Page.
<form action="/ins/" method="POST">
{% csrf_token %}
<table>
<tr>
<td>Created Date</td>
<td><input type="text" name="cid"></td>
</tr>
<tr>
<td>Updated Date</td>
<td><input type="text" name="uid"></td>
</tr>
<tr>
<td>Title</td>
<td><input type="text" name="tid"></td>
</tr>
<tr>
<td>Text</td>
<td><input type="text" name="txid"></td>
</tr>
<tr>
<td>Published Date</td>
<td><input type="text" name="pid"></td>
</tr>
<tr>
<input type="hidden" name="fdfdf" value="{{ csrf_token }}">
<td><input type="submit" value="Insert"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
{% endblock %}
views.py file:
def ins(request):
#c = {}
#c.update(csrf(request))
cr = request.POST.get('cid','')
up = request.POST.get('uid','')
tit = request.POST.get('tid','')
tx = request.POST.get('txid','')
pd = request.POST.get('pid','')
e = Entry(created=cr,updated=up,title=tit,text=tx,published=pd)
e.save()
return HttpResponse("Inserted SuccessFuly..")
I'm not sure why you're doing so much work by hand. Here's what you need to do:
# forms.py
from django import forms
from your_app.models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
# views.py
from django.shortcuts import render
from your_app.forms import EntryForm
def ins(request):
form = EntryForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
form.save()
return render(request, 'homepage/index.html', {'form': form})
# index.html
{# code shortened for demonstration purposes #}
<form action="." method="post" enctype="application/x-www-form-urlencoded">
{{ form.as_table }}
{% csrf_token %}
<button type="submit">Insert</button>
</form>
Pulling form values directly out of the request.POST dictionary without passing them through your form's validation is a horrible idea - please don't do that.

Categories

Resources