django form processing and submit issues - django

New to Django.I retrieve data from mysql db that are displayed into a form.User needs to choose among the form choices. The view processes data that have been posted from the form by querying the DB and should send the results in csv format or in graph.I am trying right now to create a csv file with the results of the query but submit does not work.
views.py:
def monitor(request):
if request.method == 'POST' :
forms = ServicesForm(request.POST)
if forms.is_valid():
service = forms.cleaned_data['service']
scale = forms.cleaned_data['scale']
datatype = forms.cleaned_data['datatype']
starttime = forms.cleaned_data['starttime']
endtime = forms.cleaned_data['endtime']
id = Servicenames.objects.raw('SELECT id FROM servicenames WHERE servicename = ' + service )
# process and create query Select "dtime",datatype where "scale" = scale and "dtime' between starttime and endtime
# and service_id
servicestats = Servicestats.objects.raw('SELECT distinct dtime,'+ datatype + ' FROM servicestats WHERE scale = '+ scale + ' AND dtime between '+ starttime + ' and '+ endtime + 'and service_id = '+ id.id)
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment;filename="export.csv"'
writer = csv.writer(response)
for s in servicestats:
writer.writerow([s.dtime,s.datatype])
return response
else:
forms = ServicesForm
return render_to_response('monitor/monitor.html', {'forms':forms},
context_instance = RequestContext(request))
models.py :
class Servicenames(models.Model):
id = models.IntegerField(primary_key=True)
servicename = models.CharField(unique=True, max_length=255)
class Meta:
db_table = u'servicenames'
def __unicode__(self):
return self.servicename
class Servicestats(models.Model):
# service_id = models.IntegerField(primary_key=True)
service_id = models.ForeignKey(Servicenames)
dtime = models.DateTimeField(primary_key=True)
scale = models.IntegerField(primary_key=True)
cnt = models.IntegerField()
min = models.FloatField()
max = models.FloatField()
avg = models.FloatField()
threenines = models.FloatField()
class Meta:
db_table = u'servicestats'
forms.py :
class ServicesForm(forms.Form):
services=Servicenames.objects.all()
service = forms.ModelMultipleChoiceField(queryset=services,widget=forms.Select(attrs={'class':'colr',}))
scales = Servicestats.objects.values_list('scale', flat=True).distinct()
scale = forms.ModelChoiceField(queryset=scales,widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
DATATYPE_CHOICES = (
('cnt', 'cnt'),
('min', 'min'),
('max', 'max'),
('avg', 'avg'),
('threenines','threenines'),
)
datatype = forms.ChoiceField(choices = DATATYPE_CHOICES,widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
starttime = forms.DateTimeField(initial = datetime.now)
endtime = forms.DateTimeField(initial = datetime.now)
template.html :
% extends "bbase.html" %}
{% block extrascripts %}
$("#monitor").addClass("active")
{% endblock %}
{% block content %}
<div class="main">
<p>Welcome to the monitoring management system.</p>
<p>Stay tuned for more details</p>
</div>
<div>{{forms.service}}<span id="selection"><--Select services</span></div>
<div>{{forms.scale}}<span id="selection"><--Select resolution</span></div>
<div>{{forms.datatype}}<span id="selection"><--Select data type</span></div>
<div>{{forms.starttime}}<span id="selection"><--Select start time</span></div>
<div>{{forms.endtime}}<span id="selection"><--Select end time</span></div>
<input type = "submit" value = "Submit">
{% endblock %}
Thanks for the help.

It seems you are missing a form tag around your form!
try
<form action='' method='post'>{% csrf_token %}
...your form html...
...inputs...
...submit...
</form>

Related

How to display your queries using filter?

So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong.
filters.py
import django_filters
from django_filters import DateFilter
from .models import *
class UserpostFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "date_published", lookup_expr='gte')
end_date = DateFilter(field_name = "date_published", lookup_expr='lte')
class Meta:
model = Userpost
fields = '__all__'
exclude = ['image', 'user', 'date_published']
models.py
class Userpost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
Year = models.CharField(max_length = 4)
Mileage = models.CharField(max_length = 8)
Make = models.CharField(max_length = 50)
Model = models.CharField(max_length = 50)
Price = models.DecimalField(max_digits=15, decimal_places=2)
email = models.EmailField()
date_published = models.DateField(default = timezone.now)
image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images")
def __str__(self):
return self.Year + " " + self.Make + " " + self.Model
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
views.py
def posts(request):
cars = Userpost.objects.all()
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
myFilter = UserpostFilter(request.GET, queryset = cars)
cars = myFilter.qs
context = {'cars':cars, 'cars_list':cars_list, "nums":nums, "myFilter":myFilter}
return render(request, 'store/userposts.html', context)
userposts.html
<div class = "row">
<div class="col">
<div class = "card card-body">
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
{% for car in cars_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
I would really appreciate if you guys could help me
EDIT
So I changed the order of the views to first filter and then paginate but it still does the same thing. I get no error, but display all the content from the page rather than the filtered ones.
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
cars = myFilter.qs
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
The paginator should work on the cars not on the orignal queryset, since you are paginate over the filtered results
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
if not myFilter.is_valid():
raise ValidationError('filter is invalid')
cars = myFilter.qs
# This is the change
p = Paginator(cars, 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)

unable to save model form data in database. gives patientmedinfo.errors = none and patientmedinfo.is_valid() = false

'I am new to Django, trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where I am going wrong.
'.I am not getting any error,my tables are created in database, but no data is saving when i click on submit button'
models.py
from django.db import models
# Create your models here.
class PatientInfo(models.Model):
sex = (
('M', 'Male'),
('F', 'Female')
)
first_name = models.CharField(max_length=35)
middle_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length= 30)
sex = models.CharField(max_length=1,choices=sex)
date_of_birth = models.DateField()
height = models.FloatField()
weight = models.FloatField()
phone_no =models.CharField(max_length=15)
class PatientHist(PatientInfo):
Yes_No = (
(True, 'Yes'),
(False, 'No'),
)
Veg_nonveg =(
(True,'Veg'),
(False,'Non-Veg'),
)
diabetes = models.BooleanField(default=False,choices=Yes_No)
diabetes_long = models.CharField(max_length=20)
hypertension = models.BooleanField(default=False,choices=Yes_No)
hypertension_long = models.CharField(max_length=20)
obesity = models.BooleanField(default=False,choices=Yes_No)
obesity_long = models.CharField(max_length=20)
pcod = models.BooleanField(default=False,choices=Yes_No)
pcod_long= models.CharField(max_length=20)
thyroid = models.BooleanField(default=False,choices=Yes_No)
thyroid_long = models.CharField(max_length=20)
heartdiease = models.BooleanField(default=False,choices=Yes_No)
heartdiease_long = models.CharField(max_length=20)
liverdisease = models.BooleanField(default=False,choices=Yes_No)
liverdisease_long = models.CharField(max_length=20)
kidney = models.BooleanField(default=False,choices=Yes_No)
kidney_long = models.CharField(max_length=20)
familyhistory = models.BooleanField(default=False,choices=Yes_No)
currentmed = models.CharField(max_length=20)
foodhabit= models.BooleanField(default=False,choices= Veg_nonveg)
hba1c = models.FloatField(max_length=20)
fasting = models.FloatField(max_length=20)
pp = models.FloatField(max_length=20)
forms.py
from django import forms from .models import *
class Patient_form(forms.ModelForm):
class Meta:
model = PatientInfo
fields = "__all__"
class PatientHistory_form(forms.ModelForm):
class Meta:
model = PatientHist
widgets = {
'diabetes': forms.RadioSelect,
'hypertension': forms.RadioSelect,
'obesity': forms.RadioSelect,
'pcod': forms.RadioSelect,
'thyroid': forms.RadioSelect,
'heartdiease': forms.RadioSelect,
'liverdisease': forms.RadioSelect,
'kidney':forms.RadioSelect,
'familyhistory' : forms.RadioSelect,
'currentmed':forms.RadioSelect,
'foodhabit':forms.RadioSelect,
}
fields = "__all__"
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import Patient_form,PatientHistory_form
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
# Create your views here.
#def home(request):
#return render(request,'home/base.html',{})
#def patient_view(request):
#context = {}
# context['form'] = Patient()
#return render(request, 'home/Patient_info.html', context)
#def patienthistory_view(request):
# context = {}
# context['history'] = PatientHistory_form
# return render(request, 'home/Patient_info.html', context)
def patienthistory_view(request):
if request.method == 'POST':
patientmedinfo = PatientHistory_form(request.POST)
if patientmedinfo.is_valid():
myid = patientmedinfo.save()
myid.save()
return HttpResponse( print(patientmedinfo.errors))
else:
patientmedinfo = PatientHistory_form()
return render(request, 'home/Patient_info.html', {'form': patientmedinfo})
patient_Info.html
{% extends "home/base.html" %}
{% block title %}Patient Information{% endblock title %}
{% block content %}
<form enctype="multipart/form-data" action=" " method="post" >
{% csrf_token %} <table align="center" border="0">
<tr>
<td><h4 align="center">Patient Information</h4></td>
<td>{{form}}</td>
<td><input align="center" type="submit" value=" Next--> "></td>
</tr> </table> </form>
{% endblock content %}
Hi finally I found your error.
you have a field currentmed which is CharField.
But in forms.py you assigned forms.RadioSelect widget to it. So it throws an error for required field.
So just remove 'currentmed':forms.RadioSelect, from widget dict of PatientHistory_form.
That's it.

