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.)
Related
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.
I wanted to filter on the _set of an item, however in the problem below while i was doing this, it wasn't on the field i thought it was. I needed to use rating__rating to get the rating column of the rating table in the post table.
in django, i have this:
class Story(models.Model):
user = models.ForeignKey(User)
...
class Post(models.Model):
post = models.TextField(max_length=345)
story = models.ForeignKey(Story)
...
class Rating(models.Model)
rating = models.IntegerField()
post = models.ForeignKey(Post)
and then i can find all the ratings for a given post that are have a set value:
def getPostsForStory(id):
return arrangeCountOfRatings(Post.objects.filter(story=id))
def arrangeCountOfRatings(postList):
for post in postList:
post.rateA = post.rating_set.filter(rating=rateA).count()
return postList
but how do i do this from a given story? That is, say i wanted to apply the above process of getting the counts for each post, but given a Story object?
def getStoryItemsForUser(request):
return arrangeCountOfItems(Story.objects.filter(user=request.user.id)
def arrangeCountOfItems(storyList):
for story in storyList:
story.rateA = story.post_set.filter(rating=rateA).count()
return storyList
doesn't get me what i want (the counts are all wrong - either zero of, if there are posts with ratings, 1
EDIT:
ah. The problem is thus:
story.rateA = story.post_set.filter(rating=rateA).count()
does not search for what i wanted - it is searching effectively on rating__id instead of rating__rating
so i just changed it to read rating__rating, simple.
What about:
story.rateA = Rating.objects.filter(rating=ratingA, post__story=story).count()
EDIT: The same is valid for post ratings(and equivalent to your code):
post.rateA = Rating.objects.filter(rating=ratingA, post=post).count()
Counting ratings for the specified post/story.
I'm trying to get all the children of a category:
def list_sub(self, category_name):
# this will return the parent if exists
category = Category.objects.filter(seo_title__exact = seo_title).filter(lang__exact = 'pt-PT').filter(level__exact = 1)
if category:
# but this doesn't work and in the documentation there are no examples
# of how to get it. See link about the method
sub_categories = category.get_children()
http://django-mptt.github.com/django-mptt/models.html#get-children
Update1:
qc = Category.objects.filter(seo_title__exact = cat).filter(lang__exact = 'pt-PT').filter(level__exact = 1)
category = qc.get()
if category:
qsc = category.get_children()
sub_categories = qsc.get()
now I get this error: "get() returned more than one Category -- it returned 7! Lookup parameters were {}"
thanks
Your problem is not with MPTT. The issue is that category is a queryset, not an instance - get_children() is an model method, not a queryset method.
Use get instead of filter.
I want to change my ImageField's attribute, however I'm constantly getting the Can't set attribute error.
My model is
class Society(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
summary = models.TextField(blank=True,null=True)
members = models.ManyToManyField(User,null=True,blank=True)
gallery = models.ForeignKey(Gallery,null=True,blank=True)
avatar = models.ImageField(upload_to=get_society_path)
def save(self,*args,**kwargs):
super(Society, self).save(*args,**kwargs)
fix_avatar_path(self)
def clean(self):
if self.id:
self.avatar.path = get_society_path(self,self.avatar.path)
save_thumb(self.avatar.path)
And my helper functions are :
def get_society_path(instance,filename):
seperator_val = instance.id
if seperator_val is None:
seperator_val = get_time()
return '%s/society_%s/%s' % (settings.UPLOAD_ROOT,seperator_val,time_to_name(filename))
def fix_avatar_path(instance):
org_society_path = get_society_path(instance,instance.avatar.name)
make_upload_dir(org_society_path)
move(instance.avatar.path,org_society_path)
os.rmdir(os.path.dirname(instance.avatar.path))
instance.clean()
The problem is :
I want to save my society directories as society_society_id. But normally, I can't assign any id before the model is saved. So i'm creating a tmp file whose name is a time value.Then to reach societies folder, I want to rename this file. So, my fix_avatar simply moves the tmp file's content to society_(society_id) folder after the society is saved. So far so good everything works well. However, my society's ImageField still holds the previously created folder. In order to change it's value, I found that i can use clean method.(from this SO question) But still i'm getting the same result, the path doesn't change, and gives the "can't set attribute" response.
Any idea ??
Not sure, if this was ever changed in Django since this question was asked. A ticket about this not being possible still exists: https://code.djangoproject.com/ticket/15590
However, you actually can change the path by doing it like this:
self.avatar = 'uploads/example/path/'
What also does the job:
self.avatar.name = 'uploads/example/path/'
It has worked for us in several occasions.
The problem is here:
self.avatar.path = get_society_path(self,self.avatar.path)
You cannot change the value of the path attribute in FileField/ImageField instances, it's readonly. There is a proposal to change this in Django 1.4
I am trying to access data.get_age_display in my email template. I can't seem to get the display of this. I am not sure what I am doing wrong, I've using get_FIELD_display numerous times before but passed as context to a normal template. Is there something different with forms?
class RequestForm(forms.Form):
ADULT = 1
SENIOR = 2
STUDENT = 3
AGE_GROUP = (
(ADULT, 'Adult'),
(SENIOR, 'Senior'),
(STUDENT, 'Student'),
)
name = forms.CharField(max_length=255)
phone = forms.CharField(max_length=15)
age = forms.ChoiceField(choices=AGE_GROUP)
details = forms.CharField(widget=forms.Textarea())
def save(self):
order = Order(
name = self.cleaned_data['name'],
phone = self.cleaned_data['phone'],
age = self.cleaned_data['age'],
details = self.cleaned_data['details'],
)
order.save()
template = loader.get_template('request_email.txt')
# send over the order object in an email extracted so they can handle the ticket order
context = Context({
'data': order,
})
#import pdb; pdb.set_trace()
email_subject = 'Request Tickets'
mail_managers(email_subject, template.render(context))
in my request_email.txt all I am doing is {{ data.get_age_display }} any ideas?
Jeff
You haven't shown the code for the Order model that you're creating. Are you sure that the age field on the model has choices set?
Any reason you're not using a ModelForm? You're creating an Order object within the form's save() method, but not returning it. A modelform would do that for you, as well as removing the need to redeclare the fields for the form.
I know this is coming WAAAAAY later than the question being posted but here's my answer for completeness and anyone else who might benefit from it :-)
I'm going to assume that in AGE_GROUP, ADULT, SENIOR and STUDENT are integers. Your form cleaning will NOT automatically clean the string contained in the POST and return an integer. So in this code:
context = Context({
'data': order,
})
you would think order.age is referring to an integer but that is, in fact, incorrect. It's burned me a few times before because this will correctly save the integer to the physical table, but the order instance still has the string representation of the age field.
You could do one of two things:
1. Clean this in the field:
clean_age(self):
return int(self.cleaned_data['age'])
or create a new field type:
def MyChoiceField(forms.ChoiceField):
def clean(self, value):
if not value:
if self.required:
raise forms.ValidationError(self.error_messages['required'])
return None
else:
return None
return int(value)
link that to the form field:
age = MyChoiceField(choices=AGE_GROUP)
and then you'll be able to apply this logic to any other such choice field in future. Personally, I find the latter approach the best one and I stick all my custom field types into a form_utils file so that I can use them everywhere. Another gotcha is that forms.charField doesn't automatically strip the entered text and you can use this approach to fix that too.