Update form input with django form value - python

I am trying to pass legacy db entries to django form.
I created the model by using django inspectdb method.
Similar to:
class Form(models.Model):
date_entered = models.DateField(blank=True, null=True)
date_needed = models.DateField(blank=True, null=True)
client = models.CharField(max_length=50, blank=True, null=True)
project_no = models.CharField(max_length=50, blank=True, null=True)
map_no = models.CharField(max_length=10, blank=True, null=True)
contact = models.CharField(max_length=50, blank=True, null=True)
I have create the corresponding view in views.py.
def post_edit(request, pk):
post = get_object_or_404(Form, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
In my post_edit.html.
<input type="text" class="form-control" name="client" value= '{{ form.client.value }}' required/>
<input type="text" name="projectno" class="form-control" value= '{{ form.project_no.value }}' required/>
..
<input type="text" name="jobcontact" class="form-control" value='{{ form.contact.value }}' required/>
Client and project_no work (produce values on the form) while contact does not. I have verified the name in model and also the existance of a value for this in the db table.
Should I pass something else for these input values. I am new to django. Help please.
EDIT: Adding class PostForm(). As identified in the accepted answer only 2 fields had been added to class PostForm(). After adding the remainig classes the form populated the values.
class PostForm(forms.ModelForm):
class Meta:
model = Form
fields = ('project_no', 'client',)

Related

How to upload payment picture by orders, 'QuerySet' object has no attribute '_meta'

I can't filter to upload pictures.
I want to upload pictures by :
orders= Order.objects.filter(id=orid, id_profil=id_profil)
get error :
'QuerySet' object has no attribute '_meta'
view.py
def Detail(request, orid=None):
data = cartData(request)
cartItems = data['cartItems']
id_profil = request.user.profile
orders = Order.objects.filter(id=orid, id_profil=id_profil)
OrderItems = OrderItem.objects.filter(order=orid)
pengirimans = Pengiriman.objects.filter(order=orid)
if request.method == "POST":
form = Uplaodpic(request.POST ,request.FILES ,instance=orders)
if form.is_valid():
form.save()
else:
form=Uplaodpic(instance=orders)
context = {'orders':orders, 'OrderItems':OrderItems, 'pengirimans':pengirimans, 'cartItems':cartItems, 'form':form}
return render(request, 'store/detail.html' ,context)
forms.py
from django.forms import ModelForm
from .models import Order, Profile
class Uplaodpic(ModelForm):
class Meta:
model=Order
fields=["id","bukti"]
detial.html
<td colspan="2">
<img src="{{ order.buktiURL }}" alt="image" class="img-thumbnail" style="max-height:100px">
</td>
<td colspan="2">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="Submit" id="submit" name="submit">
</form>
</td>
</tr>
modes.py
class Order(models.Model):
id_profil = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(upload_to='bukti/',default="person-circle.svg",null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
instance parameter here should be a single object, not QuerySet. Judging by id name, you should be using get instead of filter to fetch a single object or fail. So, your code could look like this (after very basic formatting to become readable):
from django.http import HttpResponseNotFound
def Detail(request, orid=None):
data = cartData(request)
cartItems = data['cartItems']
id_profil = request.user.profile
OrderItems = OrderItem.objects.filter(order=orid)
pengirimans = Pengiriman.objects.filter(order=orid)
try:
# Note the singular
order = Order.objects.get(id=orid, id_profil=id_profil)
except Order.DoesNotExist: # Not owned bu user or does not exist
return HttpResponseNotFound()
if request.method == "POST":
form = Uplaodpic(request.POST, request.FILES, instance=order)
if form.is_valid():
form.save()
else:
form = Uplaodpic(instance=order)
context = {
'order': order, # Note the singular, you're using "order" in template anyway
'OrderItems': OrderItems,
'pengirimans': pengirimans,
'cartItems': cartItems,
'form': form
}
return render(request, 'store/detail.html', context)
(note that it would be better to spell Upload, not Uplaod...)

How to compare data from two models in Modelform Django

I'm creating an ebay like auction site where users can bid on an item they like and if the bid is higher than the last bid, the bid amount displayed would update to the newest bid.
I want to run validation on the modelform to compare the first amount (that the person that created the listing) inputted with the last bid (that the new user inputted).
The problem is that they are in two different models and I'm not sure how to validate both without an error
FORMS.PY
class BidForm(forms.ModelForm):
class Meta:
model = Bids
fields = ['new_bid']
labels = {
'new_bid': ('Bid'),
}
def clean_new_bid(self):
new_bid = self.cleaned_data['new_bid']
current_bid = self.cleaned_data['current_bid']
if new_bid <= current_bid:
error = ValidationError("New bid must be greater than the previous bid")
self.add_error('new_bid', error)
return new_bid
MODELS.PY
class Auction(models.Model):
title = models.CharField(max_length=25)
description = models.TextField()
current_bid = models.IntegerField(null=False, blank=False)
image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE)
is_active = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']
class Bids(models.Model):
auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding', null=True)
user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding')
new_bid = models.IntegerField()
done_at = models.DateTimeField(auto_now_add=True)
VIEWS.PY
#login_required
def make_bid(request, listing_id):
auction = Auction.objects.get(pk=listing_id)
user = request.user
if request.method == 'POST':
bid_form = BidForm(request.POST)
if bid_form.is_valid():
new_bid = request.POST['new_bid']
current_price = Bids.objects.create(
listing_id = listing_id,
user = user,
new_bid = new_bid
)
messages.success(request, 'Successfully added your bid')
return HttpResponseRedirect(reverse("listing_detail", args=(listing_id,)))
else:
bid_form = BidForm(request.POST)
return render(request, 'auctions/details.html', {"bid_form": bid_form})
return render(request, 'auctions/details.html', bid_form = BidForm())
DETAILS.HTML
<p>{{ detail.description }}</p>
<hr>
<p>Current price: ${{detail.current_price}}</p>
<form action="{% url 'make_bid' detail.id %}" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.errors }}
{{ bid_form }}
<input type="submit" class="btn btn-primary btn-block mt-3" value="Place bid">
</form>
I'm having this error
KeyError at /make_bid/2
'current_bid'
Request Method:
POST
Request URL:
http://127.0.0.1:8000/make_bid/2
I'm sure its because I'm trying to compare two different models, but don't know a better way to do this. Could you please direct me or is there a better way to run this bid validation process?

