Django Model default call back not adding beyond 10 - django

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.

Related

django form commit=false after how to save many to many field data

Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.

Django-Admin Change form load quite slow while using one to one mapping field

In my case change form load very slow In Admin interface because a one_to_one field "disk" in SeverHasDisk Model in models.py. There is a disk field in ServerHasDiskInLine in admin.py. It works fine when I exclude "Disk" field from ServerHasDiskInLine in admin.py.
Is there a way to increase the performance by using a form class for ServerHasDiskInLine(admin.TabularInline)
or something else?
Models.py
#Models.py
class Server(models.Model):
hostname = models.CharField(max_length=64, unique=True, db_index=True)
description = models.TextField(max_length=255, blank=True, null=True)
note = models.TextField(max_length=255, blank=True, null=True)
numberOfCpu = models.IntegerField(default=1) # vCPU or HThread core
cpuClockRate = models.CharField(max_length=255) # Mhz
virtualization = models.CharField(max_length=255, blank=True, null=True)
ram = models.FloatField() # Go
vnc = models.IntegerField(blank=True, null=True, unique=True)
monitored = models.BooleanField(default=True)
dns = models.CharField(max_length = 255, blank=True, verbose_name= "DNS")
ansible = models.CharField(max_length = 255, blank=True, verbose_name= "Ansible")
# --------------Relations -----------------
# backup = models.ForeignKey('self', name='server_backup', related_name='backup', blank=True, null=True)
hypervisor = models.ForeignKey('self', name='server_hypervisor', related_name='hypervisor', blank=True, null=True)
operatingSystem = models.ForeignKey(OperatingSystem)
module = models.ForeignKey(Module, blank=True, null=True)
project = models.ForeignKey(Project, blank=True, null=True)
customer = models.ForeignKey(Customer, blank=True, null=True)
environment = models.ForeignKey(Environment, blank=True, null=True)
site = models.ForeignKey(Site, blank=True, null=True)
status = models.ForeignKey(ServerStatus, blank=True, null=True )
class Meta:
ordering = ('hostname',)
unique_together = ('hostname', 'site',)
class VolumeGroup(models.Model):
name = models.CharField(max_length=64, unique=True, db_index=True)
size = models.IntegerField() # Go
class Meta:
ordering = ('name',)
def __unicode__(self):
return "%s (%s Go)" % (self.name, self.size)
class LogicalVolume(models.Model):
# ------------------ Fields ---------------
name = models.CharField(max_length=64, unique=True, db_index=True)
size = models.IntegerField() # Go
note = models.TextField(max_length=255, blank=True, null=True)
# --------------Relations -----------------
volumeGroup = models.ForeignKey(VolumeGroup)
class Meta:
ordering = ('name',)
unique_together = ('volumeGroup', 'name')
def __unicode__(self):
return "%s (%s Go) on VG <%s>" % (self.name, self.size, self.volumeGroup.name)
class ServerHasDisk(models.Model):
# ------------------ Fields ---------------
mountPoint = models.CharField(max_length=255)
# --------------Relations -----------------
server = models.ForeignKey(Server, related_name='serverDisks')
disk = models.OneToOneField(LogicalVolume)
class Meta:
ordering = ('mountPoint',)
unique_together = ('server', 'disk')
def __unicode__(self):
return "Srv [%s]: %s ==> <%s> on VG <%s>" % (self.server.hostname, self.mountPoint, self.disk.name, self.disk.volumeGroup.name)
Admin.py
class ServerHasDiskInline(admin.TabularInline):
model = ServerHasDisk
extra = 0
# formset = MyFormSet
classes = ('grp-collapse grp-open',)
#exclude = ['disk']
class ServerHasRoleInline(admin.TabularInline):
model = ServerHasRole
extra = 0
fk_name = 'server'
classes = ('grp-collapse grp-open',)
class IpInline(admin.TabularInline):
model = IP
extra = 0
classes = ('grp-collapse grp-open',)
class BkSrvInline(admin.TabularInline):
model = ServerIsBackupedOn
fk_name = 'server'
extra = 0
classes = ('grp-collapse grp-open',)
class ServerAdmin(admin.ModelAdmin):
change_list_template = "admin/change_list_filter_sidebar.html"
list_display = ('hostname', 'get_project_name', 'get_module_name', 'get_environment_name', 'get_customer_name', 'get_os_name', 'get_site_name', 'get_ip_name', 'get_bk_hostname', 'get_role_name', 'description','note','get_dns','get_status','get_ansible')
list_filter = ('project__name', 'module__name', 'environment__name', 'customer__name', 'site__name', 'operatingSystem__name', 'serverRoles__role__name', 'serverIps__address')
list_per_page = 25
search_fields = ('hostname', 'project__name', 'module__name', 'environment__name', 'serverIps__address', 'serverRoles__role__name', 'note')
inlines = (ServerHasDiskInline,ServerHasVolumeGroupInline,ServerHasRoleInline, IpInline, BkSrvInline)
#related_search_fields={
#'disk': ( 'name', ),
#}
def get_project_name(self, o):
if o.project is None:
return "N/A"
else:
return o.project.name
get_project_name.admin_order_field = 'project'
get_project_name.short_description = 'Project'
def get_dns(self, o):
if o.dns is None:
return "N/A"
else:
return o.dns
get_dns.admin_order_field = 'dns'
get_dns.short_description = 'DNS'
def get_ansible(self, o):
if o.ansible is None:
return "N/A"
else:
return o.ansible
get_ansible.admin_order_field = 'ansible'
get_ansible.short_description = 'Ansible'
def get_module_name(self, o):
if o.module is None:
return "N/A"
else:
return o.module.name
get_module_name.admin_order_field = 'module'
get_module_name.short_description = 'Module'
def get_customer_name(self, o):
if o.customer is None:
return "N/A"
else:
return o.customer.name
get_customer_name.admin_order_field = 'customer'
get_customer_name.short_description = 'Customer'
def get_os_name(self, o):
if o.operatingSystem is None:
return "N/A"
else:
return o.operatingSystem.name
get_os_name.admin_order_field = 'operatingsystem'
get_os_name.short_description = 'OS'
def get_environment_name(self, o):
if o.environment is None:
return "N/A"
else:
return o.environment.name
get_environment_name.admin_order_field = 'environment'
get_environment_name.short_description = 'Environment'
def get_status(self, o):
if o.status is None:
return "N/A"
else:
return o.status.status
get_status.admin_order_field = 'status'
get_status.short_description = 'Status'
def get_site_name(self, o):
if o.site is None:
return "N/A"
else:
return o.site.name
get_site_name.admin_order_field = 'site'
get_site_name.short_description = 'Site'
def get_ip_name(self, o):
return ", ".join([
'%s' % ('../ip', k.id, k.address)
for k in o.serverIps.all()
])
# return ", ".join([k.address for k in o.serverIps.all()])
get_ip_name.admin_order_field = 'serverIps'
get_ip_name.short_description = 'IP'
get_ip_name.allow_tags = True
def get_bk_hostname(self, o):
return ", ".join([
'%s' % ('../server', k.backupServer.id, k.backupServer.hostname)
for k in o.serverBackuped.all()
])
# return '%s' % ('../project', o.project.id, o.project.name)
get_bk_hostname.admin_order_field = 'serverBackuped'
get_bk_hostname.short_description = 'Bk Srv'
get_bk_hostname.allow_tags = True
def get_role_name(self, o):
return ", ".join([k.role.name for k in o.serverRoles.all()])
get_role_name.admin_order_field = 'serverRoles'
get_role_name.short_description = 'Role'
Here is quick solution.
I have just added an attribute to ServerHasDiskInLine class in Admin.py
raw_id_fields = ("disk",) so New class is
class ServerHasDiskInline(admin.TabularInline):
model = ServerHasDisk
raw_id_fields = ("disk",)
extra = 0
classes = ('grp-collapse grp-open',)
#exclude = ['disk']

