Editing Fromset ModelChoiceField - django

When i edit formset the ModelChoiceField don't show initial value (it show the empty label). I use this example
https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html
demande\forms.py
class LinkForm(forms.Form):
etabz = forms.ModelChoiceField(empty_label="Choisir un établissement",\
queryset=Etablissement.objects.all().order_by('univ','etablissement').distinct(),
)
# etabz = forms.CharField()
def __init__(self, *args, **kwargs):
dbz = kwargs.pop("dbz", None)
super(LinkForm, self).__init__(*args, **kwargs)
if dbz:
self.fields["etabz"].queryset = Etablissement.objects.filter(univ__corps=dbz)
class BaseLinkFormSet(BaseFormSet):
def clean(self):
if any(self.errors):
return
anchors = []
urls = []
duplicates = False
for form in self.forms:
if form.cleaned_data:
dona = form.cleaned_data.get('etabz')
anchor = dona.etablissement
if anchor :
if anchor in anchors:
duplicates = True
anchors.append(anchor)
if duplicates:
raise forms.ValidationError(
'Vous ne pouvez choisir le même établissement plusiuers fois.',
code='duplicate_etab'
)
def __init__(self, *args, **kwargs):
super(BaseLinkFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
Demande\views.py
#login_required
def demande(request):
user = request.user
corpsorigine = user.profile.corps
uz = get_object_or_404(session, active=True, destine = user.profile.corps)
choice_links = choix.objects.filter(demandeur = user, session = uz )
link_data = [{'etabz': l}
for l in choice_links]
LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet, extra=1)
if request.method == 'POST':
link_formset = LinkFormSet(request.POST,form_kwargs={'dbz':corpsorigine })
if link_formset.is_valid():
new_links = []
for link_form in link_formset:
dona = link_form.cleaned_data.get('etabz')
try:
univ = dona.univ
etablissementa = dona.etablissement
except:
messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement')
return redirect(reverse('blog:post_list'))
if etablissementa and univ:
new_links.append(choix(demandeur = user,session=uz.annee_session, etablissement_demande=etablissementa, universite_demande=univ))
try:
with transaction.atomic():
UserLink = choix.objects.all()
UserLink.filter(session= uz.annee_session,demandeur = user).delete()
UserLink.bulk_create(new_links)
messages.success(request, 'Votre demande à été correctement saisie/mis à jour.')
return redirect(reverse('blog:post_list'))
except IntegrityError: # If the transaction failed
messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement')
return redirect(reverse('blog:post_list'))
else:
link_formset = LinkFormSet(initial=link_data,form_kwargs={'dbz':corpsorigine })
context = {
'uz':uz,
'link_formset': link_formset,
'choice_links':choice_links
}
return render(request, 'edit_pro.html', context)
Account\Models.py
class universite (models.Model):
gouvernorat= models.CharField(max_length=250)
universite = models.CharField(max_length=250)
corps = models.CharField(max_length=20, choices=corps_CHOICES)
class Meta:
unique_together = ('gouvernorat', 'universite')
def __str__(self):
return self.universite
class etablissement(models.Model):
etablissement = models.CharField(max_length=250)
univ = models.ForeignKey(universite, related_name='etab_universites')
def __unicode__(self):
return "{} de l'universite {}".format(self.etablissement,self.univ)
Demande\models.py
class choix(models.Model):
demandeur = models.ForeignKey(User, related_name='user_choice')
# universite_demande = models.ForeignKey(universite, related_name='universite_choice')
session = models.CharField(max_length=250)
universite_demande = models.CharField(max_length=250)
etablissement_demande = models.CharField(max_length=250)
class Meta:
unique_together = ('demandeur', 'session','etablissement_demande')
def __unicode__(self):
return "{} de l'universite {}".format(self.etablissement_demande, self.universite_demande)
In demande\forms.py If i change forms.ModelChoiceField... to forms.CharField it works perfectly. How it can works on ModelChoiceField ?

Related

request.user in createdview

