How to raise multiple ValidationError on Django Rest API? - django

Suppose I have three serializers in function and I want to check the validation. If any errors occur in the condition it Response error message at a time
My function:
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
if employ_basic_info_serializer.is_valid() and employ_academic_info_serializer.is_valid() and employ_address_serializer.is_valid():
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error':employ_basic_info_serializer.errors,
'employ_academic_info_error':employ_academic_info_serializer.errors,
'employ_address_error':employ_address_serializer.errors,
}
return Response({'stutase':status_errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST)
I want to return employ_basic_info_serializer, employ_academic_info_serializer, employ_address_serializer errors if any errors occur. How can I do it? pls, help me...

Make sure to call the is_valid() method of each serializer object as,
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(
data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(
data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
is_valid_employ_basic_info_serializer = employ_basic_info_serializer.is_valid()
is_valid_employ_academic_info_serializer = employ_academic_info_serializer.is_valid()
is_valid_employ_address_serializer = employ_address_serializer.is_valid()
if (
is_valid_employ_academic_info_serializer and
is_valid_employ_basic_info_serializer and
is_valid_employ_address_serializer
):
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error': employ_basic_info_serializer.errors,
'employ_academic_info_error': employ_academic_info_serializer.errors,
'employ_address_error': employ_address_serializer.errors,
}
return Response(
{'stutase': status_errors},
status=rest_framework.status.HTTP_400_BAD_REQUEST
)

Related

inserting a data in a formset passed by a form

hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser:
NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id
it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me
schedaName = schede_form.cleaned_data['nome_scheda']
scheda = schede_form.save(commit = False)
scheda.utente = request.user
scheda.save()
#gruppi
if gruppi_formset.is_valid():
for gruppi in gruppi_formset:
gruppi.save(commit = False)
gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
//print(gruppi.gruppi_scheda)
gruppi.save()
You have to assign the return value of gruppi.save(commit=False) into a variable and update the gruppi_scheda property there:
gruppi_instance = gruppi.save(commit=False)
gruppi_instance.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
gruppi_instance.save()

Pyomo Value Error: No value for uninitialized NumericValue object

I am relatively new to Pyomo and I am testing some energy optimization model at the moment. I can define all the objectives and constraints but when trying to solve I get the following error:
'ValueError: No value for uninitialized NumericValue object x[batt]'
Here is relevant parts of my code (things that I don't think are relevant I just filled with ... to save some space):
ders = ["pv", "batt"]
model = ConcreteModel()
model.x = Var(ders, within = NonNegativeReals)
model.p_pv_load = Var(tsIndex, within = NonNegativeReals)
model.p_pv_grid = Var(tsIndex, within = NonNegativeReals)
model.p_pv_batt = Var(tsIndex, within = NonNegativeReals)
model.p_batt_load = Var(tsIndex, within = NonNegativeReals)
model.p_batt_grid = Var(tsIndex, within = NonNegativeReals)
model.soc_batt = Var(tsIndex, within = NonNegativeReals)
model.p_grid_load = Var(tsIndex, within = NonNegativeReals)
model.p_grid_batt = Var(tsIndex, within = NonNegativeReals)
#obj
def obj_rule(model):
return sum(... for ts in tsIndex)
model.obj = Objective(rule = obj_rule, sense = maximize)
#Some potentially relevant Constraints
maxPV = Constraint(expr = model.x["pv"]<=400)
maxBat= Constraint(expr = model.x["batt"]<=400)
socMin = 0.1*model.x["batt"]
socMax = 0.9*model.x["batt"]
socIni = socMin
batt_pMax=model.x["batt"]/3
#Discharge
def battDisc_rule(model, ts):
if ts==0:
return (((model.p_batt_load[ts]+model.p_batt_grid[ts])*(timestep/60))/sqrt(effR_bat) <= model.soc_batt[ts])
else:
return (((model.p_batt_load[ts]+model.p_batt_grid[ts])*(timestep/60))/sqrt(effR_bat) <= model.soc_batt[ts-1])
model.battDisc = Constraint(tsIndex, rule = battDisc_rule)
#Charge
def battCh_rule(model, ts):
if ts==0:
return ((model.p_pv_batt[ts]+model.p_grid_batt[ts])*(timestep/60))*sqrt(effR_bat) <= socMin-model.soc_batt[ts]
else:
return ((model.p_pv_batt[ts]+model.p_grid_batt[ts])*(timestep/60))*sqrt(effR_bat) <= socMin-model.soc_batt[ts-1]
model.battCh = Constraint(tsIndex, rule = battCh_rule)
#Soc
def socBounds_rule(model, ts):
return inequality(socMin, model.soc_batt[ts], socMax)
model.socBounds = Constraint(tsIndex, rule = socBounds_rule)
def update_SOC(model, ts):
if ts==0:
return model.soc_batt[ts]==socIni
else:
return model.soc_batt[ts] == model.soc_batt[ts-1]+(((model.p_pv_batt[ts]+model.p_grid_batt[ts]*sqrt(effR_bat))-((model.p_batt_load[ts]+model.p_batt_grid[ts])/sqrt(effR_bat)))*(timestep/60))
model.updateSOC = Constraint(tsIndex, rule=update_SOC)
def chPower_rule(model, ts):
return model.p_pv_batt[ts]+model.p_grid_batt[ts]*sqrt(effR_bat) <= batt_pMax
model.chPower = Constraint(tsIndex, rule=chPower_rule)
def dchPower_rule(model, ts):
return model.p_batt_load[ts]+model.p_batt_grid[ts]/sqrt(effR_bat) <= batt_pMax
model.dchPower = Constraint(tsIndex, rule=dchPower_rule)
I do not understand the error message since of course x[batt] is uninitialized as it is one of the decision variables.
Weirdly, in Julia's JuMP i can make it run using exactly the same GLPK solver and model description.
Thanks a lot for your help in advance.
The problem was the inequality() constraint function in combination with that I forgot to add "model" to the constraint declaration twice.

Django - passing a dict to form constructor and having it available globally in the class

I'm making a big mess trying to access the object that I passed from the view to the form.
class PrenotaForm(forms.ModelForm):
ORARI_CHOICES = ()
def __init__(self, *args, **kwargs):
DICT_ORARI_CHOICES = kwargs.pop('ORARI_CHOICES_NEW', {})
ORARI_CHOICES_NEW = []
for key, value in DICT_ORARI_CHOICES.items():
temp = [key,value]
ORARI_CHOICES_NEW.append(temp)
super(PrenotaForm, self).__init__(*args, **kwargs)
self.ORARI_CHOICES = ORARI_CHOICES_NEW
print("EEEEEEEEEEEEEEE" + str(self.ORARI_CHOICES))
print(ORARI_CHOICES)
I don't understand why inside the init the ORARI_CHOICES is populated as shown in console output:
EEEEEEEEEEEEEEE[['è uguale', 'Indifferente'], ['845', '08:45'], ['900', '09:00'], ['915', {'label': '09:15', 'disabled': 'disabled'}], ['930', {'label': '09:30', 'disabled': 'disabled'}], ['945', '09:45'], ['1000', '10:00'], ['1015', '10:15'], ['1030', '10:30'], ['1045', '10:45'], ['1100', '11:00'], ['1115', '11:15'], ['1130', '11:30'], ['1145', '11:45']]
but outside the init the ORARI_CHOICE is still empty:
print(ORARI_CHOICES)
since the print does not output nothing.
How can I override the ORARI_CHOICES = () and make it avalable globally in the class after every GET request performed in the view?
if request.method == 'GET':
size_gruppi = 30
print("gruppi size is : " + str(size_gruppi))
ORARI_CHOICES = (
('è uguale', "Indifferente"),
('845', "08:45"),
('900', "09:00"),
('915', "09:15"),
('930', "09:30"),
('945', "09:45"),
('1000', "10:00"),
('1015', "10:15"),
('1030', "10:30"),
('1045', "10:45"),
('1100', "11:00"),
('1115', "11:15"),
('1130', "11:30"),
('1145', "11:45"),
)
orari_map = map(list,ORARI_CHOICES)
orari_dict = dict(ORARI_CHOICES)
print(orari_dict)
counter = 0
for key in orari_map:
if key[0] != 'è uguale':
tot_in_fascia = sum(filter(None, Iscritto.objects.filter(fasce_orarie=key[0]).aggregate(Sum('size_adulti'), Sum('size_giovani')).values()))
print(tot_in_fascia)
if tot_in_fascia >= size_gruppi:
print("fascia " + key[0] + " è al completo ")
orari_dict.update({key[0]: {'label': key[1], 'disabled': 'disabled'}})
form = PrenotaForm(ORARI_CHOICES_NEW = orari_dict)
return render(request, "prenota.html", {'form': form, 'posti_liberi': posti_disponibili, 'giovani_iscritti': giovani_iscritti})
You should set ORARI_CHOICES as a class/static attribute.
class PrenotaForm(forms.ModelForm):
ORARI_CHOICES = []
def __init__(self, *args, **kwargs):
DICT_ORARI_CHOICES = kwargs.pop('ORARI_CHOICES_NEW', {})
# ORARI_CHOICES_NEW = []
for key, value in DICT_ORARI_CHOICES.items():
temp = [key,value]
self.__class__.ORARI_CHOICES.append(temp)
super(PrenotaForm, self).__init__(*args, **kwargs)
print("EEEEEEEEEEEEEEE" + str(self.ORARI_CHOICES))
Now, PrenotaForm.ORARI_CHOICES is already accessible. PrenotaForm.ORARI_CHOICES will always be accessible, but it returns empty list, untill you do not create instance of PrenotaForm. After instance creation of PrenotaForm, __init__ method will be called and data will be added inside ORARI_CHOICES.

django: Class-based Form has no errors but is not valid. What is happening?

I have a form which is returning False from .is_valid(), but .errors and .non_field_errors() appear to be empty. Is there any other way to check out what might be causing this?
In case it's a problem with my logging code, here it is:
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
My form code:
class IncorporateForm(forms.Form):
type_choices = (("LTD", "Private company limited by shares"),
("LTG", "Private company limited by guarantee"),
("PLC", "Public limited company"),
("USC", "Unlimited company with share capital"),
("UWS", "Unlimited company without share capital"))
country_choices = (("EW", "England and Wales"),
("CY", "Wales"),
("SC", "Scotland"),
("NI", "Northern Ireland"))
articles_choices = (("MOD", "Model articles"),
("AMD", "Model articles with amendments"),
("BES", "Entirely bespoke articles"))
name = forms.CharField(initial = "[name] limited")
registered_office = forms.CharField(widget=forms.Textarea,
label='Registered office address')
registration_country = forms.ChoiceField(choices=country_choices,
widget=forms.RadioSelect(renderer=SaneRadioField))
company_type = forms.ChoiceField(choices=type_choices,
widget=forms.RadioSelect(renderer=SaneRadioField), initial="LTD")
articles_type = forms.ChoiceField(choices=articles_choices,
initial='MOD',
widget=forms.RadioSelect(renderer=SaneRadioField))
restricted_articles = forms.BooleanField()
arts_upload = forms.FileField(label='Articles to upload')
My view code (to the point where I detect that the form is not valid):
def incorporate_view(request):
form = IncorporateForm()
DirectorsFormset = forms.formsets.formset_factory(OfficerForm, extra=30)
CapitalFormset = forms.formsets.formset_factory(CapitalForm, extra=30)
HoldingFormset = forms.formsets.formset_factory(HoldingForm, extra=30)
AmendsFormset = forms.formsets.formset_factory(ArticlesAmendsForm, extra=50)
if request.method == 'POST':
#bind and validate
form.data = request.POST
guarantee_form = GuaranteeForm(data=request.POST)
directors_formset = DirectorsFormset(prefix='directors', data=request.POST)
capital_formset = CapitalFormset(prefix='capital', data=request.POST)
holding_formset = HoldingFormset(prefix='holding', data=request.POST)
amends_formset = AmendsFormset(prefix='amends', data=request.POST)
save_objects = [] # objects to be saved at the end if there is no error
user_objects = {} # keyed by email
individual_objects = {} # keyed by email?
if(not (form.is_valid() and guarantee_form.is_valid()
and directors_formset.is_valid()
and capital_formset.is_valid() and
holding_formset.is_valid() and
amends_formset.is_valid())):
dbg_str = """
form.is_valid(): %s
guarantee_form.is_valid(): %s
directors_formset.is_valid(): %s
capital_formset.is_valid(): %s
holding_formset.is_valid(): %s
amends_formset.is_valid(): %s
""" % (form.is_valid(), guarantee_form.is_valid(),
directors_formset.is_valid(),
capital_formset.is_valid(),
holding_formset.is_valid(),
amends_formset.is_valid())
logger.debug(dbg_str)
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
Assigning to form.data does not bind the form — you should pass the data dict when the object is constructed (or look into the code and see which flags are set, but that's probably not documented and therefore not recommended).

filter using Q object with dynamic from user?

In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)