django - can't work out the views to assign a new item

I've this in my views and trying to get new truck_name assigned to a new Product.
When user with truck_name as None and no instance of Product, the script goes to
try:
truck_name = Product.objects.get(user=request.user)
and skips to the except:
#login_required
def profile_edit(request):
owner = TruckOwnerStatus.objects.get(user=request.user)
truck_form = RegisterTruckForm()
i = owner.id
print i
try:
truck_name = Product.objects.get(user=request.user)
if request.method == 'GET':
if truck_name is not None:
truck_form = RegisterTruckForm(instance=truck_name)
else:
truck_form = RegisterTruckForm()
context = {
'truck_form': truck_form,
'truck_name': truck_name,
}
return render(request, 'accounts/profile_edit.html', context)
elif request.method == 'POST':
if truck_name is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_name)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
#once clicked save
if truck_form.is_valid():
truck_name = truck_form.save(commit=False)
truck_name.product = Product.objects.get(user=request.user)
truck_form.save_m2m()
truck_name.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
return render_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))
except:
print "hii"
if request.method == 'POST':
truck_form = RegisterTruckForm(request.POST, request.FILES)
truck_owner = request.user
if truck_owner is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES, instance=truck_owner)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
if truck_form.is_valid():
truck_owner = truck_form.save(commit=False)
truck_owner.profile = Product.objects.create(user=request.user)
truck_form.save_m2m()
truck_owner.profile.save()
messages.success(request, "Successfully Saved!!")
return HttpResponseRedirect('/')
else:
messages.error(request, "Please recheck")
# return render(request, context, 'accounts/profile_edit.html',)
context = {"truck_form": truck_form}
return render(request, 'accounts/profile_edit.html', context)
It does the job of saving the form but does not assign the truck_name from the form to the request user. Hence nothing gets assigned to the new Product
I tried putting
truck_name = Product.objects.get(user=request.user) in the except but it returns an error because there is no instance of Product for this user and therefore no truck_name.
I can see the entry in admin but can't view it because there is no truck_name. But if I were to run the entire profile_edit for the same user and fill the the form, the truck_name gets assigned.
How do I get it assigned?
Below is my Product model.
class Product(models.Model):
user = models.OneToOneField(User)
owner_name = models.CharField(max_length=120)
email = models.EmailField(max_length=120)
contact_number = models.IntegerField(max_length=15, null=True, blank=True)
foodtruck_name = models.CharField(max_length=120)
logo = models.ImageField(upload_to='foodtruck/logo/', null=True, blank=True)
slogan = models.TextField(max_length=250, null=True, blank=True)
about_us = models.TextField(max_length=500, null=True, blank=True)
operating_state = models.CharField(max_length=120, choices=STATE_CHOICES)
bsb = models.IntegerField(max_length=15, null=True, blank=True)
account_number = models.IntegerField(max_length=15, null=True, blank=True)
availability_link = models.CharField(max_length=300, null=True, blank=True)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
update_defaults = models.BooleanField(default=False)
def __unicode__(self):
return self.foodtruck_name
class Meta:
unique_together = ('foodtruck_name', 'slug')
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse("single_product", kwargs={"slug": self.slug})

