Initializing foriegnkey in CRUD operation - django

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

Related

Create view with more models

hi everyone I have a doubt with the use of forms and models.
I have to create a code that creates records in multiple tables and I don't know how to do it.
my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user.
I'm a beginner I still have to learn the mechanism well =)
forms.py
from django import forms
from .models import Schede, DatiGruppi, Gruppi
class CreaSchedaForm(forms.ModelForm):
nome_scheda = forms.CharField(
required = True,
label ='Nome scheda',
widget = forms.TextInput(
attrs = {
'class': 'form-control',
'placeholder' : 'nome scheda',
'autocomplete' : 'off'
}
)
)
data_inizio = forms.DateField(
label='Data inizio',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data inizio'
}
)
)
data_fine = forms.DateField(
label='Data fine',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data fine'
}
)
)
class Meta:
model = Schede
fields = ['nome_scheda','data_inizio','data_fine']
class CreaDtGruppoForm(forms.ModelForm):
giorni_settimana = forms.ChoiceField(
choices = DatiGruppi.giorni_settimana_scelta
)
dati_gruppo = forms.ModelChoiceField(
queryset = Gruppi.objects.all(),
empty_label = "-",
required = True
)
class Meta:
model = DatiGruppi
fields = ['giorni_settimana', 'dati_gruppo']
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

is it ok to use formview instead of updateview, createview in Django?

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.

How to create a subform for Django ModelForm

