how can i edit multiple objects/row atonce in django html template - django

i facing an problem on my django project . i try to edit and update an objects . but it's showing an error which is name is MultipleObjectsReturned .
hear is my issue screenshots .
when i was clicked this update button ( user can update which he went ) . than showing next 2nd image
1st img
showing this error
2nd image
Views.py
def purchase_order_item_update(request,order_id):
purchase_item_list = Purchase_order_item.objects.filter(order_id=order_id)
# porder = Purchase_order_item.objects.get(order_id=order_id)
# this is the form for getting data from html
if request.method == 'POST':
for bt in Purchase_order_item.objects.filter(order_id=order_id):
pu_id = bt.puid # product Id
quantity = request.POST.get('asqty')
unit_price = request.POST.get('uprice') # itemid = pk type
total = int(quantity) * float(unit_price)
cv = Purchase_order_item.objects.get(puid=pu_id)
cv.quantity = quantity
cv.unit_price = unit_price
cv.total_price = total
cv.save()
return redirect('purchase_order_item',order_id= order_id)
return render(request,'back/purchase/assign_purchas_item.html',
{'purchase_item_list':purchase_item_list, })
Actually i went to edit and update this list of entries and update also if user making any typing mistake then he can update .
thank you

the error is pretty descriptive:
cv = Purchase_order_item.objects.get(puid=pu_id)
returns more than one object. When using 'get' the ORM layer expects only one result, which is not the case you have. You most likely duplicated the puid value while testing. It happens often. In order to fix that you need to delete the second object that has the same puid, and ideally find out how you ended with two on the same uid value.

Related

Flask pagination, query issue, why so many items?

I'm workin on a blog page and I'm trying to filter posts by tag, the problem is that I get several pages when only 1 or 2 posts match the query (I have per_page set to 6).
I have another filter by followed posts that works correctly, therefore I guess the problem is in the query object.
This is part of my code for the view index:
if current_user.is_authenticated:
show_followed = bool(request.cookies.get('show_followed', ''))
if show_followed:
query = current_user.followed_posts
elif show_tag:
tag = Tag.query.filter_by(tag_name=show_tag).first()
query = tag.post
else:
query = Post.query
page = request.args.get('page', 1, type=int)
pagination = query.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
return render_template("index.html", posts=posts, pagination = pagination, show_followed=show_followed, show_tag=show_tag)
when I try to replicate the issue in the console, I check that the query for a sample tag matches 3 posts, nevertheless pagination.total (total items) returns 23! What does the pagination object take as items??
I did this to test in the flask shell:
tagname = 'pruebatag'
tag = Tag.query.filter_by(tag_name=tagname).first()
query = tag.post
#here if y try query.all() I get 3 posts in return
pag_object = query.paginate(per_page = 6)
pag_object.total
>>> 23
pag_object.pages
>>> 4
pag_object.items #returns items for current page
>>> [<Post example>] #only one post returned for this page? why 4 pages?
I copy my definition of the tags table:
class Tag(db.Model):
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True)
tag_name = db.Column(db.String(40), unique=True)
def add_tag(self):
if not self.id:
db.session.add(self)
db.session.commit()
tag_join = db.Table('tag_join',
db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'))
)
And in the post model:
tags = db.relationship('Tag',
secondary=tag_join,
backref=db.backref('post', lazy='dynamic'),
lazy='dynamic')
Any help would be highly appreciated as I am wasting a lot of time on this issue
Just let mi know if you need more details.
Thanks!
Finally I found what happens, I realize that table tag_join is full of duplicates, that cause the issue.

How extract individual values from POST request in Django Model Form?

Would like to be able to access data in a post request directly as well as processing it in the normal way. First created form:
class TransactionForm(ModelForm):
class Meta:
model = Transaction
fields = ['dish', 'customer', 'grams', 'amount_payable']
('customer' is the pk of another model, Customer.)
Then process form:
#csrf_exempt
def create_transaction(request):
print(request.POST)
user_input = TransactionForm(request.POST)
print (user_input)
if user_input.is_valid():
user_input.save()
#customerobject = Customer.objects.get(pk= PK-TAKEN FROM POST)
#customerobject.account_balance -= (amount_payable TAKEN FROM POST)
#customerobject.save()
return HttpResponse('AOK~')
else:
return HttpResponse(user_input) #'ERROR: transaction not valid~')
Am struggling to correctly formulate the commented lines above. (The rest works fine.)
Would like to be able to extract the value 'customer' from the POST in order to find the customer. Then to extract the value 'amount_payable' from the POST in order to deduct it from the customer's balance.
Eventually stumbled upon the relevant command:
cust = user_input.cleaned_data.get('customer')
customerobject = Customer.objects.get(pk=cust.id)
customerobject.account_balance -= user_input.cleaned_data.get('amount_payable')
customerobject.save()
Low-level languages are easier for sieve-heads like me.

Django Forms - Relating Objects (Model Formsets?)

