'Models' object has no attribute 'update' - django

I'm trying to create a new function but I'm getting this Django error :
'SocieteIntervention' object has no attribute 'update'
I have several models in my application :
class Societe(models.Model):
Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société')
Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat")
Adresse = models.CharField(max_length=30, verbose_name='Adresse')
Ville = models.CharField(max_length=30, verbose_name='Ville')
Zip = models.IntegerField(verbose_name='Code Postal')
Region = models.CharField(max_length=30, verbose_name='Région')
Pays = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
Mail = models.CharField(max_length=40, verbose_name='Email')
Web = models.CharField(max_length=40, verbose_name='Site Web')
Telephone = models.CharField(max_length=20, verbose_name='Téléphone Fixe')
Fax = models.CharField(max_length=20, verbose_name='Fax')
SIREN = models.BigIntegerField(verbose_name='N° SIREN')
SIRET = models.BigIntegerField(verbose_name='N° SIRET')
NAF_APE = models.CharField(max_length=5, verbose_name='Code NAF-APE')
RCS = models.CharField(max_length = 30, verbose_name='Code RCS')
CHOIX_TVA = models.CharField(max_length = 30, choices=CHOIX_TVA, verbose_name='Assujeti à la TVA')
TVA = models.CharField(max_length=13, verbose_name='N° TVA Intracommunautaire')
Type = models.CharField(max_length = 30, choices = CHOIX_SOCIETE, verbose_name = 'Type de Société')
Effectif = models.CharField(max_length = 30, choices = CHOIX_EFFECTIF, verbose_name = 'Effectif')
Capital = models.IntegerField(verbose_name = 'Capital de la Société (euros)')
Creation = models.DateTimeField(auto_now_add=True)
InformationsInstitution = models.CharField(max_length=30, null=False, verbose_name='Informations Institution')
Utilisateur = models.CharField(max_length=100, null=False, verbose_name="Utilisateur", default=" ")
def save(self, *args, **kwargs):
for field_name in ['Nom', 'Ville', 'Region']:
val = getattr(self, field_name, False)
if val:
setattr(self, field_name, val.upper())
super(Societe, self).save(*args, **kwargs)
class SocieteContrat(models.Model):
Societe = models.ForeignKey(Societe, related_name="Societe", verbose_name="Société")
PointsTotal = models.FloatField(verbose_name="Nombre points total")
PointsRestant = models.FloatField(verbose_name="Nombre points restants", null=True)
def __unicode__(self):
return unicode (self.id, self.Societe, self.PointsTotal, self.PointsRestant)
class SocieteIntervention(models.Model):
Societe = models.ForeignKey(Societe, related_name="Societe1", verbose_name="Société")
Date = models.DateField(verbose_name="Date de l'Intervention")
Temps = models.IntegerField(verbose_name="Durée Intervention (min)")
Description = models.CharField(max_length=200, verbose_name="Description")
Niveau = models.CharField(max_length = 30, choices = CHOIX_NIVEAU, verbose_name = 'Niveau Intervention/Intervenant')
PointsConsommes = models.FloatField(verbose_name=u"Nombre points consommés", null=True)
class CoefficientIntervention(models.Model):
Technicien = models.FloatField(verbose_name="Coefficient Technicien")
Ingenieur = models.FloatField(verbose_name="Coefficient Ingénieur")
Consultant = models.FloatField(verbose_name="Coefficient Consultant")
Architecte = models.FloatField(verbose_name="Coefficient Architecte")
def __unicode__(self):
return unicode (self.id, self.Technicien, self.Ingenieur, self.Consultant, self.Architecte)
My objective is : Create service contracts with a number of points. Points are deducted according to a coefficient. This coefficient depending on your status : Technician, Engineer, ...
I create this function in my view :
#login_required
def Identity_Contrat(request, id) :
societe = get_object_or_404(Societe, pk=id)
contrat = get_object_or_404(SocieteContrat, pk=id)
coefficient = CoefficientIntervention.objects.last()
if request.method == 'POST':
form = InterventionFormulaire(request.POST or None)
if form.is_valid() :
post = form.save()
Liste_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Temps")
Value = Liste_Intervention.last()[0]
Type_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Niveau")
if Type_Intervention.last() == (u'Ing\xe9nieur',) :
Consomme = Value * coefficient.Ingenieur
elif Type_Intervention.last() == ('Technicien',) :
Consomme = Value * coefficient.Technicien
elif Type_Intervention.last() == ('Consultant',) :
Consomme = Value * coefficient.Consultant
elif Type_Intervention.last() == ('Architecte',) :
Consomme = Value * coefficient.Architecte
PointsConsommes = SocieteIntervention.objects.latest('id').update(PointsConsommes=Consomme)
messages.success(request, 'Le formulaire a été enregistré !')
return HttpResponseRedirect('http://localhost:8000/Identity/Contrat/Societe/'+id)
else:
messages.error(request, "Le formulaire est invalide !")
else:
form = InterventionFormulaire()
context = {
"coefficient" : coefficient,
"societe" : societe,
"contrat" : contrat,
"form" : form,
}
return render(request, 'Identity_Societe_Contrat.html', context)
I fill the form, I save it with PointsConsommes == NULL,then I'm trying to update it with the value calculated previously.
How I can update the field PointsConsommes when the form is saved ? I don't overcome to update it with .update.