How implement that the user in the Model Entities add automatically the user that is authenticated in django?
now, returning the following error:
error
I have tried differents methods that i have founding in the internet but not function. all cases return error in the momento to record a row.
only, i need that, in the moment that create a row, the user field was the user that is authenticated.
My Model:
class Entities(models.Model):
#class Category(models.Model):
id = models.BigAutoField(primary_key=True)
code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True,
help_text='Codigo de entidad.')
name = models.CharField(max_length=150, verbose_name='Nombre', unique=True,
help_text='Nombre de la entidad.')
desc = models.CharField(max_length=500, null=True, blank=True, verbose_name='Descripción',
help_text='Descripción de la entidad.')
name_report = models.CharField(verbose_name='Nombre Reporte', max_length=100, blank=False, unique=True,
help_text='Rellenar para ACTIVAR el reporte')
long_desc = models.CharField(verbose_name='Descripción Larga', max_length=800, blank=True,
help_text='Descripción larga. Máximo 800 caracteres.')
language = models.CharField(verbose_name='Idioma', max_length=2, choices=languages, default='ES',
help_text='Idioma del reporte')
user = models.ForeignKey(User, default=0, verbose_name='Usuario', on_delete=models.DO_NOTHING)
date_created = models.DateTimeField(default=timezone.now, verbose_name='Creado', blank=False, unique=False)
date_updated = models.DateTimeField(default=timezone.now, verbose_name='Actualizado', blank=False, unique=False)
historical = HistoricalRecords()
def __str__(self):
return self.name
def toJSON(self):
item = model_to_dict(self)
return item
class Meta:
verbose_name = 'Entidad'
verbose_name_plural = 'Entidades'
ordering = ['id']
My CreateView:
class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Entities
form_class = EntitiesForm
template_name = 'Entities/create.html'
success_url = reverse_lazy('erp:entities_list')
permission_required = 'add_Entities'
url_redirect = success_url
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Creación de una Entidad'
context['entity'] = 'Entidades'
context['list_url'] = self.success_url
context['action'] = 'add'
return context
My Form:
class EntitiesForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# for form in self.visible_fields():
# form.field.widget.attrs['class'] = 'form-control'
# form.field.widget.attrs['autocomplete'] = 'off'
self.fields['code'].widget.attrs['autofocus'] = True
class Meta:
model = Entities
fields = '__all__'
exclude = ['user','date_created','date_updated']
widgets = {
'name': forms.TextInput(
attrs={
'placeholder': 'Ingrese un nombre',
}
),
'desc': forms.Textarea(
attrs={
'placeholder': 'Ingrese un nombre',
'rows': 3,
'cols': 3
}
),
}
def save(self, commit=True):
data = {}
form = super()
try:
if form.is_valid():
**self.instante.user = self.request.user**
form.save()
else:
data['error'] = form.errors
except Exception as e:
data['error'] = str(e)
return data
SOLVED.
Adding, in the view, the line :
form.instance.user = self.request.user
full Createview would be :
class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Entities
form_class = EntitiesForm
template_name = 'Entities/create.html'
success_url = reverse_lazy('erp:entities_list')
permission_required = 'add_Entities'
url_redirect = success_url
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
form.instance.user = self.request.user <============================
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Creación de una Entidad'
context['entity'] = 'Entidades'
context['list_url'] = self.success_url
context['action'] = 'add'
return context
If you want to save additional data into form you can commit=False for this...
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
form = self.get_form()
form = form.save(commit=False)
form.user = request.user
data = form.save()
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
return JsonResponse(data)

Django - form_valid() takes 2 positional arguments but 5 were given - Multiple forms