Form is not saving in database when submitted

I am working on a project on Django, where user can input values on form and submit using POST request. When form is submitted, datas are not saved in database. How do I implement save data when form is submitted.
Models:
class DataInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
beneficiary_name = models.CharField(max_length=250, blank=True)
beneficiary_bank_name = models.CharField(max_length=250, blank=True)
beneficiary_account_no = models.CharField(max_length=250, blank=True)
beneficiary_iban = models.CharField(max_length=250, blank=True)
beneficiary_routing_no = models.CharField(max_length=250, blank=True)
amount = models.IntegerField(blank=True)
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'DataInfo'
verbose_name_plural = 'DataInfo'
ordering = ['-date']
'''Method to filter database results'''
def __str__(self):
return self.user.username
Views:
#login_required
def TransferView(request):
form = DataForm(request.POST)
if request.method == "POST":
if form.is_valid():
pp = form.save(commit=False)
pp.user = request.user
pp.save()
return redirect('site:transfer_cot')
else:
form = DataForm()
context = {
'form':form
}
return render(request, 'transfer.html', context)
Forms:
class DataForm(forms.ModelForm):
class Meta:
model = DataInfo
fields = ('beneficiary_name', 'beneficiary_bank_name', 'beneficiary_account_no', 'beneficiary_iban', 'beneficiary_routing_no', 'amount')
Template:
<form method="POST" action="{% url 'site:transfer_cot' %}">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-secondary">Submit</button>
</form>

Additional help text to form in Django

When I create or edit model CV, I need to input some data in birth_date field. It's working, but I want to add some additional text to define some date format like (yyyy-mm-dd). I'm using cripsy forms for better look of forms. How can I add this help text ?
my code:
template.html
{% block profile %}
<div class="jumbotron">
<h2>Edit your basic informations</h2>
<hr>
<form method="POST" class="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
{% endblock %}
models.py
class Cv(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=25, null = True)
surname = models.CharField(max_length=25, null = True)
city = models.CharField(max_length=100, blank=True)
birth_date = models.DateField(blank=True, null=True)
email = models.EmailField(max_length=50, null=True)
main_programming_language = models.CharField(max_length=15, null = True)
specialization = models.CharField(max_length=30, blank=True, null=True)
interests = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
#thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
#property
def age(self):
return int((datetime.datetime.now().date() - self.birth_date).days / 365.25 )
def zapisz(self):
self.save()
def __str__(self):
return self.surname.encode('utf-8')
forms.py
class CvForm(forms.ModelForm):
class Meta:
model = Cv
fields = ('name', 'surname', 'city', 'birth_date', 'email', 'main_programming_language', 'specialization', 'interests', 'summary',)
views.py
#login_required
def new_cv(request):
if request.method == "POST":
form = CvForm(request.POST, request.FILES)
if form.is_valid():
cv = form.save(commit=False)
cv.author = request.user
cv.save()
return redirect('proj.views.cv_detail', pk=cv.pk)
else:
form = CvForm()
return render(request, 'new_cv.html', {'form': form})
Can add help_text to your model fields:
birth_date = models.DateField(blank=True, null=True, help_text="format (yyyy-mm-dd)")
see more Django Model and Form docs.
You can also use external library JQuery Tooltip too.

ImageField() not saving images in ModelForm - Django/Python

When I try to upload a picture from my form, everything processes, but the image is not being saved.
Does anyone know why this is happening?
Thanks ahead of time!
models.py:
class Photo(models.Model):
user = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.user)
views.py:
def photo_upload_view(request, username):
u = MyUser.objects.get(username=username)
if request.method == 'POST':
form = PhotoUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, "Thank you! You have successfully posted your picture!")
return HttpResponseRedirect('/')
else:
form = PhotoUploadForm()
submit_btn = "Upload Post"
context = {
"form": form,
"submit_btn": submit_btn
}
return render(request, "photos/photo_upload.html", context)
forms.py:
class PhotoUploadForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('user', 'category', 'title', 'description', 'image')
.html:
<form method='POST' action='{{ action_url }}'>{% csrf_token %}
{{ form|crispy }}
<input class='btn btn-default {{ submit_btn_class }}' type='submit' value='{{ submit_btn }}'/>
</form>
You should add the enctype=multipart/form-data attribute to the <form> tag:
<form method='POST' action='{{ action_url }}' enctype='multipart/form-data'>
except for adding enctype=multipart/form-data, another possible reason that your image is not saving in modelform can be adding request.FILES in your POST condition:
if request.method == 'POST':
form = forms.ProjectCreateForm(request.POST, instance=project)
should be:
if request.method == 'POST':
form = forms.ProjectCreateForm(request.POST, request.FILES, instance=project)
data.profile_pic = request.FILES['profile_pic']
use request.FILES

Categories