I'm having a problem to add a ManyToMany field with ModelForm, the problem is that I don't know how to create a subform to add this data to my primary form. I want to create a subform to be saved when I click a button, and I want the data that was saved to be selected to use in the primary form.
my model
class Teste(models.Model):
name = models.CharField(max_length=255)
parent_institution_name = models.CharField(max_length=255)
laboratory_departament = models.CharField(max_length=255, null=True,
blank=True, verbose_name="Laboratório")
cep = models.CharField(max_length=255, verbose_name="Cep")
cnpj = models.CharField(max_length=255, verbose_name="CNPJ")
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
institution_name = models.CharField(max_length=255, null=False,
verbose_name="Nome da instituição")
parent_institution_name = models.CharField(max_length=255, blank=True,
null=True, verbose_name="Nome da instituição vinculada")
coordinator = models.CharField(max_length=255, verbose_name="Pessoa
Responsavel")
email = models.CharField(max_length=255, verbose_name="E-mail")
website = models.CharField(max_length=255, blank=True, null=True,
verbose_name="Website")
rad_operating_time = models.IntegerField(verbose_name="Tempo de atuação
")
research_line = models.ManyToManyField('researcher.ResearchLines')
my ModelForm
class TestForm(forms.ModelForm):
class Meta:
model = Test
exclude = ('employee_number', ' revenues', 'filter_grade', 'grade', '
knowledge_grade',
'application_grade', 'ie_grade', ' ia_grade', 'final_grade', 'inactive', 'last_coordinator_access', ' hr_count',
'hr_returned', ' match_hr_count', 'general_grade', 'lat', 'lng'
'tokens', 'iso_certification', 'other_certification', 'researchers', 'thematic_network',
)
widgets ={
'name':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Nome da UBC'
}),
'parent_institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da Instituição à qual a UBC é vinculada'
}),
'laboratory_departament': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Laboratório/Departamento'
}),
'cep': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CEP'
}),
'cnpj': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CNPJ'
}),
'institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da instituição'
}),
'coordinator': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Pessoa Responsável'
}),
'email': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'E-mail'
}),
'website': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Website'
}),
'rad_operating_time': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Tempo de atuação em projetos de P&D+I'
}),
'phone': forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Telefone'
}),
'partner_category': forms.RadioSelect(),
'main_product':forms.CheckboxSelectMultiple( attrs={
'type':'checkbox'
}),
}
How my form looks, the last input shows where the subform goes to add data
Here is an example where I use inline formsets, which is in essence combining two forms into one displayed form. The formset is the service form, and the punches form where my intention is that the punches are the "form within the form".
VIEWS.PY (the most influential part)
def reportcreateview(request):
if request.method == 'POST':
reportform = ServiceReportCreateForm(request.POST)
if reportform.is_valid():
report = reportform.save(commit=False)
report.reported_by = request.user
punchesform = PunchesFormSet(request.POST, request.FILES, instance=report)
if punchesform.is_valid():
report.save()
punchesform.save()
return redirect('service:update-report', pk=report.pk)
else:
punchesform = PunchesFormSet()
reportform = ServiceReportCreateForm()
reportform.reported_by = request.user
context = {
'report': reportform,
'punches': punchesform,
}
return render(request, 'service/report-create.html', context)
FORMS.PY
from django import forms
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from .models import ServiceReportModel, ReportPunchesModel, ServiceRequestModel
class ServiceReportCreateForm(forms.ModelForm):
class Meta:
model = ServiceReportModel
fields = [
'site',
'invoiced',
'paid',
'request_number',
'equipment',
'report_reason',
'actions_taken',
'recommendations',
]
widgets = {
'site': forms.Select(attrs={
'class': 'form-control',
'id': 'inputSite',
}),
'invoiced': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'paid': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'request_number': forms.Select(attrs={
'class': 'form-control',
'id': 'inputRequest',
}),
'equipment': forms.Select(attrs={
'class': 'form-control',
'id': 'inputEquipment',
}),
'report_reason': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Reason for Service Report'}),
'actions_taken': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'To the best of your abilities, list all actions taken during service. Please include'
'dates, times, and equipment names'}),
'recommendations': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'If any recommendations were made to the customer that'
'require follow-up itemize them here...'}),
}
def __init__(self, *args, **kwargs):
super(ServiceReportCreateForm, self).__init__(*args, **kwargs)
self.fields['request_number'].required = False
class ServiceReportUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ServiceReportUpdateForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['request_number'].required = False
self.fields['report_reason'].widget.attrs['readonly'] = True
class Meta:
model = ServiceReportModel
fields = [
'invoiced',
'paid',
'request_number',
'updated_by',
'report_reason',
'actions_taken',
'recommendations',
]
widgets = {
'invoiced': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'paid': forms.CheckboxInput(attrs={
'class': 'form-control',
}),
'request_number': forms.Select(attrs={
'class': 'form-control',
'id': 'inputRequest',
}),
'updated_by': forms.Select(attrs={
'class': 'form-control',
'id': 'inputReporter',
}),
'report_reason': forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Reason for Service Report'}),
'actions_taken': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'To the best of your abilities, list all actions taken during service. Please include' +
'dates, times, and equipment names'}),
'recommendations': forms.Textarea(attrs={
'class': 'form-control',
'placeholder': 'If any recommendations were made to the customer that'
'require follow-up itemize them here...'}),
}
PunchesFormSet = inlineformset_factory(
ServiceReportModel,
ReportPunchesModel,
fields=('date',
'time_in',
'time_out',
),
widgets={
'date': forms.DateInput(attrs={
'type': 'date'
}),
'time_in': forms.TimeInput(attrs={
'type': 'time'
}),
'time_out': forms.TimeInput(attrs={
'type': 'time'
})},
extra=1,
can_order=True
)
MODELS.PY
class ServiceReportModel(ServiceParent):
report_number = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
invoiced = models.BooleanField(default=False, null=False)
paid = models.BooleanField(default=False, null=False)
request_number = models.ForeignKey(ServiceRequestModel,
on_delete=models.PROTECT,
null=True,
blank=True,
related_name='s_report_number'
)
reported_by = models.ForeignKey(
main_models.MyUser, related_name='reporter', on_delete=models.PROTECT)
reported_date = models.DateTimeField(auto_now_add=True)
report_reason = models.CharField(max_length=255, null=True)
actions_taken = models.TextField(null=False, blank=False)
recommendations = models.TextField(null=True, blank=True)
def get_absolute_url(self):
return reverse('service-report', kwargs={'pk': self.pk})
def __str__(self):
return '%s - %s, %s' % (self.site.company,
self.reported_date.strftime('%d %B %Y'),
self.equipment.name
)
class Meta:
ordering = ['reported_date', 'updated_date']
verbose_name = 'Service Report'
verbose_name_plural = 'Service Reports'
class ReportPunchesModel(models.Model):
punch_id = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
added = models.DateTimeField(auto_now_add=True)
report = models.ForeignKey(ServiceReportModel, on_delete=models.CASCADE)
date = models.DateField(blank=True, null=True)
time_in = models.TimeField(blank=True, null=True)
time_out = models.TimeField(blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.time_in,
self.time_out
)
class Meta:
ordering = ['added', 'date', 'time_in']
verbose_name = 'Report Punches'
verbose_name_plural = verbose_name
Jaberwocky Here is my code, I have to say sorry in advance for my code I still learning
class Ubc(models.Model):
""" Table Ubc """
name = models.CharField(verbose_name="Nome da instituição", max_length=255, null=False)
laboratory_departament = models.CharField(max_length=255, null=True, blank=True, verbose_name="Laboratório")
cep = models.CharField(max_length=255, verbose_name="Cep", null=True)
cnpj = models.CharField(max_length=255, verbose_name="CNPJ", null=True)
lat = models.FloatField(blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
street = models.CharField(max_length=255, verbose_name="Endereco", null=True, blank=True)
uf = models.CharField(max_length=255, verbose_name="UF", null=True, blank=True)
city = models.CharField(max_length=255, verbose_name="City", null=True, blank=True)
parent_institution_name = models.CharField(verbose_name="Nome da instituição vinculada", max_length=255, blank=True, null=True)
coordinator = models.CharField(max_length=255, verbose_name="Pessoa Responsavel")
email = models.CharField(max_length=255, verbose_name="E-mail")
website = models.CharField(max_length=255, blank=True, null=True, verbose_name="Website")
rad_operating_time = models.IntegerField(verbose_name="Tempo de atuação em projetos de P&D+I")
phone = models.CharField(max_length=255, verbose_name="Telefone", null=True)
inactive = models.NullBooleanField(verbose_name="Inativo", default=False, null=True)
partner_category = models.ForeignKey('PartnerSubCategory', on_delete=models.CASCADE)
parent = models.ForeignKey('Company', blank=True, null=True, on_delete=models.CASCADE)
general_grade = models.ForeignKey('GeneralGrade', blank=True, null=True, on_delete=models.CASCADE)
main_product = models.ManyToManyField('MainProductUbc', verbose_name="Qual o tipo de produto e/ou servico que a UBC fornece (produto, processo, mudanca organizacional)")
tokens = models.ManyToManyField('ubc.Token', blank=True, related_name='tokens')
activity_branch = models.ForeignKey('ActivityBranch', verbose_name="Ramo de Atividade (CNAE)", null=True, on_delete=models.CASCADE)
researchers = models.ManyToManyField('researcher.Researcher', related_name='researchers', through='researcher.ResearcherUbc', blank=True)
research_line = models.ManyToManyField('researcher.ResearchLines',related_name='ubc_lines', blank=True)
class ResearchLines(models.Model):
title = models.CharField(verbose_name="Descrição da Linha de Pesquisa", max_length=255, blank=True, null=True)
ubc = models.ForeignKey('ubc.Ubc', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updtaed = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Research Line'
def __str__(self):
return self.title
views.py
def ubc_register(request):
if request.method == "POST":
form = UbcForm(request.POST or None)
if form.is_valid():
form = form.save(commit=False)
formset = LinesFormSet(request.POST, request.FILES, instance=form)
if formset.is_valid():
form.save()
formset.save()
return HttpResponseRedirect(reverse('index'))
else:
form = UbcForm(prefix="form")
formset = LinesFormSet(prefix="formset")
context = {
'form':form,
'formset':formset
}
return render(request, 'accounts/ubc_form.html', context)
forms.py
class UbcForm(forms.ModelForm):
class Meta:
research_line = forms.ModelMultipleChoiceField(queryset=ResearchLines.objects.all())
model = Ubc
exclude = ('employee_number', ' revenues', 'filter_grade', 'grade',
' knowledge_grade',
'application_grade', 'ie_grade', ' ia_grade', 'final_grade',
'inactive', 'last_coordinator_access', ' hr_count',
'hr_returned', ' match_hr_count', 'general_grade', 'lat', 'lng'
'tokens', 'iso_certification', 'other_certification', 'researchers',
'thematic_network',
)
widgets ={
'name':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Nome da UBC'
}),
'parent_institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da Instituição à qual a UBC é vinculada'
}),
'laboratory_departament': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Laboratório/Departamento'
}),
'cnpj': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CNPJ'
}),
'institution_name': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Nome da instituição'
}),
'coordinator': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Pessoa Responsável'
}),
'email': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'E-mail'
}),
'website': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Website'
}),
'rad_operating_time': forms.NumberInput(attrs={
'class':'form-control',
'placeholder':'Tempo de atuação em projetos de P&D+I'
}),
'phone': forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Telefone'
}),
'partner_category': forms.RadioSelect(),
'main_product':forms.CheckboxSelectMultiple( attrs={
'type':'checkbox'
}),
'activity_branch':forms.Select( attrs={
'class':'form-control'
}),
'research_line':forms.TextInput(attrs={
'class':'form-control'
}),
'cep': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'CEP'
}),
'street': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Endereço'
}),
'city': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'Cidade'
}),
'uf': forms.TextInput(attrs={
'class':'form-control',
'placeholder':'UF'
}),
}
class ResearchLineForm(forms.ModelForm):
class Meta:
model = ResearchLines
fields = ('title', )
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control'
})
}
class AddressForm(forms.ModelForm):
model = Address
fields = '__all__'
LinesFormSet = inlineformset_factory(
Ubc,
ResearchLines,
fields=('title', ),
extra=1,
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control'
})
}
)
inside of my form.html the formset tag and the script from django-dynamic-formset to generate the new form
{{formset.management_form}}
{% for form in formset %}
<div class="link-formset">
{{ form }}
</div>
{% endfor %}
<script>
$('.link-formset').formset({
addText: 'add link',
deleteText: 'remove'
});
</script>

