in my project, user after register can complete his information in another form. after completed this form and submitted it every time he visits this page, he sees the completed form. but i have a problem in this form, calender of user's birthday field works well at the first time when field is empty, but after the form is completed and submitting when the user wants to change it the calendar looks like this:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
ED_CHOICES = [
('hs', 'High school'),
('bc', 'Bachelor'),
('ms', 'Master'),
('do', 'Doctor'),
]
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=13)
birthday = models.DateField()
education = models.CharField(max_length=20, choices=ED_CHOICES)
gender = models.CharField(max_length=15)
forms.py:
class ProfileForm(forms.ModelForm):
ED_CHOICES = [
('hs', 'High school'),
('bc', 'Bachelor'),
('ms', 'Master'),
('do', 'Doctor'),
]
phone = forms.CharField(
widget=forms.TextInput(attrs={'class': 'input--style-4'}),
label=''
)
birthday = forms.DateField(
widget=forms.DateInput(attrs={'class': 'input--style-4 js-datepicker'}),
label=''
)
education = forms.CharField(
widget=forms.Select(choices=ED_CHOICES, attrs={'class': 'select-dropdown'}),
label=''
)
gender = forms.CharField(
widget=forms.TextInput(attrs={'class': 'radio-container m-r-45'}),
label=''
)
class Meta:
model = models.UserProfile
fields = ['phone', 'birthday', 'education', 'gender']
views.py:
from django.shortcuts import render, redirect
from . import forms, models
from django.contrib.auth import get_user_model
my_user = get_user_model()
my_profile = models.UserProfile
first = True
def profile(request, slug):
global first
user = my_user.objects.get(username=slug)
if first:
pro_form = forms.ProfileForm(request.POST or None)
else:
pro = my_profile.objects.get(user=user)
pro_form = forms.ProfileForm(request.POST or None, instance=pro)
form = forms.UserProfile(request.POST or None, instance=user)
context = {'FORM': form, 'PRO': pro_form, 'USER': user}
if form.is_valid() and pro_form.is_valid():
form.save()
pro = pro_form.save(commit=False)
pro.user = user
pro.save()
first = False
if 'gender' in request.POST:
pro_form.gender = request.POST.get('gender')
return redirect('HOME')
return render(request, 'accounts/index.html', context)
template:
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Birthday</label>
<div class="input-group-icon">
{{ PRO.birthday }}
<i class="zmdi zmdi-calendar-note input-icon js-btn-calendar"></i>
</div>
</div>
</div>
js:
(function ($) {
'use strict';
/*==================================================================
[ Daterangepicker ]*/
try {
$('.js-datepicker').daterangepicker({
"singleDatePicker": true,
"showDropdowns": true,
"autoUpdateInput": false,
locale: {
format: 'DD/MM/YYYY'
},
});
var myCalendar = $('.js-datepicker');
var isClick = 0;
$(window).on('click',function(){
isClick = 0;
});
$(myCalendar).on('apply.daterangepicker',function(ev, picker){
isClick = 0;
$(this).val(picker.startDate.format('DD/MM/YYYY'));
});
$('.js-btn-calendar').on('click',function(e){
e.stopPropagation();
if(isClick === 1) isClick = 0;
else if(isClick === 0) isClick = 1;
if (isClick === 1) {
myCalendar.focus();
}
});
$(myCalendar).on('click',function(e){
e.stopPropagation();
isClick = 1;
});
$('.daterangepicker').on('click',function(e){
e.stopPropagation();
});
} catch(er) {console.log(er);}
/*[ Select 2 Config ]
===========================================================*/
try {
var selectSimple = $('.js-select-simple');
selectSimple.each(function () {
var that = $(this);
var selectBox = that.find('select');
var selectDropdown = that.find('.select-dropdown');
selectBox.select2({
dropdownParent: selectDropdown
});
});
} catch (err) {
console.log(err);
}
})(jQuery);
Related
I can't seem to upload an image to my project.
I always get this error when I try to submit the form from the frontend :
["The submitted data was not a file. Check the encoding type on the form."]
I've found some answers regarding the base64 encoding of the image but I can't seem to get it to work.
Any help would be much appreciated!!
thanks
here is the source code:
Models:
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField(default=0)
dob = models.CharField(max_length=10)
image = models.ImageField(upload_to='images/', null=True)
def __str__(self):
return self.name
class Details(models.Model):
party = models.ForeignKey(Person,on_delete=models.CASCADE,
related_name='party_details',null=True,blank=True)
adress = models.CharField(max_length=50)
date = models.CharField(max_length=20)
arrival= models.CharField(max_length=20)
def __str__(self):
return self.adress
Serializers:
class DetailsSerializer(serializers.ModelSerializer):
class Meta:
model = Details
# fields='__all__'
fields = ('id','party','adress','date','arrival')
class PersonSerializer(serializers.ModelSerializer):
party_details =DetailsSerializer(many=True)
class Meta:
model = Person
# fields='__all__'
fields = ('id','name','age','dob','image','party_details')
def create(self, validated_data):
named_details = validated_data.pop('party_details')
details = Person.objects.create(**validated_data)
for named_detail in named_details:
Details.objects.create(party=details, ** named_detail)
return details
def update(self,instance, validated_data):
named_details = validated_data.pop('party_details')
details = (instance.party_details).all()
details = list(details)
instance.name = validated_data.get('name', instance.name)
instance.age = validated_data.get('age', instance.age)
instance.dob = validated_data.get('dob', instance.dob)
instance.image = validated_data.get('image', instance.image)
instance.save()
for named_detail in named_details:
detail = details.pop(0)
detail.adress = named_detail.get('adress',detail.adress)
detail.date = named_detail.get('date',detail.date)
detail.arrival = named_detail.get('arrival', detail.arrival)
detail.save()
return instance
views:
class ListAllPerson (generics.ListCreateAPIView):
queryset=Person.objects.all()
serializer_class = PersonSerializer
class ListPerson (generics.RetrieveUpdateDestroyAPIView):
serializer_class = PersonSerializer
queryset= Person.objects.all()
class ListAllDetails(generics.ListCreateAPIView):
queryset=Details.objects.all()
serializer_class = DetailsSerializer
class ListDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = DetailsSerializer
queryset=Details.objects.all()
class CreateDetail(generics.ListCreateAPIView):
queryset=Details.objects.all()
serializer_class = DetailsSerializer
HTML FORM and Axios:
const profileImage = async ()=>{
let formField = new FormData()
formField.append('image',addImages)
await axios({
method: 'patch',
url: url,
data: formField
}).then((response) => {
history.push('/')
}).catch((error) => {
console.log(error);
})
}
<div className="add-image-input">
<form action="" className="add-image-form">
<input className="image-input" value={addImages}
onChange={(e)=>{setAddImages(e.target.value)}} type="file"/>
<button className="" type="button" onClick={profileImage} >add</button>
</form>
</div>
Hopefully you are using React js, this should help. At the point of
saving and submitting your form data, your function should look like this:
const onSubmit = (data) => {
console.log(data)
let form_data = new FormData();
form_data.append('upload_image_photo', data.cover_image, data.cover_image.name);
form_data.append('title', data.title);
form_data.append('category', data.category);
form_data.append('price_per_night', data.price_per_night);
form_data.append('room_slug', data.room_slug);
form_data.append('capacity', data.capacity);
form_data.append('room_size', data.room_size);
let url = '/url to the end point you are saving with the expected image field / ';
const config = {
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
},
};
axios.post(url, form_data, config)
.then(res => {
console.log(res.request.status);
console.log(res.data);
})
.catch(err => console.log(err))
};
I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I have something in the webflow_id field I got this error when I tried to select the edit option: Employee matching query does not exist.
When I tried to edit record without this webflow_id it doesn't change, but creates a new record.
my views.py:
def staff_edit(request, webflow_id):
#employees = Employee.objects.all()
#print(employees)
if request.method == 'GET':
if webflow_id == 0:
form = EmployeeEditForm()
else:
try:
#employees = Employee.objects.get(pk=webflow_id)
employees = Employee.objects.get(pk=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")
form = EmployeeEditForm(instance=employees)
return render(request, 'staffedit.html', {'form': form})
else:
if webflow_id == 0:
form = EmployeeEditForm(request.POST)
else:
employees = Employee.objects.get(pk=webflow_id)
form = EmployeeEditForm(request.POST, instance=employees)
if form.is_valid():
form.save()
return redirect('feedback:staff')
context = {'form': form} #when the form is invalid
return render(request, 'staffedit.html', context)
models.py:
class Employee(models.Model):
webflow_id = models.CharField(max_length=100, primary_key=True, default=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, default=True)
email = models.EmailField(max_length=100)
user_type = models.CharField(max_length=100)
status = models.CharField(max_length=100, default=True)
roles = models.ManyToManyField('Role', through='EmployeeRole')
def __str__(self):
return self.webflow_id + " " + self.email + " " + self.first_name + " " + self.last_name
this is my general html staff.html:
$(document).ready(function() {
var data;
fetch("http://192.168.2.85:8000/fetchapi_employees/")
.then(response => response.json())
.then(json => data = json)
.then(() => {console.log(data); //this gave me Array of objects from my database
$('#datatable').DataTable( {
data: data.employees,
deferRender: true,
scrollY: false,
scrollX: false,
scrollCollapse: true,
scroller: true,
"columns": [
{ data: "webflow_id" },
{ data: "first_name" },
{ data: "last_name" },
{ data: "email" },
{ render: function ( data, type, row ) {
return '<i class="far fa-edit fa-lg" aria-hidden="true"></i>';
} },
{ render: function ( data, type, row ) {
return '<i class="fa fa-plus-circle" aria-hidden="true"></i>';
} },
],
"order": [[1, 'asc']]
} )
})
} );
staffedit.html:
<div class="container">
<div class="col-md-10.offset-md-1 mt-5">
<div class="jumbotron">
<h1 class="display-4">Edit employee</h1>
<hr class="my-4">
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn btn-success"><i class="far fa-save"></i> Save</button>
</form>
</div>
</div>
</div>
forms.py:
class EmployeeEditForm(ModelForm):
class Meta:
model = Employee
fields = [
'webflow_id',
'first_name',
'last_name',
'roles',
]
and this is my urls.py:
path('staff/edit/<int:webflow_id>', views.staff_edit, name="staffedit"),
Can anyone see what I'm missing?
Best regards!
webflow_id is a CharField
webflow_id = models.CharField(max_length=100, default=True)
Url parameter must be contain string:
path('staff/edit/<str:webflow_id>', views.staff_edit, name="staffedit"),
Also your webflow_id is not primary key. If you want to use it as primary key, you have to add primary_key=True.
webflow_id = models.CharField(max_length=100, primary_key=True)
I would also use Try Except for get method:
from django.http import Http404
try:
Employee.objects.get(webflow_id=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")
I have got two dropdown options, country and number service location. Options for both can be selected from their respective dropdown.
My objective is to display correct telephone number based on the selected country and number service location. You will also see my attempt to implement this functionality using Ajax in views below.
Model created here -
class DID_Number_Assignment_Model(models.Model): #DID Number Assignment
country = models.ForeignKey(Country_Model, on_delete=models.CASCADE)
number_service_location = models.ForeignKey(Number_Service_Location_Model, on_delete=models.CASCADE)
did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE)
Views.py
def did_assignment_form(request, id=0, *args, **kwargs):
if request.method =="POST":
if id==0:
form = DID_Number_Assignment_Model_Form(request.POST)
if request.is_ajax():
country = request.GET.get('country')
number_service_location = request.GET.get('number_service_location')
filters = {'country': country, 'number_service_location': number_service_location}
dids_searched = DID_Definition_Model.objects.filter(**filters)
data = []
for dids in dids_searched:
data.append({
'country': dids.country,
'number_service_location': dids.number_service_location})
return HttpResponse({
'success': True,
'data': data,
}, content_type=content_type)
else:
return HttpResponse({
'success': False,
'message': 'Only AJAX method is allowed.'
}, content_type=content_type)
template html file here -
<form action="" method="post" autocomplete="off">
{%csrf_token%}
<!--{{form|crispy}} !-->
<div class="row", style = "position:relative; left:57px; top:100px">
<div class="col-md-7"> {{ form.country | as_crispy_field }} </div>
<div class="col-md-7"> {{ form.number_service_location | as_crispy_field }} </div>
<script type="text/javascript">
$(document).on('change', '.filter-dropdown', function() {
var country = $('#countryDropdown').children('option:selected').val();
var number_service_location = $('#number_service_locationDropdown').children('option:selected').val();
if (country !== "" && number_service_location !== "" ) {
var data = {
'country': country,
'number_service_location': number_service_location
}
$.ajax({
url: '/did_definition_list/',
type: 'GET',
data: data,
dataType: 'json',
success: function(response) {
if (response.success) {
// render did_number from `response.data`
} else {
// show message from `response.message`
}
},
error: function(errorResponse) {
// show error message
}
});
} else {
return;
}
});
</script>
Model form below -
class DID_Number_Assignment_Model_Form(forms.ModelForm):
class Meta:
model = DID_Number_Assignment_Model
fields = ('country','number_service_location','did_selector', 'usage_assignment', 'employee_fullname', 'employee_email', 'subscriber_department' )
def __init__(self, *args, **kwargs):
super(DID_Number_Assignment_Model_Form,self).__init__(*args, **kwargs)
defs_with_no_assignments = DID_Definition_Model.objects.filter(did_number_assignment_model__isnull=True)
available_did= defs_with_no_assignments.values_list('did_number', flat=True)
# TO SET drop down default text for a field , optional -
self.fields['did_selector'].empty_label = "Select"
self.fields['did_selector'].queryset = DID_Definition_Model.objects.filter(did_number__in=available_did)
'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.
I am creating a Health App that will take the Identity, Symptom, Disease and Treatment of the patient.
I have created models: Identity, Symptom, Disease, Treatment.
I am using form.ModelForm so that I can save the data to the db i.e. sqlite3.
I have created class based views that will handle forms, take field values, sanitize the data, and render the required form and values.
Problem: Each time I attempt to save values for the Symptom form it
seems to save it, and redirect to a new form but I am not seeing it in
the Admin Backend.
Code:
Model document
from django.db import models
from django.utils import timezone
import datetime
class Identity(models.Model):
NIS =models.CharField(max_length = 200, primary_key = True)
timestamp = models.DateTimeField(auto_now = True)
first_name = models.CharField(max_length = 80, null = True)
last_name = models.CharField(max_length = 80, null = True )
contact = models.CharField(max_length = 15, null = True)
location = models.CharField(max_length = 100, blank = True)
birthday= models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return '%s, %s' % (self.first_name ,self.last_name)
class Symptom(models.Model):
condition_name = models.CharField(max_length = 80, default = '')
description = models.TextField(max_length = 1000, default = '')
def __str__(self):
return self.condition_name
class Disease(models.Model):
disease_name = models.CharField(max_length = 80, default = '')
description = models.TextField(max_length = 1000, default = '')
def __str__(self):
return self.disease_name
class Treatment(models.Model):
term = models.CharField(max_length = 80, default = '')
treatment = models.TextField()
patient = models.ManyToManyField(Identity, through = 'Consultation')
date_done = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return self.Term
class Consultation(models.Model):
patient_identity = models.ForeignKey(Identity)
patient_condition = models.ForeignKey(Symptom)
patient_disease = models.ForeignKey(Disease)
patient_treatment = models.ForeignKey(Treatment)
date_seen = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return '%s' %(self.patient_identity)
Views document
from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView, DetailView, FormView, TemplateView
from patient.models import Identity, Symptom, Treatment, Disease, Consultation
from patient.forms import IdentityScript, SymptomScript
class Identity_view(CreateView):
model = Identity
template_name = 'patient/script.html'
def get(self, request):
form = IdentityScript()
script = Identity.objects.all()
var = {'form':form, 'script':script}
return render(request, self.template_name, var)
def post(self, request):
form = IdentityScript(request.POST)
being = None
if form.is_valid():
NIS = form.save(commit = False)
NIS.user = request.user
NIS.save()
being = form.cleaned_data['first_name']
form = IdentityScript()
return redirect('script:script')
var = {'form':form, 'being':being}
return render(request, self.template_name, var)
class Identity_list_view(ListView):
model = Identity
template_name = 'patient/Identity_list.html'
def get(self, request):
form = IdentityScript()
script = Identity.objects.all().order_by('-Timestamp')
var = {'form':form, 'script':script}
return render(request, self.template_name, var)
class Medical_document(CreateView):
model = Symptom
template_name = 'patient/medical_document.html'
def get(self, request, pk):
form = SymptomScript()
expression = Symptom.objects.all()
var = {'form':form, 'expression':expression, 'pk':pk}
return render(request, self.template_name, var)
def post(self, request, pk):
form = SymptomScript()
state = None
if form.is_valid():
manuscript = form.save(commit = False)
manuscript.user = request.user
state = form.cleaned_data['description']
manuscript.save()
patient = Identity.objects.get(pk=pk)
form = SymptomScript()
redirect('script:script')
else:
print(form)
var = {'form': form, 'state':state, 'pk':pk}
return render(request, self.template_name, var)
Forms document
from django import forms
from patient.models import Identity, Symptom, Disease
class IdentityScript(forms.ModelForm):
NIS = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter NIS',
'class' : 'form-control'
}
)
)
first_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter First Name',
'class' : 'form-control'
}
)
)
last_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Last Name',
'class' : 'form-control'
}
)
)
contact = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder':'Enter Contact',
'class':'form-control'
}
)
)
born = forms.DateField(
widget = forms.TextInput(
attrs = {
'placeholder' : 'Enter Birth',
'class':'form-control'
}
)
)
location = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder':'Enter location',
'class':'form-control'
}
)
)
class Meta:
model = Identity
fields = ('NIS', 'first_name', 'last_name', 'birthday', 'location', 'contact', )
class DiseaseScript(forms.ModelForm):
disease_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Disease Name',
'class' : 'form-control'
}
)
)
description = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter description',
'class' : 'form-control'
}
)
)
class Meta:
model = Disease
fields = ('disease_name', 'description')
# Create SymptomScript form
class SymptomScript(forms.ModelForm):
condition_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Condition Name',
'class' : 'form-control'
}
)
)
description = forms.CharField(
widget = forms.Textarea(
attrs = {
'placeholder': 'Enter Description',
'class' : 'form-control'
}
)
)
class Meta:
model = Symptom
fields = ('condition_name', 'description')