Can create new model instance but can not update an existing one oin Django

For some reason i can create an new instance of classified model but cannot update an existing one neither via my view or through admin panel in Django. I am using postgresql and from the logs, it seems like queries are not hitting the database at all. I removed and resetted the app, even drop the tables but didn't help.
class classified(models.Model):
slug = models.SlugField(unique=True,blank=True, null=True)
submitted_by = models.ForeignKey(User, blank=True, null=True)
title = models.CharField(max_length=120, blank=True, null=True)
point = models.PointField(srid=settings.SRID, blank=True, null=True)
address = models.CharField(max_length=120, blank=True, null=True)
city = models.CharField(max_length=60, blank=True, null=True)
state = models.CharField(max_length=60, blank=True, null=True)
zipcode = models.CharField(max_length=5, blank=True, null=True)
description = models.TextField(max_length=500,blank=True, null=True)
objects = models.GeoManager()
tags = TaggableManager(blank=True)
submission_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
price = models.CharField(max_length=20, blank=True, null=True)
def __unicode__(self):
#return "%s %s %s"%(self.title, self.point.x, self.point.y)
return "%s"%(self.title)
#models.permalink
def get_absolute_url(self):
return ('listing_detail', (),
{
'slug' :self.slug,
})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
if not self.point:
location = "%s+%s+%s+%s"%(self.address, self.city, self.state, self.zipcode)
cord = get_lat_long(location)
x,y = cord.split(",")
x = float(x)
y = float(y)
self.point = Point(x,y)
self.point2 = Point(x,y)
super(classified, self).save(*args, **kwargs)
ClassifiedImage model:
class ClassifiedImage(models.Model):
classified = models.ForeignKey(classified, related_name="images", null=True, blank=True)
image = models.ImageField(upload_to='classifieds/%Y/%m/%d', default='static/img/no-thumb.jpg', null=True, blank=True)
Classified View:
def add_classified(request):
userprofile = User.objects.get(pk=request.user.id)
if request.method == 'POST':
form = classifiedForm(request.POST, request.FILES)
if form.is_valid():
classifiedad = form.save(commit=False)
image_formset = ImageFormSet(request.POST, request.FILES, instance=classifiedad)
classifiedad.submitted_by = request.user
classifiedad.save()
image_formset.save()
slug = classifiedad.slug
redirect_to =reverse('classified-detail', kwargs={'slug':slug})
return HttpResponseRedirect(redirect_to)
else:
form = classifiedForm()
image_formset = ImageFormSet()
return render_to_response('shclassified/add_classified.html',{'form':form, 'image_formset':image_formset},context_instance = RequestContext(request))
Classified Update view:
def ClassifiedUpdate(request, slug):
classifiedins = classified.objects.get(slug=slug)
if request.method == 'POST':
form = classifiedForm(request.POST, request.FILES)
if form.is_valid():
#classifiedad = form.save(commit=False)
image_formset = ImageFormSet(request.POST, request.FILES, prefix="images", instance=classifiedins)
#classifiedad.submitted_by = request.user
#classifiedad.save()
#form().save()
image_formset.save()
#slug = classifiedad.slug
return HttpResponseRedirect(".")
else:
form = classifiedForm(instance=classifiedins)
image_formset = ImageFormSet(instance=classifiedins, prefix="images")
return render_to_response('shclassified/add_classified.html',{'form':form, 'image_formset':image_formset},context_instance = RequestContext(request))
You're overriding the save method incorrectly by the looks of things:
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
if not self.point:
location = "%s+%s+%s+%s"%(self.address, self.city, self.state, self.zipcode)
cord = get_lat_long(location)
x,y = cord.split(",")
x = float(x)
y = float(y)
self.point = Point(x,y)
self.point2 = Point(x,y)
super(classified, self).save(*args, **kwargs) ## wrong indentation!
Your super() call should be aligned with the first level of indentation. As you have it, super().save is only called if there is no self.point.

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()
..................