setting form field values django - 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()
..................

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 - 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})

Forms in Django. How to initialize model field from form?

In models.py:
class Client(AbstractBaseUser):
username = models.CharField(max_length=32, unique=True)
email = models.EmailField('email address', unique=True, db_index=True)
avatar = models.ImageField('avatar', upload_to='avatars')
id = id(object)
class Order(models.Model):
class Meta():
db_table = 'order'
short_desc = models.CharField(max_length=30)
subject = models.ForeignKey(Subject, blank=True)
user_id = models.ForeignKey('Client', to_field='id', related_name='client_id', default='0', blank=True)
performer_id = models.ForeignKey('Client', to_field='id', related_name='performer_id', default='0', blank=True)
worktype = models.ForeignKey(Type, blank=True)
level = models.IntegerField(default=0, blank=True)
readiness = models.BooleanField(default=False, blank=True)
description = models.TextField(max_length=2000, blank=True)
file = models.FileField(upload_to='orderfiles', blank=True)
#maxdate = models.DateField(blank=True)
addate = models.DateField(auto_now=True, blank=True)
price = models.IntegerField(max_length=10, blank=True)
responses = models.IntegerField(blank=True)
In forms.py:
class AddOrderForm(forms.ModelForm):
short_desc = forms.CharField(widget=forms.TextInput,label="Краткое описание(послужит именем)")
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), label="Предмет")
worktype = forms.ModelChoiceField(queryset=Type.objects.all(), label="Тип")
level = forms.IntegerField(widget=forms.TextInput,label="Уровень сложности (от 1 до 5)")
description = forms.CharField(widget=forms.TextInput,label="Полное описание")
#maxdate = forms.DateField(widget=forms.TextInput,label="maxdate")
price = forms.IntegerField(widget=forms.TextInput,label="Ваша цена")
responses = forms.IntegerField(widget=forms.TextInput,label="Кол-во ответов на заказ")
class Meta:
model = Order
fields = ['short_desc', 'level', 'description', 'price', 'responses', 'subject', 'worktype']
In views.py:
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html', { 'form': form,'username' : auth1}, context_instance=RequestContext(request))
I need the field user_id in class Order to be initialized immediately after adding order(). Where should I do it and in which way? I need something like this logic: Client adds an Order through AddOrderForm and then user_id field of just added object of class Order has to be initialized with an object of class Client, whose id equals user_id in parameters of addorder() function.
You can do that using commit=False while saving the form. This is typical way of saving the object using model form which has fewer fields.
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
order = form.save(commit=false)
order.client_id = Client.objects.get(id=user_id)
order.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html',
{ 'form': form,'username' : auth1},
context_instance=RequestContext(request))
Disclaimer: Handle errors e.g. Client.objects.get() may fail. Use appropriate fields to search.

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.

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})