I have a custom form as follows
class ticketform( BootstrapForm ):
class Meta:
layout = (
Fieldset( "", "project", "manager", "cc_to", "urgency", "deadline", "subject", "steps", "result", "desc", "file" ),
)
project = forms.CharField( max_length = 100, label = "Project", help_text = "Project this request is related to" )
manager = UserModelChoiceField( queryset = User.objects.filter( is_active = True ).order_by( 'first_name' ), label = "Manager",
help_text = "Immediate superior or project manager", required = True )
cc_to = UserMultipleSelectField( queryset = User.objects.filter( is_active = True ).order_by( 'first_name' ), label = "CC To",
widget = widgets.FilteredSelectMultiple( "Users", is_stacked = True ), required = False )
OPTIONS = (
( 'Critical', 'Critical' ),
( 'Major', 'Major' ),
( 'Minor', 'Minor' ),
)
urgency = forms.ChoiceField( choices = OPTIONS, label = "Urgency", help_text = "Urgency of the request" )
deadline = forms.CharField( widget = widgets.AdminSplitDateTime(), label = "Deadline",
help_text = "When should this ticket be completed", required = True )
subject = forms.CharField( max_length = 100, label = "Subject", help_text = "Ticket Subject" )
steps = forms.CharField( widget = forms.Textarea, label = "Steps", help_text = "Reproducible error/feature Steps" )
result = forms.CharField( widget = forms.Textarea, label = "Result", help_text = "Expected Result" )
desc = forms.CharField( widget = forms.Textarea, label = "Description", help_text = "Detailed Description" )
file = forms.FileField( label = "File", help_text = "Attach File Max size 10MB", required = False )
i have the following code in my view to populate the form for view
def view_ticket( request, ticket_id ):
ticket = Ticket.objects.filter( pk=ticket_id )[0]
dict = {'project' : ticket.project,
'manager' : ticket.manager.pk,
'urgencry': ticket.urgency,
'deadline': ticket.deadline,
'subject' : ticket.subject,
'steps' : ticket.steps,
'result' : ticket.result,
'desc' : ticket.detailed_disc,
'file' : ticket.attachments,
'cc_to' : ticket.cc_to.all()
}
form = ticketform( dict )
return render_to_response( 'form/request.html', {'form':form,
},
mimetype="text/html", context_instance=RequestContext( request ) )
now what is happening is that the deadline field is not being populated (all other fields gets populated just fine). all though i pass it the values in dictionary. Is there a way to pre-populated the AdminSplitDateTime() field on the form ?
setting the initial value for the form worked as pointed out by jpic
Related
Import and export work as expected but when i try to reimport the same file (update), i get this error:enter image description here
resources.py
class ArticleResource(resources.ModelResource):
number = fields.Field(column_name="GMC", attribute="number", widget=CharWidget())
name = fields.Field(column_name="Artikelbezeichnung", attribute="name")
intern_name = fields.Field(column_name="Artikelbezeichnung_intern", attribute="intern_name")
brand = fields.Field(column_name="Marke", attribute="brand")
base_label_number = fields.Field(column_name="Grundetikettennummer", attribute="base_label_number")
barcode = fields.Field(column_name="Barcode_Produkt", attribute="barcode")
layers = fields.Field(column_name="Lagen", attribute="layers")
formatclass = fields.Field(
column_name="FCL", attribute="formatclass", widget=ForeignKeyWidget(FormatClass, "number")
)
volume = fields.Field(column_name="Volumen_in_L", attribute="volume", widget=IntegerWidget())
height = fields.Field(column_name="Höhe", attribute="height", widget=IntegerWidget())
width = fields.Field(column_name="Breite", attribute="width", widget=IntegerWidget())
comment = fields.Field(column_name="Bemerkung", attribute="comment")
group_code = fields.Field(
column_name="Grundetikett_A-Code", attribute="group", widget=ArticleGroupWidget(ArticleGroup, "code")
)
group_name = fields.Field(
column_name="Bezeichnung_Grundetikett",
attribute="group",
widget=ForeignKeyWidget(ArticleGroup, "name"),
readonly=True,
)
class Meta:
model = Article
use_bulk = True
use_transactions = True
skip_unchanged = True
report_skipped = True
import_id_fields = ["number"]
exclude = ["id", "group", "packsize"]
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')
I basically have to display a list of service providers and in each, I need to display the categories of service they offer.
So as an example:
Possible Service Type Categories:
[id: 1, name:'Programming']
[id: 2, name:'Design']
Possible Service Types:
[id: 1, name: 'PHP Service', service_type_category_id: 1]
[id: 2, name: 'JAVA Service', service_type_category_id: 1]
[id: 3, name: 'Web Design Service', service_type_category_id: 2]
Example of Display Results:
Company Blue offers 'Programming'
Company Test offers 'Programming' and 'Design'
Company Orange offers 'Design' ....
I'm trying to write the least number of queries:
I have these models:
class ServiceTypeCategory( BaseModel ):
# Model Attributes
name = models.CharField( _( "name" ), max_length = 40 )
class ServiceType( BaseModel ):
# Model Attributes
service_type_category = models.ForeignKey( 'ServiceTypeCategory', verbose_name = _( 'category' ) )
name = models.CharField( _( "name" ), max_length = 60 )
description = models.TextField( _( "description" ) )
class Provider( BaseModel ):
# Model Attributes
display_name = models.CharField( _( "name" ), max_length = 80 )
# Many to many relations
countries = models.ManyToManyField( 'core.Country' ) # countries this provider support
service_types = models.ManyToManyField( 'ServiceType', through = 'Provider_ServiceTypes', related_name = 'service_types' )
class Provider_ServiceTypes( BaseModel ):
# Model Attributes
service_type = models.ForeignKey( 'ServiceType', verbose_name = _( 'service type' ) )
provider = models.ForeignKey( 'Provider', verbose_name = _( 'provider' ) )
is_top = models.BooleanField( _( "is top service" ), default = False )
Then, to run the query, I have the following:
providers = Provider.objects.select_related(
'user',
).prefetch_related(
Prefetch(
'service_types__service_type_category',
queryset = ServiceTypeCategory.objects
.only( 'name' )
)
).filter(
countries = country_id,
).only(
'id', 'display_name', 'user'
).order_by(
'-user__last_login'
)
This works out well, but it runs the 3 following queries:
SELECT app_provider.id, app_provider.user_id, app_provider.display_name, core_user.id, core_user.password, core_user.last_login, core_user.is_superuser, core_user.created_date, core_user.modified_date, core_user.email, core_user.name, core_user.is_active, core_user.is_admin
FROM app_provider
INNER JOIN app_provider_countries ON ( app_provider.id = app_provider_countries.provider_id )
INNER JOIN core_user ON ( app_provider.user_id = core_user.id )
LEFT OUTER JOIN core_userpersonal ON ( core_user.id = core_userpersonal.user_id )
LEFT OUTER JOIN core_userstats ON ( core_user.id = core_userstats.user_id )
WHERE app_provider_countries.country_id = 204
ORDER BY core_userstats.total_reviews DESC, core_userstats.total_contracts DESC, core_userstats.total_answers DESC, core_user.last_login DESC LIMIT 5
SELECT (app_provider_servicetypes.provider_id) AS _prefetch_related_val_provider_id, app_servicetype.id, app_servicetype.created_date, app_servicetype.modified_date, app_servicetype.service_type_category_id, app_servicetype.name, app_servicetype.description
FROM app_servicetype
INNER JOIN app_provider_servicetypes ON ( app_servicetype.id = app_provider_servicetypes.service_type_id )
WHERE app_provider_servicetypes.provider_id IN (2)
SELECT app_servicetypecategory.id, app_servicetypecategory.name
FROM app_servicetypecategory
WHERE app_servicetypecategory.id IN (1, 2)
Question is: How can I make to run just 2 queries in total? (The last 2 queries should be joined with INNER JOIN and a group by per service_type_category_name)
Thanks in advance!
Try this:
providers = Provider.objects.select_related(
'user',
).prefetch_related(
Prefetch(
'service_types',
queryset = ServiceType.objects\
.select_related('service_type_category')\
.only( 'service_type_category', 'name' )
)
).filter(
countries = country_id,
).only(
'id', 'display_name', 'user'
).order_by(
'-user__last_login'
)
I am trying to make a search option for my data table in my site,
in models.py I have:
class Mymodel(models.Model):
id = models.AutoField(primary_key=True)
title = models.TextField()
body = models.TextField()
creator = models.CharField(max_length=255, blank=True, db_index = True)
creation_time = models.DateTimeField( db_index = True )
event_id = models.CharField(unique=True, max_length=255)
capture_rule = models.ForeignKey(CaptureRule, db_index = True)
status = models.ForeignKey(EventStatus, null = True, blank=True, db_index = True)
comment = models.TextField( null = True, blank = True )
source_url = models.CharField(max_length=4096, null = True, blank = True )
links = models.ManyToManyField( Link, related_name = 'events' )
and in my views.py:
class edittest(XEditableDatatableView):
model = Event
template_name = 'webapp/index.html'
datatable_options = {
'columns':[( 'Time', 'creation_time', 'get_event_age' ),
( 'Status', 'status', make_xeditable( type='select' ), 'status__name' ),
( 'Creator', 'creator' ),
( 'Source', 'source' ),
( 'Title', 'title' ),
( 'Body', 'body', 'get_body_with_markup' ),
'comment',
'id',
'source_url',
( 'Tag', 'capture_rule__tag__name' ),
( 'Matcher', 'capture_rule__matcher'),
'linked_urls',
'capture_rule'
],
'search_fields': [ 'status__name' ],
'hidden_columns' : ['body', 'comment', 'id', 'source_url', 'linked_urls', 'capture_rule' ],
'ordering':['-creation_time'],
}
and it works ok but when I change the search_fields parameter to
'search_fields': [ 'title' ] or 'search_fields': [ 'comment' ]
it search in the whole columns like if I wrote : 'search_fields': []
That's probably because the search field should not already appear in the column list.
A list of filter-like ORM fields that are always appended to the list
of search fields when a search is performed on the table.
search_fields should only contain ORM paths to fields that aren't
already in the column definitions, since those are already searched by
default.
https://pypi.python.org/pypi/django-datatable-view/0.5.5
I have these models:
OrderLine
StockItem
WaybillItem
Waybill
The Waybill consists of a number of WaybillItem connected to one Order Number.
The WaybillItem consists of a OrderLine & a StockItem
The relation between StockItem & Orderline is a loose many to many dependent on a query from the data of the OrderLine:
StockItem.objects.filter( wh_code = OrderLine.origin_wh_code ).filter( si_code = OrderLine.si_code ).filter( commodity_code = OrderLine.commodity_code )
In the form I would like the user to have a single select to choose the possible options where for each matching StockItem/OrderLine there is one item.
Example:
In OrderLines there is the following OrderLines:
Line_ID, OrderNumber, commodity_code, si_code, origin_wh_code
1001,1, Wheat, 2222,Rome
1002,1, Oat, 2222, Rome
1003,2, Oat, 2222, Rome
In StockItem you have:
Stock_ID, commodity_code, si_code, wh_code, reference_code
10, Wheat, 2222, Rome, 222201
12, Oat, 2222, Rome, 222202
13, Wheat, 2222, Rome, 222203
14, Wheat, 2222, Paris, 222203
This should result in a dropdown for waybillline for waybill with number 1 with:
Line_ID, Stock_ID, (commodity_code, si_code, reference_code)
1001, 10, (Wheat, 2222, 222201
1001, 13, (Wheat, 2222, 222203)
1002, 12, (Oat,2222, 222202)
When selected the Waybill line should have both the Line_ID & Stock_ID saved, but the user is only using a single Dropdown.
I am using inlineformset_factory to create the list of wabill lines.
Can anyone help?
Edited Adding Models View and Template
Models:
The Waybill
class Waybill( models.Model ):
ltiNumber = models.CharField( max_length = 20 )
waybillNumber = models.CharField( max_length = 20 )
dateOfLoading = models.DateField( null = True, blank = True )
recipientLocation = models.CharField( max_length = 100, blank = True )
destinationWarehouse = models.ForeignKey( Places, blank = True )
The Order
class OrderLine( models.Model ):
lti_pk = models.CharField( max_length = 50, primary_key = True, db_column = 'LTI_PK' )
lti_id = models.CharField( max_length = 40, db_column = 'LTI_ID' )
code = models.CharField( max_length = 40, db_column = 'CODE' )
origin_wh_code = models.CharField( max_length = 13, blank = True, db_column = 'ORIGIN_WH_CODE' )
destination_location_code = models.CharField( max_length = 10, db_column = 'DESTINATION_LOCATION_CODE' )
si_code = models.CharField( max_length = 8, db_column = 'SI_CODE' )
commodity_code = models.CharField( max_length = 18, db_column = 'COMMODITY_CODE' )
number_of_units = models.DecimalField( max_digits = 7, decimal_places = 0, db_column = 'NUMBER_OF_UNITS' )
This is the stock model
class StockItem( models.Model ):
wh_pk = models.CharField( max_length = 90, blank = True, primary_key = True )
wh_code = models.CharField( max_length = 13 )
wh_name = models.CharField( max_length = 50, blank = True )
si_code = models.CharField( max_length = 8 )
origin_id = models.CharField( max_length = 23 )
commodity_code = models.CharField( max_length = 18 )
number_of_units = models.IntegerField()
This is the WaybillItem
class WaybillItem( models.Model ):
wbNumber = models.ForeignKey( Waybill )
siNo = models.ForeignKey( OrderLine )
coi_code = models.ForeignKey( StockItem )
numberUnitsLoaded = models.DecimalField( default = 0, blank = False, null = False, max_digits = 10, decimal_places = 3 )
View:
def waybillCreate( request, lti_code ):
#Retrive the LTIs for this Waybill
current_lti = OrderLine.objects.filter( code = lti_code )
for lti in current_lti:
c_sis.append( lti.si_code )
current_stock = StockItem.in_stock_objects.filter( si_code__in = c_sis ).filter( wh_code = current_lti[0].origin_wh_code )
class LoadingDetailDispatchForm( ModelForm ):
#Here are the order lines
siNo = ModelChoiceField( queryset = current_lti, label = 'Commodity' )
#This is from the Stock
coi_code = ModelChoiceField( queryset = current_stock )
overload = forms.BooleanField( required = False )
class Meta:
model = LoadingDetail
fields = ( 'siNo', 'numberUnitsLoaded', 'wbNumber', 'overloadedUnits', 'overOffloadUnits' , 'coi_code' )
LDFormSet = inlineformset_factory( Waybill, LoadingDetail, form = LoadingDetailDispatchForm, fk_name = "wbNumber", formset = BaseLoadingDetailFormFormSet, extra = 5, max_num = 5 )
current_wh = ''
if request.method == 'POST':
form = WaybillForm( request.POST )
form.fields["destinationWarehouse"].queryset = Places.objects.filter( geo_name = current_lti[0].destination_loc_name )
formset = LDFormSet( request.POST )
if form.is_valid() and formset.is_valid():
wb_new = form.save()
instances = formset.save( commit = False )
wb_new.waybillNumber = new_waybill_no( wb_new )
for subform in instances:
subform.wbNumber = wb_new
subform.save()
wb_new.save()
return HttpResponseRedirect( '../viewwb/' + str( wb_new.id ) )
else:
loggit( formset.errors )
loggit( form.errors )
loggit( formset.non_form_errors )
else:
qs = Places.objects.filter( geo_name = current_lti[0].destination_loc_name ).filter( organization_id = current_lti[0].consegnee_code )
if len( qs ) == 0:
qs = Places.objects.filter( geo_name = current_lti[0].destination_loc_name )
else:
current_wh = qs[0]
form = WaybillForm(
initial = {
'dispatcherName': request.user.profile.compasUser.person_pk,
'dispatcherTitle': request.user.profile.compasUser.title,
'ltiNumber': current_lti[0].code,
'dateOfLoading': datetime.date.today(),
'dateOfDispatch': datetime.date.today(),
'recipientLocation': current_lti[0].destination_loc_name,
'recipientConsingee':current_lti[0].consegnee_name,
'transportContractor': current_lti[0].transport_name,
'invalidated':'False',
'destinationWarehouse':current_wh,
'waybillNumber':'N/A'
}
)
form.fields["destinationWarehouse"].queryset = qs
formset = LDFormSet()
return render_to_response( 'waybill/createWaybill.html', {'form': form, 'lti_list':current_lti, 'formset':formset}, context_instance = RequestContext( request ) )
Template (part):
<table cellpadding="1px" cellspacing="1px" id="example" style="border:1px;">
<thead>
<tr><th></th><th>Commodity</th><th>{%if lti_list.0.is_bulk%}Metric Tons{%else%}Number of Units{%endif%}</th><th>Overload</th></tr>
</thead>
{% for sform in formset.forms %}
<tr>
<td>{{ sform.id }}{{forloop.counter}}</td>
<td>{{ sform.siNo }} {{sform.coi_code}}</td>
<td>{{ sform.numberUnitsLoaded }} {%for error in sform.numberUnitsLoaded.errors%}<span class='error'> {{error|escape}}</span>{%endfor%}</td>
<td>{{ sform.overloadedUnits}}</td>
</tr>
{% endfor %}
</table>
First of all, you should refactor your models.
Create model WareHouse:
class WareHouse(models.Model):
code = models.CharField...
Link OrderItem and StockItem to warehouse with foreign keys instead of 'origin_wh_code' and 'wh_code'. Only then you will be able to select data using joins.
Use choice field with custom choices or even better - create inherited from forms.TypedChoiceField field, which encapsulates logic of serializing (stock item, order item) pks.
choices = StockItem.objects.filter(commodity_code=F("warehouse__orders__commodity_code"))\
.values('pk', 'warehouse__orders__pk')# or , <other required fields>)
item = CustomChoiceField(choices= choices, required=True)
After post you could retrieve pair:
stock_item, order_item = form.cleaned_data['item']
#Save'em here