Image not uploading to the folder

I want to upload an Image, but it is not showing in the media folder.
This is the HTML template
<form class="form" action="/profile/edit/{{user.id}}" method="post" enctype="multipart/form-data" style="padding-top:20px;">
{% csrf_token %}
<input type="file" class="btn " name="pro_pic" accept=".png, .jpg, .jpeg">
<button type="submit" class="btn text-success" name="pr_pic" id="pic_submit"><i class="fas fa-check"></i> Submit</button>
</form>
Models.py
class UserDetails(models.Model):
user_id = models.IntegerField(unique=True)
bio = models.TextField(null = True)
profession = models.CharField(max_length = 100, null = True)
city = models.CharField(max_length = 100, null = True)
country = models.CharField(max_length = 100, null = True)
img = models.ImageField(upload_to='pic_user', null = True)
views.py
def edit (request, id = '') :
if request.user.is_authenticated == True :
if request.method == 'POST' :
# MyModel.objects.filter(pk=some_value).update(field1='some value')
if request.POST.get('pr_pic') == '' :
post_image = request.FILES['pro_pic']
# pic = UserDetails.objects.filter(user_id = id).update(img = post_image)
# UserDetails.objects.filter(user_id = id).update(img = post_image)
pic = UserDetails.objects.filter(user_id = id)
pic.img = post_image
pic.save()
Whenever an user is created his user_id gets updated in another table(UserDetails model), and the fields are null.
But in the HTML ive an option to upload image later (that ive shown in the HTML).
I think my views.py is wrong, please help me correct it
Try:
import uuid
from PIL import Image
format_image, img_str = request.FILES['pro_pic'].split(';base64,')
file_content = ContentFile(base64.b64decode(img_str))
unique_filename = str(uuid.uuid4())
pic.img.save(unique_filename, file_content)
file_url = settings.MEDIA_FILES + '/tmp/' + unique_filename
# convert image into JPEG format and save
img = Image.open(file_url)
img.save(file_url, format='jpeg', optimize=True, quality=85)