You can try to use update_fields:
PointsConsommes = SocieteIntervention.objects.latest('id')
PointsConsommes.PointsConsommes = Consomme
PointsConsommes.save(update_fields=['PointsConsommes'])

Related

Django Model default call back not adding beyond 10

I was hoping someone can assist with my issue in that when I used a default callback my 'account_number' field gets an Integrity Error when above 10. Without a default callback, I have no issues and it works.
My Account Model:
def account_number_increment():
last_number = Account.objects.all().order_by("account_number").last()
print("I am the last number")
start_from = AccountSettings.account_number_startfrom
print("I am the start from")
acc_number = '1'
if last_number is None:
print("I am the initiator")
return acc_number
if start_from != '' or start_from is not None:
while Account.objects.all().filter(account_number=start_from).exists():
acc_number_start = int(last_number.account_number) + 1
print("acc # from start from", str(acc_number_start))
return str(acc_number_start)
if last_number:
# last_number.refresh_from_db(fields="account_number")
# last_number.refresh_from_db()
while Account.objects.all().filter(account_number=last_number.account_number).exists():
print("BEFORE addition", last_number.account_number)
new_acc_number = int(last_number.account_number) + 1
print("acc # new number", str(new_acc_number))
return str(new_acc_number)
class Account(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
address = models.OneToOneField(Address, on_delete=models.SET_NULL, blank=True, null=True,
related_name="account_address")
account_number = models.CharField(max_length=20, default=account_number_increment, null=True, blank=True, unique=True)
# account_number = models.CharField(max_length=20, default='1def') # works with for loop in views.
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name
My Account_Settings Model
class AccountSettings(models.Model):
account_number_startfrom = models.CharField(max_length=100, default='1', blank=True, null=True)
def __str__(self):
return f'{self.job_number_startfrom}, {self.account_number_startfrom}, {self.invoice_number_startfrom}'
My views
def index(request):
if request.method == 'POST':
form1 = AccountForm(prefix='form1', data=request.POST)
form2 = AccountForm(prefix='form2', data=request.POST)
if form1.is_valid() and form2.is_valid():
form1.save()
form2.save()
print("FORMs SAVED")
return redirect(reverse('account:home'))
else:
user1 = CustomUser.objects.create(username='userFirst')
acc1 = Account.objects.create(name='IamUser40000', user=user1)
print('this is the new 1 ----' + str(acc1.pk) + acc1.name + '--------------')
acc11 = Account.objects.get(pk=acc1.pk)
acc2 = Account.objects.create(name='IamUser3000', user=user1)
print('this is the new 2 ----' + str(acc2.pk) + acc2.name +'--------------')
acc22 = Account.objects.get(pk=acc2.pk)
form1 = AccountForm(prefix='form1', instance=acc11)
form2 = AccountForm(prefix='form2', instance=acc22)
# for loop for non default callback
# num = 3
# for i in range(15):
# name = "IAMUSER"+str(i)
# account_number = str(num)
# Account.objects.create(name=name, account_number=account_number, user=user1)
# num = num + 1
# for loop for default with call back
for i in range(15):
name = "IAMUSER" + str(i)
# Account.objects.create(name=name, account_number=account_number_increment(), user=user1)
Account.objects.create(name=name, user=user1)
context = {
'form1': form1,
'form2': form2,
}
return render(request, 'accounts/index.html', context)
The error:
django.db.utils.IntegrityError: duplicate key value violates unique
constraint "account_account_account_number_a5d74cff_uniq" DETAIL: Key
(account_number)=(10) already exists.

Django: BooleanField return 'on' instead of true?

I have a BooleanField (ran_bug) in my Randomisation models that is displayed as a checkbox.
Click on the checkbox sould show 2 other fields that are not mandatory (ran_dem_nom and ran_dem_dat).
My problem is that, when I 'check' the checkbox, it return 'on' instead of true.
And I got an error when I try to registered data:
django.core.exceptions.ValidationError: ["'on' value must be either True, False, or None."]
models.py
class Randomisation(models.Model):
ran_ide = models.AutoField(primary_key=True)
pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country
ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True)
ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True)
bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True)
ran_act = models.IntegerField("Activated line", null=True, blank=True)
pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True)
ran_nai = models.IntegerField("Patient birthdate (year)", blank=True)
ran_sex = models.IntegerField("Sex", null=True, blank=True)
ran_st1 = models.IntegerField("Stratification variable 1", blank=True)
ran_st2 = models.IntegerField("Stratification variable 2", blank=True)
ran_bug = models.BooleanField("Use of alternative randomization procedure?", null=True, blank=True)
ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True) # hide at pageload
ran_dem_dat = models.DateField("Date of demand", null=True, blank=True) # hide at pageload
ran_log = models.CharField("User", max_length=12, null=True, blank=True)
ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True)
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.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["pay_ide"] = forms.IntegerField(label = "Pays", initial=2, widget=forms.HiddenInput())
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)
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'
})
JS
$(function(){
$("#div_id_ran_dem_nom").hide();
$("#div_id_ran_dem_dat").hide();
});
// affichage des champs en fonction de la valeur sélectionnée dans la liste
$("#div_id_ran_bug").on("change", function(event){
console.log($("#id_ran_bug").val())
if ($("#id_ran_bug").is(":checked")){
$("#div_id_ran_dem_nom").show();
$("#div_id_ran_dem_dat").show();
}
else {
$("#div_id_ran_dem_nom").hide();
$("#div_id_ran_dem_dat").hide();
}
});
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.data.get('pat')
randomisation.ran_nai = form.data.get('ran_nai')
randomisation.ran_sex = form.data.get('ran_sex')
randomisation.ran_bug = form.data.get('ran_bug')
randomisation.ran_dem_nom = form.data.get('ran_dem_nom')
randomisation.ran_dem_dat = form.data.get('ran_dem_dat')
print('ran_bug',form.data.get('ran_bug'))
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})
OK, i resolve my problem: form.cleaned_data['ran_bug'] instead of form.data.get('ran_bug')

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