Connecting a Symptom Object to and Identity Object in my Health App

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

Django forms: how to use a query to show right options

I have the following model:
class Question(models.Model):
name = RichTextField (
verbose_name = 'Question'
)
QUESTION_TYPE = (
('Multi', 'Multiple Choice (one correct answer)'),
('Check', 'Multiple Answers')
)
question_type = models.CharField(
default = "Multi",
max_length = 7,
verbose_name = "Question Type",
choices = QUESTION_TYPE)
category = models.ForeignKey(
Category,
help_text = 'Category for this Question',
null = True
)
author = models.ForeignKey(
User,
)
quiz = models.ForeignKey (
Quiz,
)
def __unicode__(self):
return u'%s' % (self.name)
I am trying to use a Django form with it so I have this form:
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['id','question_type','category','name','author','quiz',]
widgets = {'id': forms.HiddenInput(),
'author': forms.HiddenInput(),
'quiz': forms.HiddenInput(),
'name': forms.TextInput(attrs={'class': 'form-control'}),
'question_type' :forms.Select(attrs={'class': 'form-control'}),
'category' :forms.Select(attrs={'class': 'form-control'}),
}
It works fine except the Category model is associated to a specific Quiz and I only want Categories for the Quiz to which the Question is linked.
class Category(models.Model):
name = models.CharField (
max_length = 30,
verbose_name = "Question Categories",
)
quiz = models.ForeignKey (
Quiz,
verbose_name = 'Quiz',
)
def __unicode__(self):
return u'%s' % (self.name)
I am trying to work out how to limit the Category models presented to the user through the form but I cannot work out how. Help much appreciated.
You could try something like below:
q_info = Question.objects.get(id=question_id)
Q = QuestionForm(instance=q_info)
Q.fields['category'].queryset = Category.objects.filter(condition)