I am new using Django and I want to save 4 different forms using CreateView. I am able to save 3 of them:
Product Form
Product Cost Form
Product Prices Form
But with Product inventory Form, I am getting this error: form_valid() takes 2 positional arguments but 5 were given.
Product inventory Form:
class ProdInvForm2(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Row(
Column('invmax', css_class='form-group col-md-6 mb-0'),
Column('invmin', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
)
class Meta:
model = ProdInv
# fields = ('invmin', 'invmax')
widgets = {
'invmax': NumberInput(
attrs={
'placeholder': 'Inventario Maximo',
}
),
'invmin': NumberInput(
attrs={
'placeholder': 'Inventario Minimo',
}
),
}
# esto es para excluir campos que no quieres que aparezcan
#, 'invact', 'invord', 'invres'
exclude = ['user_updated', 'user_creation', 'prod', 'invact', 'invord', 'invres']
Product Inventory Models:
class ProdInv(BaseModel):
prod = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Producto')
invact = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Actual')
invres = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Reservado')
invord = models.IntegerField(default=0, null=True, blank=True, verbose_name='Inventario Ordenado')
invmax = models.IntegerField(default=0, blank=True, verbose_name='Inventario Maximo')
invmin = models.IntegerField(default=0, blank=True, verbose_name='Inventario Minimo')
def toJSON(self):
item = model_to_dict(self, exclude=['user_creation', 'user_updated'])
item['prod'] = self.prod.toJSON()
return item
def __str__(self):
return self.prod.name
class Meta:
verbose_name = 'Inventario de Producto'
verbose_name_plural = 'Inventario de Productos'
ordering = ['id']
CreateView:
class ProductCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
model = Product
form_class = ProductForm
template_name = 'product/create.html'
success_url = reverse_lazy('erpInv:product_list')
permission_required = 'erpAdm.add_product'
url_redirect = success_url
#method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
formprod = ProductForm(request.POST)
formcost = ProdCostForm(request.POST)
formprice = ProdPriceForm(request.POST)
formprodinv = ProdInvForm2(request.POST)
AV_formset = AttrValueFormSet(request.POST)
with transaction.atomic():
if formprod.is_valid() and formcost.is_valid() and formprice.is_valid() \
and formprodinv.is_valid():
return self.form_valid(formprod, formcost, formprice, formprodinv)
else:
return self.form_invalid(formprod, formcost, formprice, formprodinv)
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
# acuerdate cuando es coleccion de elementos, hay que serializar con safe=flase
return JsonResponse(data, safe=False)
def form_valid(self, formprod, formcost, formprice, formprodinv):
# hubo que cmentar e save del form, para que funcione el save()
with transaction.atomic():
prod = formprod.save(commit=True)
print(prod.pk)
price = formprice.save(commit=False)
price.prod_id = prod.pk
cost = formcost.save(commit=False)
cost.prod_id = prod.pk
print(cost)
inv = formprodinv.save(commit=False)
inv.prod_id = prod.pk
print(inv)
inv.save()
cost.save()
price.save()
return super().form_valid(formprod, formcost, formprice, formprodinv)
def form_invalid(self, formprod, formcost, formprice, formprodinv):
return self.render_to_response(
self.get_context_data(formprod=formprod.errors, formcost=formcost.errors, formprice=formprice.errors,
formprodinv=formprodinv.errors))
# Dont Know which one to use as return statement
# return super().form_invalid(formprod=formprod.errors, formcost=formcost.errors, formprice=formprice.errors,
# formprodinv=formprodinv.errors)
def get_context_data(self, **kwargs):
# AVForm = AttrValueForm(prefix='avprefix')
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
context = super().get_context_data(**kwargs)
context['title'] = 'Creación un Producto'
context['entity'] = 'Productos'
context['list_url'] = self.success_url
context['action'] = 'add'
context['formcost'] = ProdCostForm()
context['formprice'] = ProdPriceForm(prefix='precio')
context['formprodinv'] = ProdInvForm2(prefix='invent')
# Next step try to use formset to save product attributes
# context['AV_formset'] = AttrValueFormSet(prefix='avprefix')
# context['avHelper'] = AVHelper()
return context
I did the test and comment "transaction.atomic()". I was able to save to other forms, but do not know why I am having this problem with the Product Inventory Form.
Hope someone can highlight what I am doing wrong.
Cheers and Happy New Year
To solve my problem I saved the forms inside de def POST. Instead of using the form_valid().
def post(self, request, *args, **kwargs):
data = {}
try:
action = request.POST['action']
if action == 'add':
AttrValueFormSet = formset_factory(AttrValueForm, can_delete=True, extra=1)
formprod = ProductForm(request.POST)
formcost = ProdCostForm(request.POST)
formprice = ProdPriceForm(request.POST)
formprodinv = ProdInvForm2(request.POST)
AV_formset = AttrValueFormSet(request.POST)
with transaction.atomic():
if formprod.is_valid() and formcost.is_valid() and formprice.is_valid() and formprodinv.is_valid():
print('los form son validos')
prod = formprod.save(commit=True)
print(prod.pk)
price = formprice.save(commit=False)
print('precio')
print(formprice.cleaned_data)
price.prod_id = prod.pk
cost = formcost.save(commit=False)
print('costo')
cost.prod_id = prod.pk
inv = formprodinv.save(commit=False)
print('Inventario')
print(formprodinv.cleaned_data)
inv.prod_id = prod.pk
inv.save()
cost.save()
price.save()
else:
print('los forms NO son validos')
return formprod.errors, formprice.errors, formcost.errors, formprodinv.errors
else:
data['error'] = 'No ha ingresado a ninguna opción'
except Exception as e:
data['error'] = str(e)
# acuerdate cuandp es coleccion de elementos, hay que serializar con safe=flase
return JsonResponse(data, safe=False)

Django: field validator and UNIQUE constraint are not applyed

I have a Randomisation model with pat field that should be unique and have a specified format.
I defined unique=true and and validators but neither are applyed
For example, FRA-0001 sould be valid and if I try to registered this code twice it should raise an error validation message on my form (but not crash database).
But currently, I can registered FRA for example and if I registered it twice I raise database error UNIQUE contraint failed
models.py
class Randomisation(models.Model):
...
pat = models.CharField("Patient number", max_length=8, unique=True, null=True, blank=True,
validators = [
RegexValidator(
regex='^[A-Z]{3}-[0-9]{4}$',
message= 'L\'identifiant doit être au format XXX-0000',
code='invalid_participant_id'
),
],
)
...
forms.py
class RandomizationEditForm(forms.Form):
def __init__(self, request, *args, **kwargs):
super(RandomizationEditForm, self).__init__(*args, **kwargs)
self.user_country = Pays.objects.get(pay_ide = request.session.get('user_country'))
# self.language = request.session.get('language')
# print(self.language)
self.user_site_type = request.session.get('user_site_type')
PAYS = Pays.options_list(self.user_country,self.user_site_type,'fr')
SEXE = Thesaurus.options_list(2,'fr')
STRATE_1 = Thesaurus.options_list(3,'fr')
STRATE_2 = Thesaurus.options_list(4,'fr')
YES = [(None,''),(0,'Non'),(1,'Oui'),]
self.fields["pat"] = forms.CharField(label = "Numéro patient (XXX-0000)")
self.fields['pat'].widget.attrs.update({
'autocomplete': 'off'
})
self.fields["ran_nai"] = forms.IntegerField(label = "Date de naissance (année)", widget=forms.TextInput)
self.fields['ran_nai'].widget.attrs.update({
'autocomplete': 'off'
})
self.fields["ran_sex"] = forms.ChoiceField(label = "Sexe", widget=forms.Select, choices=SEXE)
self.fields["ran_st1"] = forms.ChoiceField(label = "Gravité de la maladie COVID-19", widget=forms.Select, choices=STRATE_1)
self.fields["ran_bug"] = forms.BooleanField(label = "Recours à la procédure de secours ?", required = False)
self.fields["ran_dem_nom"] = forms.CharField(label = "Nom de la personne qui demande la randomisation", required = False, initial=None)
self.fields['ran_dem_nom'].widget.attrs.update({
'autocomplete': 'off'
})
self.fields["ran_dem_dat"] = forms.DateField(
# input_formats=settings.DATE_INPUT_FORMATS,
label = "Date de la demande",
initial = timezone.now(),
required = False,
)
self.fields['ran_dem_dat'].widget.attrs.update({
'autocomplete': 'off'
})
# def clean_pat(self):
# data = self.cleaned_data['pat']
# if len(data) < 8:
# raise forms.ValidationError("Merci de contrôler la numéro patient")
# return data
def clean_ran_nai(self):
data = self.cleaned_data['ran_nai']
if data > 2003:
raise forms.ValidationError("Merci de contrôler la date de naissance")
return data
def clean_ran_dem_dat(self):
data = self.cleaned_data['ran_dem_dat']
entrydate = datetime.datetime.strptime(str(data), "%Y-%m-%d")
currentdate = datetime.datetime.now()
if entrydate > currentdate:
raise forms.ValidationError("Merci de contrôler la date (postérieure à la date du jour)")
return data
views.py
def randomization_edit(request):
if request.method == "POST":
form = RandomizationEditForm(request, data=request.POST or None)
if form.is_valid():
# Récupération des données permettant la randomisation
randomisation = Randomisation.objects.filter(Q(pay_ide=form.data.get('pay_ide')) & Q(ran_act=1) & Q(ran_st1=form.data.get('ran_st1')) & Q(pat=None)).first()
randomisation.pat = form.cleaned_data['pat']
randomisation.ran_nai = form.data.get('ran_nai')
randomisation.ran_sex = form.data.get('ran_sex')
randomisation.ran_bug = form.cleaned_data['ran_bug']
if form.data.get('ran_dem_nom') == '':
randomisation.ran_dem_nom = None
else:
randomisation.ran_dem_dat = form.data.get('ran_dem_dat')
randomisation.ran_log = request.user.username
randomisation.ran_dat = timezone.now()
randomisation.save()
return redirect('randomization:confirmation', pk = randomisation.pk)
else:
form = RandomizationEditForm(request)
return render(request, 'randomization/edit.html', {'form': form})
You're redefining the pat field as a CharField in your form, so none of the validations you specified on the model apply. You can either rewrite your form to be a ModelForm or add the regex and uniqueness validation into your form.
class RandomizationEditForm(forms.Form):
def __init__(self, *args, **kwargs):
super(RandomizationEditForm, self).__init__(*args, **kwargs)
self.fields["pat"] = forms.CharField(label = "Numéro patient (XXX-0000)", validators=[RegexValidator(
regex='^[A-Z]{3}-[0-9]{4}$',
message= 'L\'identifiant doit être au format XXX-0000',
code='invalid_participant_id'
)])
def clean_pat(self):
data = self.cleaned_data['pat']
if Randomisation.objects.filter(pat=data).exists():
raise forms.ValidationError("L\'identifiant doit être unique")
return data

How to validate if a field is not blank in a form when it's set Blank = True in the model

I have a model which is filled in different steps by different forms. Fields that are not filled in the first step need to be set Blank = True so you can submit the form. When I try to fill those fields later, the form lets the user leave them blank, which is undesirable. How can I make them mandatory in the subsequent forms?
I've tried implementing a Validation method (clean_almacen) like the one below, but it does nothing.
class RecepcionForm(ModelForm):
def clean_almacen(self):
data = self.cleaned_data['almacen']
# Check if the field is empty.
if data == '':
raise ValidationError(_('¡Seleccione un almacén!'))
return data
def clean_usuario(self):
if not self.cleaned_data['usuario_recepcion']:
return User()
return self.cleaned_data['usuario_recepcion']
class Meta:
model = Pedido
fields = ['almacen']
Also, setting the field Blank = False and null = True will make this work, but it will make mandatory to assign a value to the field when you edit the object in the admin page (which is undesirable too).
This is my code:
models.py
class Pedido(models.Model):
nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.'))
referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.'))
cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = _('CPM'))
fecha = models.DateTimeField(auto_now_add=True)
fecha_cpm = models.DateTimeField(blank=True, null=True, verbose_name=_('Fecha asignación CPM'))
unidades = models.IntegerField(default = 1)
usuario = models.ForeignKey(User, on_delete=models.CASCADE, blank = True)
autogestion = models.BooleanField(default = False, verbose_name='Autogestión', help_text = _("Marca esta casilla si vas a procesar tú mismo el pedido."))
usuario_recepcion = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='recepcion', verbose_name=_('Recepcionado por'))
fecha_recepcion = models.DateTimeField(blank=True, null=True)
ESTADO_PEDIDO = (
('n', _('Pendiente')),
('p', _('Proforma solicitada')),
('c', _('CPM solicitado')),
('v', _('Para validar')),
('r', _('Recibido')),
('b', _('Bloqueado')),
)
estado = models.CharField(
max_length=1,
choices=ESTADO_PEDIDO,
blank=False,
default='n',
help_text=_('Estado del pedido'),
)
fabricante = models.ForeignKey('Fabricante', null = True, on_delete=models.SET_NULL)
centro_gasto = models.ForeignKey('CentroGasto', null = True, on_delete=models.SET_NULL, verbose_name = _('Centro de Gasto'))
almacen = models.ForeignKey('Almacen', null = True, on_delete=models.SET_NULL, blank = True)
direccion = models.ForeignKey('Direccion', default = 'CIBM', null = True, on_delete=models.SET_NULL, verbose_name = _('Dirección de entrega'))
codigo = models.CharField(max_length=20, blank=True, default=keygen())
bloqueo = models.TextField(blank=True, verbose_name=_('Incidencias'), help_text = _('Anote las incidencias relacionadas con el pedido para que puedan ser solucionadas'))
views.py
#permission_required('gestion.puede_editar_cpm')
def añadir_cpm(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = CPMForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.estado = 'v'
model_instance.fecha_cpm = datetime.now()
model_instance.save(update_fields=['estado', 'fecha_cpm', 'cpm'])
return redirect('/')
else:
form = CPMForm()
return render(request, "gestion/cpm_edit.html", {'form': form})
#permission_required('gestion.puede_editar_cpm')
def cpm_block(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = CPMBlockForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.estado = 'b'
model_instance.save(update_fields=['estado', 'bloqueo'])
return redirect('/')
else:
form = CPMBlockForm()
return render(request, "gestion/cpm_block.html", {'form': form})
#login_required
def recepcion(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = RecepcionForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.usuario_recepcion = request.user
model_instance.estado = 'r'
model_instance.fecha_recepcion = datetime.now()
model_instance.save(update_fields=['usuario_recepcion', 'almacen', 'fecha_recepcion', 'estado'])
return redirect('/')
else:
form = RecepcionForm()
return render(request, "gestion/pedido_recepcionar.html", {'form': form})
forms.py
class PedidoForm(ModelForm):
def clean_usuario(self):
if not self.cleaned_data['usuario']:
return User()
return self.cleaned_data['usuario']
class Meta:
model = Pedido
exclude = ['codigo', 'fecha', 'cpm', 'almacen', 'estado', 'usuario']
class RecepcionForm(ModelForm):
def clean_almacen(self):
data = self.cleaned_data['almacen']
# Check if a date is not in the past.
if data == '':
raise ValidationError(_('¡Seleccione un almacén!'))
return data
def clean_usuario(self):
if not self.cleaned_data['usuario_recepcion']:
return User()
return self.cleaned_data['usuario_recepcion']
class Meta:
model = Pedido
fields = ['almacen']
class CPMForm(ModelForm):
class Meta:
model = Pedido
fields = ['cpm']
class CPMBlockForm(ModelForm):
class Meta:
model = Pedido
fields = ['bloqueo']
I'm sorry for the long code, I don't know what could be useful or not. I hope you guys can help me.
Thanks in advance.
You would override the field definitions in the subsequent forms. You can do this declaratively:
class CPMForm(ModelForm):
cpm = forms.CharField(required=True, max_length=20, initial='A la espera.', help_text=_('Código del CPM asignado a este pedido.'), label=_('CPM'))
class Meta:
model = Pedido
fields = ['cpm']
or programmatically:
class CPMBlockForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['bloqueo'].required = True
class Meta:
model = Pedido
fields = ['bloqueo']

Getting a field value using Django

Can I get the value of the field which I am not showing in form? I want to pass ref_id in session.
This is my model:
def _createId():
"""
"""
return hexlify(os.urandom(4))
class jobpost(models.Model):
item_types = (
('Full Time','Full Time'),
('Part Time','Part Time'),
('Contract','Contract'),
)
posttype= (
('Job','Job'),
('Classified','Classified'),
('Project/Task','Project/Task'),
('Internship','Internship'),
)
#user = models.ForeignKey(User)
job_id = models.AutoField(primary_key=True)
country= models.ForeignKey(Country,to_field = 'country_name', null=True)
#user = models.ForeignKey(User, editable = False)
post_type = models.CharField(max_length=255,null=True, choices=posttype,default='Job')
job_type = models.CharField(max_length=255,null=True, choices=item_types,default='Full Time')
job_location = models.CharField(max_length=255,null=True)
job_title = models.CharField(max_length=255,null=True)
job_description = models.TextField(null=True)
start_date = models.DateField(null=True, help_text="mm/dd/yyyy")
end_date = models.DateField(null=True, help_text="mm/dd/yyyy")
how_to_apply = models.CharField(max_length=255,null=True)
ref_id = models.CharField(max_length=32, default=_createId)
def __unicode__(self):
return unicode(self.country)
return self.post_type
return self.job_location
return self.job_type
return self.job_title
return self.job_description
return self.start_date
return self.end_date
return self.how_to_apply
return self.ref_id
means i am not displaying it in my form and i want to pass this value in session in next form..
can anyone tell me how can i do this? and how can i pass the primary key of the form in next form ?
forms.py
class JobPostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobPostForm, self).__init__(*args, **kwargs)
self.fields['ref_id'].widget = forms.HiddenInput()
class Meta:
model = jobpost
views.py
def your_view(request):
if request.method == 'POST':
form = JobPostForm(request.POST)
if form.is_valid():
request.session['ref_id'] = form.cleaned_data.get('ref_id')
pk = form.save()
request.session['pk'] = pk.id
else:
form = JobPostForm()
return render(request, page.html,{'form': form})