How to update a model query

i'm developing a web app that will guide the student what to choose on his next year , if the general average > 12 and specialite ==Si he can choose Si else he is obliged to choose ISIL
i want to update the specialite into ISIL
PS : im new at django
views.py :
def resultats(request,id=None):
etudiant = MyUser.objects.all
etud_si = MyUser.objects.all().filter(specialite='SI')
etud_isil = MyUser.objects.all().filter(specialite='ISIL')
moy = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__gt=11.99,specialite='SI')
moy1 = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__lt=11.99,specialite='SI')
if moy1 :
moy1.specialite = 'ISIL'
moy1.save()
if id:
pr = get_object_or_404(MyUser,id=id)
else:
pr = request.user
context = {
'etudiant':etudiant,
'profile':pr,
'etud_si':moy,
'etud_isil':moy1
}
return render(request,'resultats.html',context)
models.py :
class MyUser(AbstractBaseUser,PermissionsMixin):
SI = 'SI'
ISIL = 'ISIL'
SPEC_CHOICES = [
(SI,'SI - System Informatique'),
(ISIL,'ISIL - Ingenieur system informatique et logiciels')
]
username = models.CharField(
max_length=300,
validators = [
RegexValidator(regex = USERNAME_REGEX,
message = 'Nom d\'utilisateur doit etre Alphanumeric',
code = 'nom d\'utilisateur invalid'
)],
unique = True
)
email = models.EmailField(unique = True)
nom = models.CharField(default=' ',max_length=300)
prenom = models.CharField(default=' ',max_length=300)
moyenne_s1 =models.DecimalField(default=00.00,max_digits=4,decimal_places=2)
moyenne_s2 = models.DecimalField(default=00.00,max_digits=4,decimal_places=2)
specialite = models.CharField(max_length=300,choices=SPEC_CHOICES,default=SI)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','moyenne_s1','moyenne_s2']
def get_update(self):
return reverse("edit", kwargs={"id": self.id})
#property
def moyenne_gen(self):
return (self.moyenne_s1+self.moyenne_s2)/2
I Solved it :
def resultats(request,id=None):
etudiant = MyUser.objects.all
moy = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__gt=11.99,specialite='SI')
moy1 = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__lt=11.99)
if moy1 :
moy1.specialite = 'ISIL'
moy1.update(specialite='ISIL')
if id:
pr = get_object_or_404(MyUser,id=id)
else:
pr = request.user
context = {
'etudiant':etudiant,
'profile':pr,
'etud_si':moy,
'etud_isil':moy1
}
return render(request,'resultats.html',context)