Say I have something like this:
class Product(models.Model)
name = models.CharField()
description models.TextField()
class Image(models.Model)
product = models.ForeignKey(Product, null=True, blank=True, related_name="images")
image = models.ImageField()
Suppose I'm in a form for creating a Product and in this form there is a section that allows you to upload images. These images are uploaded asynchronously. How can I have it so that:
On creation:
Product is created and images are related to it.
On editing:
Product is fetched, related Images are fetched. Product is edited, Images are edited.
Currently, I have a view that does both jobs of creating or editing Products. How can I accomplish the image related part of this product form? Model Formsets?
Edit:
#login_required
def create_or_edit_product(request, product_id=None):
# Redirect user if he has no account associated to him
try:
account = Account.objects.get(membership__user=request.user)
except:
login_url = reverse('login') + ('?next=%s') % request.path
return HttpResponseRedirect(login_url)
# Get product if product id passed
product_instance = None
if product_id is not None:
product_instance = get_object_or_404(product, id=product_id)
# Get related pictures if product exists. Get picture values (dictionary list, used for initial formset data) if pictures found.
pictures = product.pictures.all() if product_instance is not None else None
pictures_values = pictures.values() if pictures else []
PictureFormSet = formset_factory(PictureForm, formset=BasePictureFormSet, extra=0, can_delete=False, max_num=40)
if request.method == "POST":
product_form = productForm(request.POST, prefix='product', instance=product_instance)
picture_formset = PictureFormSet(request.POST, prefix='pictures', initial=pictures_values)
# If forms are valid
if product_form.is_valid() and picture_formset.is_valid():
try:
# Add account to product and save
product = product_form.save(commit=False)
if product_instance is None:
product.account = account
product.save()
# Remove picture-product relationships of current pictures
if pictures is not None:
pictures.update(product=None)
# Update each picture with the product and corresponding sort order. (The field 'id' is a picture object. The form converts the passed picture id to a picture object)
for index, form in enumerate(picture_formset):
picture = form.cleaned_data['id']
Picture.objects.filter(id=picture.id).update(product=product, sort_order=index)
except Exception, e:
# Rollback changes - something went wrong
transaction.rollback()
print "Transaction Rollback: %s" % e
else:
# Commit changes and redirect to product edit page
transaction.commit()
return HttpResponseRedirect('product_edit', product_id=product.id)
else:
product_form = productForm(prefix='product', instance=product_instance)
picture_formset = PictureFormSet(prefix='pictures')
# TODO: change add template to an add/edit one
return render_to_response('products/add.html', {
'product_form' : product_form,
'picture_formset' : picture_formset,
'pictures' : pictures,
},
context_instance=RequestContext(request))
I'm new to Python and Django but that is my somewhat working view. (I've only tried adding a new product so far)
The form that the user sees has thumbnails with hidden inputs containing each picture id. In the case that the form fails, I'd like to re display thumbnails along with the hidden inputs (which are already kept). To make that work, I'm guessing I'd have to query the picture ids, but the form is not valid so how would I go about doing that? (if that is even the right path to go about)
What do you think?
#Aamir Adnan is right that Model Formsets are an elegant way to deal with this.
Here's a full fledge example that is similar to what you need - http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/
As in the example, because the end user may need to add additional "images" (in your case) which are related to the product, you will need some javascript logic to handle the dynamic addition of forms so that the user can arbitrarily add and upload images on save.

Want to hide error message (View)

I'm matching the name in Album Model. And Its working just fine. But Some time It does not match. And It raise error message Album matching query does not exist. I want if no match is found. Then don't display any error message. Is it possible? Thanks
def movie_details(request,slug):
movies = get_object_or_404(Movie,slug=slug)
# calculating wikipedia directory structer for images
#image_name = movies.image
name = movies.title
album_name = Album.objects.get(name__exact=name)
album_id = album_name.id
song_list = Song.objects.filter(album=album_id)
#image_path = generateWikiImage(image_name)
#
return render_to_response('base_movies.html',locals(),
context_instance=RequestContext(request)
)
Error message
Album matching query does not exist
UPDATE:
def movie_details(request,slug):
movies = get_object_or_404(Movie,slug=slug)
# calculating wikipedia directory structer for images
#image_name = movies.image
name = movies.title
try:
album_name = Album.objects.get(name__exact=name)
album_id = album_name.id
song_list = Song.objects.filter(album=album_id)
except:
pass
Thanks F.C.
As suggested in the comment above, you need to catch the exception that's raised. In your case, it'd be:
try:
album_name = Album.objects.get(name__exact=name)
except Album.DoesNotExist:
pass
If you want to set album_name to some default value if you can't find it, replace pass with code to set it to your default value.
(This StackOverflow post also deals with a similar issue.)

Django select choices with optgroup fails to validate

I have a a form in Django with two inline forms. One of them is giving me grief.
My model is like so.
class BookingActivity(models.Model):
booking = models.ForeignKey('Booking')
program = models.ForeignKey(Program)
activity = models.ForeignKey(Activity, choices=programs_as_optgroups())
the activity ForeignKey choices are generated via this method:
def programs_as_optgroups():
activities = []
programs = []
for program in Program.objects.all():
new_program = []
new_activities = []
for activity in Activity.objects.filter(program=program):
new_activities.append([activity.id, activity.name])
new_program = [program.name, new_activities]
activities.append(new_program)
return activities
I'm trying to add <optgroup> tags to my ForeignKey select which is working. But when I submit the form I get an error: Cannot assign "u'3'": "BookingActivity.activity" must be a "Activity" instance.
This makes some sense - sort of. But if I check the request data sent from the form post. With choices either setup or not I get the same values, i.e.
activity = models.ForeignKey(Activity, choices=programs_as_optgroups())
and
activity = models.ForeignKey(Activity)
both return the a u'3' from the form. But I can't figure out why I get an error only when I'm using the optgroups.
I'm guessing you're trying
http://dealingit.wordpress.com/2009/10/26/django-tip-showing-optgroup-in-a-modelform/
in the blog
sub_categories.append([sub_category.id, sub_category.name])
you have
new_activities.append([activity.id, activity])
I think you're assuming you will get an object when it actually is a string you're getting back.