I have postgres function
DECLARE office_lastnumber TEXT;
BEGIN
UPDATE curriculum.clearance_item SET resolve=TRUE,resolve_date=now() where cl_itemid=f_cl_itemid;
INSERT INTO curriculum.transaction_log (cl_itemid,trans_desc,trans_recorded)
VALUES (f_cl_itemid,'Resolved Clearance Item',now());
RETURN f_cl_itemid;
END;
I have this list of items, cut some rows so it's easier to read
<table style="width:100%">
<tr>
<th>cl_itemid</th>
<th colspan="2">Actions:</th>
</tr>
{%for data in data%}
<tr>
<td>{{data.cl_itemid}}</td>
<td>Update</td>
</tr>
{%endfor%}
</table>
And views.py
def update(request):
if request.method == "POST":
cursor = connection.cursor()
resolve_item = # what to put here
cursor.execute("select resolve_clearance_item('"+resolve_item+"')")
return render(request, 'clearance/index.html')
else:
return render(request, 'clearance/index.html')
cl_itemid
OSA2022-2023 | update
DORM2022-2023| update
How can def update knows if I click update (ex.OSA2022-2023) then it puts in resolve_item and run the function
# ---------------- VIEW.PY ----------------
# Update Data In Student Table
def UpdateData(request,id):
student_data = Student.objects.all() # Show data of Student Table
get_student = Student.objects.get(id=id)
if request.method == 'POST':
form = Student(request.POST,request.FILES,instance=set_student)
if form.is_valid():
form.save()
messages.success(request,'Student Successfully Updated')
return redirect('/home/')
else:
form = Student(instance=set_student)
context= {'form':form,'student_data':student_data}
return render(request,'home.html',context)
Related
How to realize checking 'name' for current user in forms.py in ValidationError('Same name already added, change name').
views.py
#login_required
def main_page(request):
form = URL_listForm(request.POST)
if request.method == "POST":
if form.is_valid():
name = form.cleaned_data['name']
if URL_list.objects.filter(user=request.user, name=name).exists():
return HttpResponse('Same name already added, change name')
new_post = form.save(commit=False)
new_post.user = request.user
new_post.save()
return HttpResponse("Data added")
return render(request, 'link/main.html', {'form': form})
If you want validate in database
#-------ADDED CODE
data_tmp = """SELECT count(*) from jobtest WHERE link = %s""", (line)
data_tmp = cur.fetchall()
#-------END ADDED CODE
if (data_tmp == 0 ) :
Not exist
add form with name
<input type="text" id="projectName" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
when press post button and action to api you can get value in input field using request.form['Name']
if you want send data from server code to html
return render_template('index.html', data=userinfo)
and render as
{% userinfo %}
I am confused when I try to insert record from a "GET" request
I will try to explain what I want to do.
I am creating an application to take inventory of assets.
I have 3 tables in my database.
I have a main table called
fixed asset("ActFijo") where all the assets of my company are registered.
Another call Inventory ("Inventario"), which stores the name of each inventory
and another call Inventory_detail ("Inventario_detalle"), where the details or assets in which they are being counted are stored to verify that the equipament or furniture is not being stolen in that location.
From the main table ("ActFijo") I have to search for the furniture or asset and store it in the detail table ("Inventario_detalle")
I'm confused I don't know how to work on a GET request and then do a POST all in one request
Do I have to write my code in parts in a GET request and then POST?
Or can I do everything in the GET request?
This is the code I have so far
I don't know if it's ok, please I need guidance
For example my code does not pass the validation of the form.
if form.is_valid():
I am trying to print, But I don't see any validation error, it doesn't print anything
print(form.errors)
Views.py
from django.shortcuts import redirect, render
from .form import InventarioDetalle_Form, InventarioForm
from .models import ActFijo, Inventario, Inventario_detalle
# Create your views here.
def inventario_home_view(request):
if request.method == "GET":
inv = Inventario.objects.all()
context = {"inventarios": inv}
return render(request, "inventario/index.html", context)
def inventario_crear_view(request):
if request.method == "POST":
form = InventarioForm(request.POST)
if form.is_valid():
form.save()
return redirect("inventario-home")
else:
form = InventarioForm()
inv = Inventario.objects.all()
context = {"formulario": form, "inventarios": inv}
return render(request, 'inventario/crear.html', context)
def inventario_detalle_view(request, inventario):
if request.method == "GET":
# Obtener el valor del input "Buscar"
codigo_activo = request.GET.get("buscar")
print("[CODIGO ACTIVO]:", codigo_activo)
# Buscar el activo en la bd por el campo codigo
try:
activo = ActFijo.objects.get(codigo=codigo_activo)
# print(activo)
except ActFijo.DoesNotExist:
activo = None
if activo:
form = InventarioDetalle_Form(instance=activo)
# print(form)
print(form.errors)
if form.is_valid():
instance = form.save(commit=False)
instance.inventario_id = inventario
instance.save()
else:
print(
"This request does not pass the validation")
else:
print(
"The element does not exist")
context = {"item": Inventario_detalle.objects.all()}
return render(request, "inventario/detalle.html", context)
form.py:
from django import forms
from .models import Inventario, Inventario_detalle
class InventarioForm(forms.ModelForm):
class Meta:
model = Inventario
fields = '__all__'
class InventarioDetalle_Form(forms.ModelForm):
class Meta:
model = Inventario_detalle
fields = '__all__'
url.py
from django.urls import path
from django import views
from . import views
urlpatterns = [
path("", views.inventario_home_view, name="inventario-home"),
path("create/", views.inventario_crear_view,
name="inventario-create"),
path('detail/<int:inventario>',
views.inventario_detalle_view, name="inventario-detail"),
]
detail.html
{% extends "core/base.html" %} {% block content%}
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="titulo mt-5">
<h1>Inventario Detalle</h1>
</div>
<form method="get">
<input type="text" class="form-control" placeholder="Buscar Activo" name="buscar" />
</form>
<div style="overflow-x: auto">
<table>
<thead>
<tr>
<th>Codigo</th>
<th>Descripcion</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
{% for i in item %}
<tr>
<td>{{i.codigo}}</td>
<td>{{i.descripcion}}</td>
<td><button type="button" class="btn btn-danger">Eliminar</button></td>
</tr>
</tbody>
{% endfor %}
</tbody>
</table>
</div>
<div>{{request.GET}}</div>
</div>
</div>
</div>
{% endblock %}
The problem is here
def inventario_detalle_view(request, inventario):
if request.method == "GET":
codigo_activo = request.GET.get("buscar")
print("[CODIGO ACTIVO]:", codigo_activo)
try:
activo = ActFijo.objects.get(codigo=codigo_activo)
print(activo)
except ActFijo.DoesNotExist:
activo = None
if activo:
form = InventarioDetalle_Form(instance=activo)
print(form.errors)
if form.is_valid():
instance = form.save(commit=False)
instance.inventario_id = inventario
instance.save()
else:
print(
"This request does not pass the validation")
else:
print(
"The element does not exist")
context = {"item": Inventario_detalle.objects.all()}
return render(request, "inventario/detalle.html", context)
I believe you don't see any validation errors on the form because for the GET request, you are not passing in anything. The only thing you're passing into the form is the model instance and you're running form.is_valid on it which does not make sense. You dont need to use the form at all. Use this instead.
def inventario_detalle_view(request, inventario):
if request.method == "GET":
codigo_activo = request.GET.get("buscar")
print("[CODIGO ACTIVO]:", codigo_activo)
try:
activo = ActFijo.objects.get(codigo=codigo_activo) # get activo object
activo.inventario_id = inventario # update object
activo.save() # save changes
print(activo)
except ActFijo.DoesNotExist:
# you can do anthing here
# maybe redirect with a message..
pass
context = {"item": Inventario_detalle.objects.all()}
return render(request, "inventario/detalle.html", context)
This is my model:
class dateEvent(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
event = models.ForeignKey('Event', on_delete=models.CASCADE)
start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False)
My views.py:
def event_edit_view(request, id):
event = get_object_or_404(Event, id=id)
#MyOtherForm instantiated by event
DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'),
widgets={
'venue': s2forms.Select2Widget(),
'start_date_time': CalendarWidget(),
form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id))
if request.method == "POST":
if MyOtherForm.is_valid() and form_date_event.is_valid():
MyOtherForm.save()
form_date_event.save()
return redirect('my-events')
else:
raise forms.ValidationError(form_date_event.errors) #?
context = {
[other forms...]
'form_date_event': form_date_event,
}
return render(request, "events/template.html", context)
And my template.html:
<table id="dateEvent">
<thead>
<th>Venue</th>
<th>Date and time</th>
<th>Link</th>
<th>Link description</th>
</thead>
<tbody id='date_body'>
{{ form_date_event.management_form }}
{% for formDate in form_date_event.forms %}
<tr class="form-row-dateEvent" style='display:table-row;'>
<td>{{formDate.venue}}<br>
Add a new venue</td>
<td>{{ formDate.start_date_time}}</td>
<td>{{formDate.link}} {{formDate.this_composition}}</td>
<td>{{formDate.id}}{{formDate.link_description}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Now, how can I enforce the user to fill in both venue and the date? As it is now if a user fills in the venue field and leaves the corresponding date field empty, Django redirects the user to an ugly yellow page
ValidationError at /private/event-edit/1150/
['This field is required.']
Request Method: POST
Request URL: .../event-edit/1150/
Django Version: 3.1
Exception Type: ValidationError
Exception Value:
['This field is required.']
Exception Location: /home/.../.../.../views.py, line 682, in event_edit_view
if DEBUG=TRUE is set, otherwise an even uglier Error 500. Is there a way that the user would get a nice 'please fill in this field' message in the same row next to the populated venue field, when they hit the 'submit' button?
PS
Do I need to declare a custom clear() method, according to which if a record has a venue needs also to have a date populated?
I think an issue is inside your event_edit_view function inside the views.py file, you should pass the formset in the context inside the POST method condition
do this in your else part instead of raising the validation error. It should work now.
def event_edit_view(request, id):
.....
if request.method == "POST":
.....
if MyOtherForm.is_valid() and form_date_event.is_valid():
MyOtherForm.save()
form_date_event.save()
return redirect('my-events')
else:
context = {
[other forms...]
'form_date_event': form_date_event,
}
return render(request, "events/template.html", context)
I'm using Django 1.4 with Python 2.7 on Ubuntu 12.04.
I'm going to continue to update this question as I make progress.
UPDATE 2:
I'm trying to generate 2 choice fields in a form using information from an existing model.
class AssignProject(forms.Form):
def __init__(self, devs, *args, **kwargs):
"""
.. method:: __init__()
Class constructor
:param devs: Tuple with which developer
"""
super(AssignProject, self).__init__(*args, **kwargs)
self.dev = forms.ChoiceField(widget = forms.Select(), choices = devs, required = True)
self.designer = forms.ChoiceField(widget = forms.Select(), choices = devs, required = True)
At this point I can't seem to access dev and designer ChoiceField in my template yet.
Here is the view:
#login_required
def view_all_projects(request):
"""
.. function:: view_projects()
Show the projects
:param request: Django Request object
"""
data = { 'user' : request.user }
if (request.user.is_authenticated() and request.user.is_superuser):
all_projects = Projects.objects.filter(active = True)
dev_info = User.objects.filter(is_staff = True, is_superuser = False)
dev_dict = {}
for dev in dev_info:
dev_dict[dev.id] = '{0} {1}'.format(dev.first_name, dev.last_name)
devs = tuple(dev_dict.items())
form = AssignProject(devs)
data.update({ 'form' : form })
data.update({ 'projects' : all_projects })
data.update(csrf(request))
return render_to_response("view_all_projects.html", data)
return render_to_response("index.html", data)
I have verified that the developers/designers are properly getting set in the devs tuple.
...and the template from view_all_projects.html:
<form action="/assignProject/" method="post">{% csrf_token %}
<table>
<td>
<input type="hidden" name="project_id" value={{ project.id }}>
<tr>
<td align="right"><label class="formlabel">Assign Developer:<br /></label></td><td>{{ form.dev }}</td>
</tr>
<tr>
<td align="right"><label class="formlabel">Assign Designer:<br /></label></td><td>{{ form.designer }}</td>
</tr>
<tr>
<td align="right"><label class="formlabel"> </label></td><td><input type="submit" value="Submit ►"></td>
</tr>
</td>
</table>
</form>
I don't see any errors, but I do see a strange object reference in place of the ChoiceField in the template.
<django.forms.fields.ChoiceField object at 0x7ffdbc054190>
<django.forms.fields.ChoiceField object at 0x7ffdbc0542d0>
I see these instead. I know I'm close...just can't quite get what I'm going wrong.
Thoughts?
The issue was entirely in the form __init__.
I should have assigned the fields like follows:
class AssignProject(forms.Form):
def __init__(self, devs, *args, **kwargs):
"""
.. method:: __init__()
Class constructor
:param devs: Tuple with developers
"""
super(AssignProject, self).__init__(*args, **kwargs)
self.fields['dev'] = forms.ChoiceField(widget = forms.Select(), choices = devs, required = True)
self.fields['designer'] = forms.ChoiceField(widget = forms.Select(), choices = devs, required = True)
Note the self.fields['dev'] not self.dev. Fixed everything.
Django: 1.4.1
Model:
class Hoja(models.Model):
nombre = models.CharField(max_length=200) # requerido
class Linea(models.Model):
hoja = models.ForeignKey(Hoja) # requerido
nombre = models.CharField(max_length=200) # requerido
padre = models.ForeignKey('self', null=True, blank=True, related_name='hijo')
View:
lineas = Linea.objects.filter(hoja=alt).order_by('id')
LineaHojaSet = modelformset_factory(Linea, can_delete=True, extra=1 if request.POST.has_key('siguiente') else 0)
formset = LineaHojaSet(request.POST or None, queryset=lineas)
if request.method=='POST':
# process formset
return render_to_response('template.html', {'formset':formset}, context_instance=RequestContext(request))
Template:
<table>
<thead>
<tr><th>Nombre</th><th>Borrar</th></tr>
</thead>
<tbody>
{% for fs in formset %}
<tr>
<td>{{ fs.nombre }}</td>
<td>{{ fs.id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" name="siguiente" value="Añadir siguiente" />
When I submit the "siguiente" button, I can see than the formset is getting the correct extra field of 1, but in the webpage, the only rows showing are the database ones. It's this a bug, or I'm doing something wrong?
Formset factory finds number of forms either by max_num, extra parameters or form-TOTAL_FORMS parameter in request.POST (or data) from management form.
In your case, request.POST['form-TOTAL_FORMS'] has number which does not include extra form . So it does not add extra form when you create formset.
One solution would be to increment this number by one when your condition is met. e.g.
data = None
if request.POST:
data = request.POST.copy() #required as request.POST is immutable
if request.POST.has_key('siguiente'):
data['form-TOTAL_FORMS'] = int(data['form-TOTAL_FORMS']) + 1
#now use data instead of request.POST
formset = LineaHojaSet(data, queryset=lineas)
....
However, there are some drawbacks of manipulating formset this way. When you validate formset, the extra form will show errors if there are any required fields.
Better solution would be to create formset again before passing it template with one extra form and queryset. Most likely, when formset is valid, you would save any new objects, those will get added by queryset. So your page will show newly added objects and one extra form.
lineas = Linea.objects.filter(hoja=alt).order_by('id')
LineaHojaSet = modelformset_factory(Linea, can_delete=True,)
formset = LineaHojaSet(request.POST or None, queryset=lineas)
if request.method=='POST':
# process formset
if formset.is_valid:
#saved and done with formset.
if request.POST.has_key('siguiente'):
LineaHojaSet = modelformset_factory(Linea, can_delete=True, extra=1)
formset = LineaHojaSet(queryset=lineas)
...
return render_to_response('template.html', {'formset':formset}, context_instance=RequestContext(request))