setting form field values django

I want to set the form value..i am not displaying it in form but want to set the value of field in my view?
This my modelform:
class payment_detail(models.Model):
status = (
('Paid','Paid'),
('Pending','Pending'),
)
id = models.AutoField(primary_key=True)
#ref_id = models.CharField(max_length=32, default=_createId)
#user = models.ForeignKey(User, editable = False)
payment_type= models.ForeignKey(Payment_types,to_field = 'payment_types', null=True, blank=True)
job_post_id= models.ForeignKey(jobpost,to_field = 'job_id', null=True, blank=True)
price= models.ForeignKey(package,to_field = 'amount', null=True, blank=True)
created_date = models.DateField(("date"), default=datetime.date.today)
payment_status = models.CharField(max_length=255, choices=status,default='Pending')
transaction_id = models.CharField(max_length=255, null=True, blank=True)
payment_date = models.DateField(null=True, blank=True)
email = models.CharField(max_length=255, null=True)
def __unicode__(self):
#return self.user
return unicode(self.id)
#return self.ref_id
return unicode(self.payment_type)
return unicode(self.job_post_id)
return unicode(self.price)
return unicode(self.created_date)
return unicode(self.payment_status)
return unicode(self.payment_date)
return unicode(self.transaction_id)
return unicode(self.email)
admin.site.register(payment_detail)
my View:
def payment(request):
if "pk" in request.session:
pk = request.session["pk"]
Country = request.session["country"]
price = package.objects.filter(item_type__exact='Job' ,country__country_name__exact=Country, number_of_items__exact='1')
if request.method == 'POST':
entity = payment_detail()
form = jobpostForm_detail(request.POST, instance=entity)
if form.is_valid():
#form.fields["transaction_id"] = 100
form.save()
#message = EmailMessage('portal/pay_email.html', 'Madeeha ', to=[form.cleaned_data['email']])
#message.send()
return HttpResponseRedirect('/portal/pay/mail/')
else:
form = jobpostForm_detail(initial={'transaction_id': "US"})
c = {}
c.update(csrf(request))
return render_to_response('portal/display.html',{
'form':form,'price':price
},context_instance=RequestContext(request))
like i want to set the value of job_location and don't want to display it in form..
forms.py
//this is how you hide the field
class jobpostForm(ModelForm):
def __init__(self, *args, **kwargs):
super(jobpostForm, self).__init__(*args, **kwargs)
self.fields['job_location'].widget = forms.HiddenInput()
class Meta:
model = jobpost
views.py
.........
if request.method == 'POST':
entity = payment_detail(transaction_id="US") #change
form = jobpostForm_detail(request.POST, instance=entity)
if form.is_valid():
#form.fields["transaction_id"] = 100
form.save()
#message = EmailMessage('portal/pay_email.html', 'Madeeha ', to=[form.cleaned_data['email']])
#message.send()
return HttpResponseRedirect('/portal/pay/mail/')
else:
form = jobpostForm_detail()
..................