How do I update data on SQLite Database using HTML - python

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})

Related

Django retrieve filter value in views.py

I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function).
Example:
models.py
class User(models.Model):
name = models.CharField(max_length=30)
email = models.CharField(max_length=30)
address = models.CharField(max_length=30)
def __str__(self):
return self.name
views.py
def users(request):
users= User.objects.all()
context = {'users': users}
return render(request, 'users.html', context)
users.html
{% block content %}
<div>
<table style="width:100%" class="table table-hover table-sm table-stripped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>E mail</th>
<th>Address</th>
</tr>
</thead>
{% for i in users%}
<tr>
<td>{{i.name}}</td>
<td>{{i.email}}</td>
<td>{{i.address}}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock content%}
I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table.
Any idea on how to proceed ?
If I understood correctly, you could make a form like this
<form method="post">
<label for="users">Choose a user:</label>
<select name="users" id="users">
{% for user in users %}
<option value="{{ user.name }}">{{ user.name }}</option>
{% endfor %}
</select>
<button id="submit" type="submit">Submit</button>
</form>
and then when submitted, get the value of selected option using like this
selected_user = request.POST.get('users')
or something along these lines
In your html add select element and append users data first with <table> body empty.
<div>
<select class="form-control" id="user" name="user">
{% for i in users %}
<option value="{{i.id}}">{{i.name}}</option>
{% endfor %}
</select>
<table id="userTable" style="width:100%" class="table table-hover table-sm table-stripped">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>E mail</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
And in your script call new url using jQuery.ajax() with every .change() event of <select> element to get corresponsing user value with provided userid value and append data to the table. By this way you don't need to refresh the page and get your data with every change event.
<script>
$('#user').on('change', function() {
$.ajax({
url: "/user/" + $(this).val(),
method: 'GET',
contentType : 'application/json',
success: function (data) {
var tr = '<tr><td>'+ data.name +'</td><td>'+ data.email +'</td><td>'+ data.address +'</td></tr>';
$('#userTable tbody').append(tr);
},
error : function(x) {
console.log(x);
}
});
});
</script>
Then in your urls.py add new url as
path('user/<str:user_id>/', views.user_data, name='user-data')
Add in your views.py
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
def user_data(request, user_id):
user = get_object_or_404(GuruUsers, id=user_id)
user_data = {
'name' : user.name,
'email' : user.email,
'address' : user.address
}
return JsonResponse(user_data, status=200)

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 %}

Method not allowed Flask

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)

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.

Django comments. How back to page after validation error

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.

Categories

Resources