Changing values ​in two models using one form - did not work. Django

I am trying to make changes in two models at the same time. So, according to one topic on the forum, I created two forms in one view and added it to one html.
I think I am doing something wrong in my second form. Why my value in my model does not change to False?
It looks more or less like that.
views.pl
if request.method == 'POST' and 'btn_massage_order' in request.POST:
ordering_form = OrderingMassageForm(data=request.POST)
if ordering_form.is_valid():
ordering = ordering_form.save(commit=False)
massage_product = query_product # nazwa produkty
masseurs = query_user # massage
massage_time_interval = time # time example 60 min
price_massage = price # price
day_week = clean_my_date # day week
time_compartment = ordering_form.cleaned_data['time']
[...]
ordering.massage_product = massage_product
ordering.masseurs = masseurs
ordering.massage_time_interval = massage_time_interval
ordering.time_compartment = time_compartment
ordering.price = price_massage
ordering.day_week = day_week
[...]
ordering.save()
else:
ordering_form = OrderingMassageForm()
#next form i views
if request.method == 'POST' and 'btn_massage_order' in request.POST:
ordering_form = OrderingMassageForm(data=request.POST)
ordering_form_on_off = TimeOnTimeOff(data=request.POST)
if ordering_form_on_off.is_valid() and ordering_form.is_valid():
ordering_form_on_off = ordering_form_on_off.save(commit=False)
# the value that will be save
reservation = False
# I receive my object
time_compartment = ordering_form.cleaned_data['time']
# assigning my object
ordering_form_on_off.time_compartment = reservation
#save
ordering_form_on_off.save()
else:
ordering_form_on_off = TimeOnTimeOff()
forms.py
class OrderingMassageForm(forms.ModelForm):
class Meta:
model = OrderingMassage
fields = ('time',
'place',
'payment_method',
'name',
'surname',
[...]
class TimeOnTimeOff(forms.ModelForm):
class Meta:
model = Time
fields = ('free_or_no',
)
widgets = {
'free_or_no': forms.HiddenInput(),
}
models.py
(in which I try to change the value through a second form that does not work)
class Time(models.Model):
day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE)
compartment = models.CharField(max_length=11)
free_or_no = models.BooleanField(default=True)
time_equivalent = models.IntegerField()
template
<form action="." method="post">
{% csrf_token %}
{{ ordering_form.as_p }}
<button type="submit" name="btn_massage_order" class="btn btn-primary">Potwierdż rezerwacje</button>
</form>
Any help will be appreciated.

django - mysql selecting data from db does not work well

In main.html:
{% for item in count_list %}
{{ item }}<br>
{% endfor %}
In views.py:
def four(request):
count_list = PDivContent.objects.filter(divv = '5')
return render(request, 'main.html', {'count_list': count_list})
The problem is that the count_list list, contains data repeated for twice like this:
طلا و جواهرات
بدلیجات و نقره سرا
اجناس کادویی
اسباب بازی فروشی
صنایع دستی
فروش و تعمیر ساعت
طلا و جواهرات
بدلیجات و نقره سرا
صنایع دستی
اجناس کادویی
اسباب بازی فروشی
How can I solve it?
models.py:
class PDivContent(models.Model):
chest = models.IntegerField()
divv = models.IntegerField()
txt = models.TextField()
img = models.TextField()
symbol = models.TextField()
def __str__(self):
return self.txt
class Meta:
managed = False
db_table = 'p_div_content'
And in the db, data are not repeated for twice.
How about trying .distinct() in your query?
def four(request):
count_list = PDivContent.objects.filter(divv = '5').distinct()
return render(request, 'main.html', {'count_list': count_list})