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.
Related
I am trying to save my form in my data base. But my code adds a new row instead of save changes to the existing one. where is my mistake?
view.py
def settings(request):
error = ''
if request.method == 'POST':
new_form = TrafficSourcesForm(request.POST)
if new_form.is_valid():
new_form.save()
else:
error = 'Something went wrong!'
new_form = TrafficSourcesForm()
forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
template
<div class="table table-striped table-hover">
<div class="table-row">
<th style="width: 42%">Name</th>
<th style="width: 43%">Token</th>
<th style="width: 15%">Action</th>
</div>
{% for form in forms %}
<div class="table-row">
<form method="POST">
{% csrf_token %}
<div class="table-cell">{{ form.name }}</div>
<div class="table-cell">{{ form.token }}</div>
<div class="table-cell"><button class="btn btn-lg btn-success w-100"">Save</button></div>
</form>
</div>
</div>
If its not clear: I am showing all the table from my databese on the page. I want to edit them and save again to the database.
Because you are using POST data and form to create a new instance on every request:
...
if request.method == 'POST':
new_form = TrafficSourcesForm(request.POST)
if new_form.is_valid():
new_form.save()
...
To edit an object, you first need to retrieve the instance, which is normally done using its unique identifier (pk). Although normally you would send this ID using the url dispatcher captured value. I am using a hidden field in this case:
mainpage/dashboard.html
<body>
{% if forms %}
<table class="table table-striped table-hover">
<thead>
<tr>
<th style="width: 42%">Name</th>
<th style="width: 43%">Token</th>
<th style="width: 15%">Action</th>
</tr>
</thead>
<tbody>
{% for form in forms %}
<form method="POST">
{% csrf_token %}
<tr>
<td>{{ form.name }}</td>
<td>{{ form.token }}</td>
<input type="hidden" value="{{ form.instance.pk }}" name="id">
<td class="table-cell"><button class="btn btn-lg btn-success w-100">Save</button></td>
</tr>
</form>
{% endfor %}
</tbody>
</table>
{% endif %}
<form method="POST">
{% csrf_token %}
{{new_form.as_p}}
<div class="table-cell"><button class="btn btn-lg btn-success w-100">Create</button></div>
</form>
</body>
views.py
def settings(request):
error = ''
if request.method == 'POST':
new_form = TrafficSourceForm(request.POST)
pk = request.POST.get('id')
if new_form.is_valid():
if pk:
TrafficSource.objects.filter(id=pk).update(**new_form.cleaned_data)
else:
TrafficSource.objects.create(**new_form.cleaned_data)
else:
error = 'Something went wrong!'
new_form = TrafficSourceForm()
forms = [TrafficSourceForm(instance=x) for x in TrafficSource.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
Id recommend getting the specific object you want to modify. Ex. traffic_source = TrafficSources.objects.get(id=<id_here>)
I have a few forms in my forms variable, which I took from my DB.
views.py:
def settings(request):
new_form = TrafficSourcesForm()
forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()]
return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error})
MY HTML:
<h3>{{ error }}</h3>
{% for form in forms %}
<form method="POST" id="{{form.name.name}}">{% csrf_token %}</form>
{% endfor %}
<form method="POST" id="new-form"> {% csrf_token %}</form>
{% for form in forms %}
<tr>
<td>{{ form.name }}</td>
<td>{{ form.token }}</td>
<td><button class="btn btn-lg btn-success w-100">Save</button></td>
</tr>
{% endfor %}
<tr>
<td><input class="form-control" placeholder="Name" form="new-form"></td>
<td><input class="form-control" placeholder="API-token" form="new-form"></td>
<td><button class="btn btn-lg btn-success w-100" form="new-form">Add</button></td>
</tr>
I am making a kind of editable grid and using a table for my layout ( so I cannot put a form direct to a row). So I am making the forms separately with the new HTML 5 form tag.
But I cannot take out the name(HTML attr on my inputs) which == the name field in the DB. So I could make different forms for every single row in my database. Can you help me?
I was thinking about setting the id of the form from my forms object but it makes the same forms for every row.
I'm trying to allow users to update the information that they have provided by clicking the edit icon on my html webpage, but I am unsure on how to start.
Update:
urls.py
urlpatterns = [
...
path('editclaims/<int:id>', views.editclaims, name='editclaims'),
]
views.py
def editclaims(request,id):
context = initialize_context(request)
user = context['user']
getclaims = SaveClaimForm.objects.get(id=id)
return render(request, 'editclaims.html',{'SaveClaimForm':getclaims, 'user':user})
editclaims.html
{% extends "Login/layout.html" %}
{% block title %}
<title>Update Claim {{claims.id}} </title>
{% endblock %}
{% block content %}
<form method=POST action="editclaims/{{getclaims.id}}">
<table border="1">
<tr>
<td>Name: </td>
<td><input id="name" type="text" name="name_field" value = "{{user.name}}" readonly ></td>
<td>Email: </td>
<td><input id="email" type="text" name="email_field" value="{{ user.email }}" readonly></td>
<td>Claim Amount: </td>
<td><input id="claim" type="number" name="claim_field" required min="0.01" step=".01" value="{{claims.claim}}"></td>
</tr>
</table>
</form>
{% endblock %}
After doing this the site returns a TemplateDoesNotExist Error.
Ensure that your views.py returns the exact path of where the HTML page is, for my case it was Login/editclaims.html
def editclaims(request,id):
context = initialize_context(request)
user = context['user']
claims = SaveClaimForm.objects.get(id=id)
return render(request, "Login/editclaims.html",{'SaveClaimForm':claims, 'user':user})
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 %}
Whenever I press my submit button for my file to go to that file page I get a method not allowed, I thought it was an issue with not has POST and GET but I do. Essentially this line isn't working in my code
if request.method == 'POST':
return redirect(url_for('files()'))
views.py
class HView(BaseView):
route_base = "/home"
#expose('/test')
#appbuilder.app.route('/test', methods=['GET', 'POST'])
def test(self):
if request.method == 'POST':
return redirect(url_for('files()'))
else:
return render_template(blah)
index.html
{% extends "appbuilder/base.html" %}
{% block title %}Title{% endblock %}
{% block content %}
<div class="container">
<div class="col-12-xs">
<h3>Bucket List</h3>
<table class="table table-striped">
<tr>
<th>Bucket Name</th>
<th>Created</th>
<th></th>
</tr>
{% for bucket in buckets %}
<tr>
<td>{{ bucket['Name'] }}</td>
<td>{{ bucket['CreationDate'] | datetimeformat }}</td>
<td>
<form class="select-bucket" action="{{ url_for('HView.test')}}" method="post">
<input type="hidden" name="bucket" value="{{ bucket['Name'] }}"/>
<button type="submit" class="btn btn-primary btn-sm">
<i class="fas fa-archive"></i>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
{% endblock %}
Try specifying the method in #expose
Ex:
class HView(BaseView):
route_base = "/home"
#expose('/test', methods=['GET', 'POST'])
def test(self):
if request.method == 'POST':
return redirect(url_for('files()'))
else:
return render_template(blah)