Related
i am working on a project to manage animal farm. The backend is with django and the frot end is with bootstrap. The project has several apps as in django documentation.
views.py
from django.shortcuts import render,redirect, get_object_or_404
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from livestockrecords.models import *
from .models import *
from .forms import *
from .models import *
from .forms import *
def save_feedin_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
livestocks = Livestock.objects.all()
context ={
'livestocks': livestocks
}
data['html_livestock_list'] =
render_to_string('includes/_list_feeding.html', context)
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def feeding_add(request, pk):
livestocks = get_object_or_404(Livestock, pk=pk)
data = dict()
if request.method == 'POST':
form = FeedingForm(request.POST , initial={'livestock': pk})
else:
form = FeedingForm(initial={'livestock': livestocks})
return save_feedin_form(request, form, 'includes/_add_feeding.html')
models.py
from django.db import models
from livestockrecords.models import Livestock
# Create your models here.
class Addmedication(models.Model):
MEDICATIONTYPE = (
('Drugs', 'Drugs'),
('Vaccination', 'Vaccination'),
)
name = models.CharField(max_length=200, null=True)
medicationType = models.CharField(max_length=200, null=True, choices= MEDICATIONTYPE)
def __str__(self):
return self.name
class Adddisease(models.Model):
name = models.CharField(max_length=200, null=True)
description = models.TextField(null=True)
def __str__(self):
return self.name
class DailyRecords(models.Model):
livestock = models.ForeignKey(Livestock, null=True, on_delete = models.SET_NULL)
dateAdded =models.DateTimeField(auto_now_add=True, null=True)
datepurchased=models.DateField(auto_now_add=False, null=True)
class Meta:
abstract = True
class Mortality(DailyRecords):
qty = models.IntegerField()
cause = models.TextField(null=True)
class Medication(DailyRecords):
medication = models.ForeignKey(Addmedication, null=True, on_delete = models.SET_NULL)
disease = models.ForeignKey(Adddisease, null=True, on_delete = models.SET_NULL)
class Feeding(DailyRecords):
feedname = models.CharField(max_length=200, null=True)
qty = models.FloatField()
forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class FeedingForm(ModelForm):
class Meta:
model = Feeding
fields = ['livestock','datepurchased', 'feedname', 'qty']
labels = {
'livestock':'',
'datepurchased': '',
'feedname': '',
'qty': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'feedname':forms.TextInput(attrs = {
'placeholder': 'feed name *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Quantity of feed in kg *',
'class': 'form-control'}),
}
class mortalityForm(ModelForm):
class Meta:
model = Mortality
fields = ['livestock','datepurchased', 'qty', 'cause']
labels = {
'livestock':'',
'datepurchased': '',
'qty': '',
'cause': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'cause':forms.TextInput(attrs = {
'placeholder': 'Cause of Mortality *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Number *',
'class': 'form-control'}),
}
class MedicationForm(ModelForm):
class Meta:
model = Medication
fields = ['livestock','datepurchased', 'medication', 'disease']
labels = {
'livestock':'',
'datepurchased': '',
'medication': '',
'disease': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'medication':forms.Select(attrs = {
'placeholder': 'Drug name *',
'class': 'form-control'}),
'disease':forms.Select(attrs = {
'placeholder': 'Disease Name *',
'class': 'form-control'}),
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
# livestockrecords
path('', views.daily_home, name = "daily-home"),
path('daily-feeding/<str:pk>/', views.feeding_add, name = "daily-feeding"),
]
In the view.py, the form is an ajax form. it display but when i hit the add button it will not capture the foriegnkey.
When i run the code i get this: error raise e.class(
ValueError: Field 'id' expected a number but got 'None'.
Please i need help
I am trying to set initial values for my django model form
but when I try in my views.py:
add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'})
It doesn't work. If I specify default values in the model they work fine.
Models.py:
class contact(models.Model):
name = models.CharField(max_length=20, blank=True)
email = models.EmailField(primary_key=True)
tel = PhoneField(null=True, blank=True)
contact_relations = [
('Supplier', 'Supplier'),
('Customer', 'Customer'),
('Other', 'Other'),
]
relation = models.CharField(max_length=50, choices=contact_relations)
Forms.py:
class newContactForm(forms.ModelForm):
class Meta:
model = contact
fields = [
'name',
'email',
'tel',
'relation',
]
widgets = {
'relation': forms.RadioSelect(),
}
Views.py:
def add_contact_view(request):
add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'})
if add_contact_form.is_valid():
add_contact_form.save()
else:
add_contact_form = newContactForm()
context = {
"add_contact_form":add_contact_form,
}
return render(request, 'contacts/new_contact.html', context)
thats because you are not setting them when the page loads, you are initializing when the form is submitted.
def add_contact_view(request):
add_contact_form = newContactForm(request.POST)
if add_contact_form.is_valid():
add_contact_form.save()
else:
add_contact_form = newContactForm(initial={'relation':'Customer'})
context = {
"add_contact_form":add_contact_form,
}
return render(request, 'contacts/new_contact.html', context)
Good morning, when I try to send the form, I get the error, and when I send it, it generates that my view does not return any httpresponse object.
this is the view
class ProductView(View):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_queryset(self):
return self.model.objects.filter(state=True)
def get_context_data(self, **kwargs):
context = {}
context['product'] = self.get_queryset()
context['list_product'] = self.form_class
return context
def get(self, request, *args, **kwargs):
return render(request, self.template_name, self.get_context_data())
def post(self, request, *args, **kwargs):
list_product = self.form_class(request.POST)
if list_product.is_valid():
list_product.save()
return redirect('products:product')
and this is the form
class ProductForm(forms.ModelForm):
name_product = forms.CharField(
max_length=25,
widget=forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
)
)
def clean_name_product(self):
name_product = self.cleaned_data.get('name_product')
if Product.objects.filter(name_product=name_product).exists():
raise forms.ValidationError('El nombre del producto ya existe')
return name_product
class Meta:
model = Product
fields = (
'name_product', 'description', 'price', 'category', 'state', 'image'
)
labels = {
'name_product': 'Nombre del Producto',
'description': 'Descripcion',
'price': 'Precio',
'category': 'Categoria',
'state': 'Estado',
'image': 'Imagen del Producto',
}
widgets = {
'name_product': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'name_product',
}
),
'description': forms.TextInput(
attrs={
'class': 'form-control',
'id': 'description',
}
),
'price': forms.NumberInput(
attrs={
'class': 'form-control',
'id': 'price',
}
),
'category': forms.SelectMultiple(
attrs={
'class': 'custom-select',
'id': 'category',
}
),
'state': forms.CheckboxInput(),
}
when I give send it generates the error.The view products.views.ProductView didn't return an HttpResponse object. It returned None instead.
At the beginning I thought that the error is due to the error lifting in the form, change the code without the validation and it generates the same error
In case the form.is_valid() fails, you do not return anything in the post method, hence the error. That being said, this is basically just a CreateView [Django-doc], so it might be better to use that to reduce the amount of "boilerplate" code:
from django.views.generic.edit import CreateView
class ProductView(CreateView):
template_name = 'products/product.html'
model = Product
form_class = ProductForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(
product=Product.objects.filter(state=True),
list_product=context['form']
)
return context
so I'm new here in django and have already get the point of some generic views but it really gives me a hard time to understand the UpdateView, CreateView and DeleteView all information that I search still not giving me a point on how to use them. So I have a form registration which have username and password but they are in different table or model to save; you may take a look on the forms.py, And trying UpdateView its giving me only an error to my project. So as I found in some forums, i can't use UpdateView to a foreign key table for its looking only a primary key So instead of using them I use FormView replacing by the 3 generic view for now. Is it ok to use the FormView as an option aside the 3 generic view?
Here is my source code.
forms.py:
from django import forms
class UserCredentialForm(forms.Form):
username = forms.CharField(label = 'Email', widget = forms.TextInput(
attrs = {
'id': 'id_login_username',
'class': 'form-control',
'autocomplete': 'off',
}
), required = False)
password = forms.CharField(label = 'Password', widget = forms.PasswordInput(
attrs = {
'id': 'id_login_password',
'class': 'form-control',
}
), required = False)
class UserInfoForm(forms.Form):
year = {}
days = {}
month = {
'': '---------',
'Jan': 'January', 'Feb': 'February', 'Mar': 'March',
'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July',
'Aug': 'August', 'Sep': 'September', 'Oct': 'October',
'Nov': 'November', 'Dec': 'December'
}
gender = {
'Male': 'Male', 'Female': 'Female',
'Not Specify': 'Not Specify'
}
year[''] = '---------'
days[''] = '---------'
from datetime import datetime
for i in range((int(datetime.now().strftime('%Y'))), (1920 - 1), -1):
year[i] = i
for i in range(1, (31 + 1)):
days[i] = i
password = forms.CharField(label = 'Password', widget = forms.PasswordInput(
attrs = {
'id': 'id_signup_password',
'class': 'form-control',
'placeholder': 'Password'
}
), required = True)
email = forms.EmailField(label = 'Email', widget = forms.EmailInput(
attrs = {
'id': 'id_signup_email',
'class': 'form-control',
'placeholder': 'Email',
'autocomplete': 'off'
}
), required = True)
firstname = forms.CharField(label = 'Firstname', widget = forms.TextInput(
attrs = {
'id': 'id_signup_firstname',
'class': 'form-control',
'placeholder': 'Firstname',
'autocomplete': 'off'
}
), required = True)
lastname = forms.CharField(label = 'Lastname', widget = forms.TextInput(
attrs = {
'id': 'id_signup_lastname',
'class': 'form-control',
'placeholder': 'Lastname',
'autocomplete': 'off'
}
), required = True)
gender = forms.ChoiceField(label = 'Gender', widget = forms.Select(
attrs = {
'id': 'id_signup_gender',
'class': 'form-control',
}
), choices = list(gender.items()), required = False)
birthdate_year = forms.ChoiceField(label = 'Year', widget = forms.Select(
attrs = {
'id': 'id_signup_birthyear',
'class': 'form-control',
}
), choices = list(year.items()), required = True)
birthdate_day = forms.ChoiceField(label = 'Day', widget = forms.Select(
attrs = {
'id': 'id_signup_day',
'class': 'form-control',
}
), choices = list(days.items()), required = True)
birthdate_month = forms.ChoiceField(label = 'Month', widget = forms.Select(
attrs = {
'id': 'id_signup_month',
'class': 'form-control',
}
), choices = list(month.items()), required = True)
This view file is from the login app:
views.py
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from .models import (
UserModel,
)
from django.db.models import (
Q,
)
from django.contrib.auth.hashers import (
make_password, check_password
)
from django.views.generic.base import (
TemplateView,
)
from django.views.generic import (
FormView,
)
from .formprocess import (
UserCredentialForm, UserInfoForm,
)
from .forms import (
UserCredentialForm, UserInfoForm,
)
# Create your views here.
class LoginView(TemplateView):
template_name = 'login/views/index.html'
def get(self, request, *args, **kwargs):
loginform = UserCredentialForm(self.request.GET or None)
registerform = UserInfoForm(self.request.GET or None)
context = self.get_context_data(**kwargs)
context['loginform'] = loginform
context['registerform'] = registerform
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
mForm = UserCredentialForm(self.request.POST)
if mForm.is_valid():
mUsername = mForm.cleaned_data['username']
mPassword = mForm.cleaned_data['password']
mUserModel = UserModel.objects.filter(
Q(email = mUsername) | Q(username = mUsername)
)
# Check if there is fetched data from UserModel.
if not mUserModel:
return redirect(reverse_lazy('login'))
else:
# Get password from query result.
# Check if password valid or not.
db_password = ''
for obj in mUserModel:
db_password = obj.password
if check_password(mPassword, db_password):
return redirect(reverse_lazy('site'))
else:
return redirect(reverse_lazy('login'))
else:
return self.render_to_response(
self.get_context_data(mForm)
)
# Handle forms
def signup(request):
return RegisterFormProcess(request).do_task()
def logout(request):
return redirect('login')
and for the signup process method here it is:
from django.shortcuts import render, redirect, HttpResponseRedirect
from django.urls import reverse_lazy
from django.contrib import messages
from django.db.models import (
Q,
)
from django.contrib.auth.hashers import (
make_password, check_password,
)
from .models import (
UserModel, UserInfoModel,
)
from .forms import (
UserCredentialForm, UserInfoForm,
)
class RegisterFormProcess:
def __init__(self, request):
self.request = request
def do_task(self):
if self.request.method == 'POST':
mRegisterForm = UserInfoForm(self.request.POST)
if mRegisterForm.is_valid():
# Collect data
mFirstname = mRegisterForm.cleaned_data['firstname']
mLastname = mRegisterForm.cleaned_data['lastname']
mEmail = mRegisterForm.cleaned_data['email']
mPassword = mRegisterForm.cleaned_data['password']
mGender = mRegisterForm.cleaned_data['gender']
mBYear = mRegisterForm.cleaned_data['birthdate_year']
mBDay = mRegisterForm.cleaned_data['birthdate_day']
mBMonth = mRegisterForm.cleaned_data['birthdate_month']
# Check if email is already exists.
isEmaiExists = UserModel.objects.filter(email = mEmail)
if not isEmaiExists:
# Validate password length.
if len(mPassword) < 4:
messages.error(self.request, 'Password is too short to use.')
return HttpResponseRedirect(reverse_lazy('login'))
else:
# Save user information and move to user profile settings.
from datetime import datetime
mUserModel = UserModel()
mUserModel.email = mEmail
mUserModel.password = make_password(mPassword)
mUserModel.status = 'active'
mUserModel.date_join = datetime.now().strftime('%Y-%m-%d')
mUserModel.authority = 1
mUserModel.save()
mUserInfoModel = UserInfoModel()
mUserInfoModel.users = mUserModel
mUserInfoModel.firstname = mFirstname
mUserInfoModel.lastname = mLastname
mUserInfoModel.birthdate = f'{mBMonth} {mBDay}, {mBYear}'
mUserInfoModel.gender = mGender
mUserInfoModel.save()
return HttpResponseRedirect(reverse_lazy('site'))
else:
messages.error(self.request, 'Email is already in use.')
return HttpResponseRedirect(reverse_lazy('login'))
else:
mRegisterForm = UserInfoForm()
return HttpResponseRedirect(reverse_lazy('login'))
and here is the view site app file:
views.py
from django.shortcuts import render, HttpResponse
from mediasocialplatform.wraps import login_required
from django.views.generic.base import (
TemplateView,
)
from django.views.generic import (
FormView,
)
from login.models import (
UserInfoModel,
)
from login.forms import (
UserInfoForm,
)
# Create your views here.
class SiteIndexView(TemplateView):
template_name = 'site/views/index.html'
# THIS IS WHERE I WANT TO USE THE UPDATEVIEW
class SettingsProfileView(FormView):
template_name = 'site/views/settingsprofile.html'
form_class = UserInfoForm
def get_context_data(self, **kwargs):
mForm = self.form_class(self.request.GET or None)
kwargs['form'] = mForm
kwargs['object'] = UserInfoModel.objects.filter(
users_id = self.kwargs['pk']
)
return super().get_context_data(**kwargs)
def get(self, request, *args, **kwargs):
return self.render_to_response(self.get_context_data())
UpdateView, CreateView and DeleteView are there to make your life easy. To basically make easy forms and only include or exclude fields that you do or don't want to see, and the rest is taken care of by Django. That's the benefit.
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')