Search Results

Search found 8610 results on 345 pages for 'django filter'.

Page 6/345 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Django: Summing values of records grouped by foreign key

    - by Dan0
    Hi there In django, given the following models (slightly simplified), I'm struggling to work out how I would get a view including sums of groups class Client(models.Model): api_key = models.CharField(unique=True, max_length=250, primary_key=True) name = models.CharField(unique=True, max_length=250) class Purchase(models.Model): purchase_date = models.DateTimeField() client = models.ForeignKey(SavedClient, to_field='api_key') amount_to_invoice = models.FloatField(null=True) For a given month, I'd like to see e.g. April 2010 For Each Client that purchased this month: * CLient: Name * Total amount of Purchases for this month * Total cost of purchases for this month For each Purchase made by client: * Date * Amount * Etc I've been looking into django annotation, but can't get my head around how to sum values of a field for a particular group over a particular month and send the information to a template as a variable/tag. Any info would be appreciated

    Read the article

  • Django: Country drop down list?

    - by User
    I have a form for address information. One of the fields is for the address country. Currently this is just a textbox. I would like a drop down list (of ISO 3166 countries) for this. I'm a django newbie so I haven't even used a Django Select widget yet. What is a good way to do this? Hard-code the choices in a file somewhere? Put them in the database? In the template?

    Read the article

  • Django: reverse lookup URL of feeds?

    - by Santa
    I am having trouble doing a reverse URL lookup for Django-generated feeds. I have the following setup in urls.py: feeds = { 'latest': LatestEntries, } urlpatterns = patterns('', # ... # enable feeds (RSS) url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds_view'), ) I have tried using the following template tag: <a href="{% url feeds_view latest %}">RSS feeds</a> But the resulting link is not what want (http://my.domain.com/feeds//). It should be http://my.domain.com/feeds/latest/. For now, I am using a hack to generate the URL for the template: <a href="http://{{ request.META.HTTP_HOST }}/feeds/latest">RSS feeds</a> But, as you can see, it clearly is not DRY. Is there something I am missing?

    Read the article

  • Project name inserted automatically in url when using django template url tag

    - by thebossman
    I am applying the 'url' template tag to all links in my current Django project. I have my urls named like so... url(r'^login/$', 'login', name='site_login'), This allows me to access /login at my site's root. I have my template tag defined like so... <a href="{% url site_login %}"> It works fine, except that Django automatically resolves that url as /myprojectname/login, not /login. Both urls are accessible. Why? Is there an option to remove the projectname? This occurs for all url tags, not just this one.

    Read the article

  • How to customize a many-to-many inline model in django admin

    - by Jonathan
    I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: class Product(models.Model): name = models.TextField() price = models.DecimalField(max_digits=10,decimal_places=2) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) In admin.py: class ProductInline(admin.StackedInline): model = Invoice.products.through class InvoiceAdmin(admin.ModelAdmin): inlines = [FilteredApartmentInline,] admin.site.register(Product, ProductAdmin) The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic. How can I change it so that it'll just display the product's name in the inline table? Which form should I override, and how?

    Read the article

  • django cross-site reverse a url

    - by tutuca
    I have a similar question than django cross-site reverse. But i think I can't apply the same solution. I'm creating an app that lets the users create their own site. After completing the signup form the user should be redirected to his site's new post form. Something along this lines: new_post_url = 'http://%s.domain:9292/manage/new_post %site.domain' logged_user = authenticate(username=user.username, password=user.password) if logged_user is not None: login(request, logged_user) return redirect(new_product_url) Now, I know that "new_post_url" is awful and makes babies cry so I need to reverse it in some way. I thought in using django.core.urlresolvers.reverse to solve this but that only returns urls on my domain, and not in the user's newly created site, so it doesn't works for me. So, do you know a better/smarter way to solve this?

    Read the article

  • Load django template from the database

    - by Björn Lindqvist
    Hello, Im trying to render a django template from a database outside of djangos normal request-response structure. But it appears to be non-trivial due to the way django templates are compiled. I want to do something like this: >>> s = Template.objects.get(pk = 123).content >>> some_method_to_render(s, {'a' : 123, 'b' : 456}) >>> ... the rendered output here ... How do you do this?

    Read the article

  • How to use multiple flatpages models in a django app?

    - by the_drow
    I have multiple models that can be converted to flatpages but have to have some extra information (For example I have an about us page but I also have a blog). However I understand that there must be only one flatpages model since the middleware only returns the flatpages instance and does not resolve the child models. What do I have to do? EDIT: It seems I need to change the views. Here's the current code: from django.contrib.flatpages.models import FlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core.xheaders import populate_xheaders from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = 'flatpages/default.html' # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url # Here instead of getting the flat page it needs to find if it has a page with a child model. f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) # Here I need to be able to configure what I am passing in the context c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response

    Read the article

  • Create Django formset wihtout multiple queries

    - by Martin
    I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this. TheFormSet = formset_factory(SomeForm, extra=10) ... formset = TheFormSet(prefix='party') return render_to_response('template.html', { 'formset' : formset, }) The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same. Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?

    Read the article

  • django auth_views.login and redirects

    - by Zayatzz
    Hello I could not understand why after logging in from address: http://localhost/en/accounts/login/?next=/en/test/ I get refirected to http://localhost/accounts/profile/ So i ran search in django files and found that this address is the default LOGIN_REDIRECT_URL for django. What i did not understand is why it gets redirected to there. I guessed, that my login form's post address should be : /accounts/login/?next=/en/test/ instead of /accounts/login/ I wrote it into template and it worked. But since the redirect url changes dynamically, how can i make this login post forms address change dynamically too? is there a templatetag for that or something? Alan

    Read the article

  • Calling a method from within a django model save() override

    - by Jonathan
    I'm overriding a django model save() method. Within the override I'm calling another method of the same class and instance which calculates one of the instance's fields based on other fields of the same instance. class MyClass(models.Model): field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() def calculateField1(self) self.field1 = self.field2 + self.field3 def save(self, *args, **kwargs): self.calculateField1() super(MyClass, self).save(*args, **kwargs) The override method is called when I change the model in admin. Alas I've discovered that within calculateField1() field2 and field3 have the values of the instance from before I edited them in admin. If I enter the instance again in admin and save again, only then field1 receives the correct value as field2 and field3 are already updated. Is this the correct behavior on django's side? If yes, then how can I use the new values within calculateField1? I cannot implement the calculation within the save() as calculateField1() actually quite long and I need it to be called from elsewhere.

    Read the article

  • Django: Complex filter parameters or...?

    - by minder
    This question is connected to my other question but I changed the logic a bit. I have models like this: from django.contrib.auth.models import Group class Category(models.Model): (...) editors = ForeignKey(Group) class Entry(models.Model): (...) category = ForeignKey(Category) Now let's say User logs into admin panel and wants to change an Entry. How do I limit the list of Entries only to those, he has the right to edit? I mean: How can I list only those Entries which are assigned to a Category that in its "editors" field has one of the groups the User belongs to? What if User belongs to several groups? I still need to show all relevant Entries. I tried experimenting with changelist_view() and queryset() methods but this problem is a bit too complex for me. I'm also wondering if granular-permissions could help me with the task, but for now I have no clue. I came up only with this: First I get the list of all Groups the User belongs to. Then for each Group I get all connected Categories and then for each Category I get all Entries that belong to these Categories. Unfortunately I have no idea how to stitch everything together as filter() parameters to produce a nice single QuerySet.

    Read the article

  • Django: testing get query

    - by Brant
    Okay, so I am sick of writing this... res = Something.objects.filter(asdf=something) if res: single = res[0] else: single = None if single: # do some stuff I would much rather be able to do something like this: single = Something.objects.filter(asdf=something) if single: #do some stuff I want to be able to grab a single object without testing the filtered results. In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a 'None'. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line. Is there any way to do what I have described?

    Read the article

  • Django ORM QuerySet intersection by a field

    - by Sri Raghavan
    These are the (pseudo) models I've got. Blog: name etc... Article: name blog creator etc User (as per django.contrib.auth) So my problem is this: I've got two users. I want to get all of the articles that the two users published on the same blog (no matter which blog). I can't simply filter the Article model by both users, because that would yield the set of Articles created by both users. Obviously not what I want. but can I filter somehow to get all of the articles where a field of the object matches between the two querysets?

    Read the article

  • Django | django-socialregistration error

    - by MMRUser
    I'm trying to add the facebook connect feature to my site, I decided to use django socialregistration.All are setup including pyfacebook, here is my source code. settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebook.djangofb.FacebookMiddleware', 'socialregistration.middleware.FacebookMiddleware', ) urls.py (r'^callback/$', 'fbproject.fbapp.views.callback'), views.py def callback(request): return render_to_response('canvas.fbml') Template <html> <body> {% load facebook_tags %} {% facebook_button %} {% facebook_js %} </body> </html> but when I point to the URL, I'm getting this error Traceback (most recent call last): File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__ response = self.get_response(request) File "C:\Python26\lib\site-packages\django\core\handlers\base.py", line 73, in get_response response = middleware_method(request) File "build\bdist.win32\egg\socialregistration\middleware.py", line 13, in process_request request.facebook.check_session(request) File "C:\Python26\lib\site-packages\facebook\__init__.py", line 1293, in check_session self.session_key_expires = int(params['expires']) ValueError: invalid literal for int() with base 10: 'None' Django 1.1.1 *Python 2.6.2*

    Read the article

  • Manditory read-only fields in django

    - by jamida
    I'm writing a test "grade book" application. The models.py file is shown below. class Student(models.Model): name = models.CharField(max_length=50) parent = models.CharField(max_length=50) def __unicode__(self): return self.name class Grade(models.Model): studentId = models.ForeignKey(Student) finalGrade = models.CharField(max_length=3) I'd like to be able to change the final grade for several students in a modelformset but for now I'm just trying one student at a time. I'm also trying to create a form for it that shows the student name as a field that can not be changed, the only thing that can be changed here is the finalGrade. So I used this trick to make the studentId read-only. class GradeROForm(ModelForm): studentId = forms.ModelChoiceField(queryset=Student.objects.all()) def __init__(self, *args, **kwargs): super(GradeROForm,self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.id: self.fields['studentId'].widget.attrs['disabled']='disabled' def clean_studentId(self): instance = getattr(self,'instance',None) if instance: return instance.studentId else: return self.cleaned_data.get('studentId',None) class Meta: model=Grade And here is my view: def modifyGrade(request,student): student = Student.objects.get(name=student) mygrade = Grade.objects.get(studentId=student) if request.method == "POST": myform = GradeROForm(data=request.POST, instance=mygrade) if myform.is_valid(): grade = myform.save() info = "successfully updated %s" % grade.studentId else: myform=GradeROForm(instance=mygrade) return render_to_response('grades/modifyGrade.html',locals()) This displays the form like I expect, but when I hit "submit" I get a form validation error for the student field telling me this field is required. I'm guessing that, since the field is "disabled", the value is not being reported in the POST and for reasons unknown to me the instance isn't being used in its place. I'm a new Django/Python programmer, but quite experienced in other languages. I can't believe I've stumbled upon such a difficult to solve problem in my first significant django app. I figure I must be missing something. Any ideas?

    Read the article

  • Django Upload form to S3 img and form validation

    - by citadelgrad
    I'm fairly new to both Django and Python. This is my first time using forms and upload files with django. I can get the uploads and saves to the database to work fine but it fails to valid email or check if the users selected a file to upload. I've spent a lot of time reading documentation trying to figure this out. Thanks! views.py def submit_photo(request): if request.method == 'POST': def store_in_s3(filename, content): conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(AWS_STORAGE_BUCKET_NAME) mime = mimetypes.guess_type(filename)[0] k = Key(bucket) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_file(content) k.set_acl('public-read') if imghdr.what(request.FILES['image_url']): qw = request.FILES['image_url'] filename = qw.name image = filename content = qw.file url = "http://bpd-public.s3.amazonaws.com/" + image data = {image_url : url, user_email : request.POST['user_email'], user_twittername : request.POST['user_twittername'], user_website : request.POST['user_website'], user_desc : request.POST['user_desc']} s = BeerPhotos(data) if s.is_valid(): #import pdb; pdb.set_trace() s.save() store_in_s3(filename, content) return HttpResponseRedirect(reverse('photos.views.thanks')) return s.errors else: return errors else: form = BeerPhotoForm() return render_to_response('photos/submit_photos.html', locals(),context_instance=RequestContext(request) forms.py class BeerPhotoForm(forms.Form): image_url = forms.ImageField(widget=forms.FileInput, required=True,label='Beer',help_text='Select a image of no more than 2MB.') user_email = forms.EmailField(required=True,help_text='Please type a valid e-mail address.') user_twittername = forms.CharField() user_website = forms.URLField(max_length=128,) user_desc = forms.CharField(required=True,widget=forms.Textarea,label='Description',) template.html <div id="stylized" class="myform"> <form action="." method="post" enctype="multipart/form-data" width="450px"> <h1>Photo Submission</h1> {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <label><span>Click here</span></label> <input type="submit" class="greenbutton" value="Submit your Photo" /> </form> </div>

    Read the article

  • Invalidating Memcached Keys on save() in Django

    - by Zack
    I've got a view in Django that uses memcached to cache data for the more highly trafficked views that rely on a relatively static set of data. The key word is relatively: I need invalidate the memcached key for that particular URL's data when it's changed in the database. To be as clear as possible, here's the meat an' potatoes of the view (Person is a model, cache is django.core.cache.cache): def person_detail(request, slug): if request.is_ajax(): cache_key = "%s_ABOUT_%s" % settings.SITE_PREFIX, slug # Check the cache to see if we've already got this result made. json_dict = cache.get(cache_key) # Was it a cache hit? if json_dict is None: # That's a negative Ghost Rider person = get_object_or_404(Person, display = True, slug = slug) json_dict = { 'name' : person.name, 'bio' : person.bio_html, 'image' : person.image.extra_thumbnails['large'].absolute_url, } cache.set(cache_key) # json_dict will now exist, whether it's from the cache or not response = HttpResponse() response['Content-Type'] = 'text/javascript' response.write(simpljson.dumps(json_dict)) # Make sure it's all properly formatted for JS by using simplejson return response else: # This is where the fully templated response is generated What I want to do is get at that cache_key variable in it's "unformatted" form, but I'm not sure how to do this--if it can be done at all. Just in case there's already something to do this, here's what I want to do with it (this is from the Person model's hypothetical save method) def save(self): # If this is an update, the key will be cached, otherwise it won't, let's see if we can't find me try: old_self = Person.objects.get(pk=self.id) cache_key = # Voodoo magic to get that variable old_key = cache_key.format(settings.SITE_PREFIX, old_self.slug) # Generate the key currently cached cache.delete(old_key) # Hit it with both barrels of rock salt # Turns out this doesn't already exist, let's make that first request even faster by making this cache right now except DoesNotExist: # I haven't gotten to this yet. super(Person, self).save() I'm thinking about making a view class for this sorta stuff, and having functions in it like remove_cache or generate_cache since I do this sorta stuff a lot. Would that be a better idea? If so, how would I call the views in the URLconf if they're in a class?

    Read the article

  • Formatting inline many-to-many related models presented in django admin

    - by Jonathan
    I've got two django models (simplified): class Product(models.Model): name = models.TextField() price = models.IntegerField() class Invoice(models.Model): company = models.TextField() customer = models.TextField() products = models.ManyToManyField(Product) I would like to see the relevant products as a nice table (of product fields) in an Invoice page in admin and be able to link to the individual respective Product pages. My first thought was using the admin's inline - but django used a select box widget per related Product. This isn't linked to the Product pages, and also as I have thousands of products, and each select box independently downloads all the product names, it quickly becomes unreasonably slow. So I turned to using ModelAdmin.filter_horizontal as suggested here, which used a single instance of a different widget, where you have a list of all Products and another list of related Products and you can add\remove products in the later from the former. This solved the slowness, but it still doesn't show the relevant Product fields, and it ain't linkable. So, what should I do? tweak views? override ModelForms? I Googled around and couldn't find any example of such code...

    Read the article

  • Math on Django Templates

    - by Leandro Abilio
    Here's another question about Django. I have this code: views.py cursor = connections['cdr'].cursor() calls = cursor.execute("SELECT * FROM cdr where calldate > '%s'" %(start_date)) result = [SQLRow(cursor, r) for r in cursor.fetchall()] return render_to_response("cdr_user.html", {'calls':result }, context_instance=RequestContext(request)) I use a MySQL query like that because the database is not part of a django project. My cdr table has a field called duration, I need to divide that by 60 and multiply the result by a float number like 0.16. Is there a way to multiply this values using the template tags? If not, is there a good way to do it in my views? My template is like this: {% for call in calls %} <tr class="{% cycle 'odd' 'even' %}"><h3> <td valign="middle" align="center"><h3>{{ call.calldate }}</h3></td> <td valign="middle" align="center"><h3>{{ call.disposition }}</h3></td> <td valign="middle" align="center"><h3>{{ call.dst }}</h3></td> <td valign="middle" align="center"><h3>{{ call.billsec }}</h3></td> <td valign="middle" align="center">{{ (call.billsec/60)*0.16 }}</td></h3> </tr> {% endfor %} The last is where I need to show the value, I know the "(call.billsec/60)*0.16" is impossible to be done there. I wrote it just to represent what I need to show.

    Read the article

  • Django ModelForm is giving me a validation error that doesn't make sense

    - by River Tam
    I've got a ModelForm based on a Picture. class Picture(models.Model): name = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') tags = models.ManyToManyField('Tag', blank=True) content = models.ImageField(upload_to='instaton') def __unicode__(self): return self.name class PictureForm(forms.ModelForm): class Meta: model = Picture exclude = ('pub_date','tags') That's the model and the ModelForm, of course. def submit(request): if request.method == 'POST': # if the form has been submitted form = PictureForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/django/instaton') else: form = PictureForm() # blank form return render_to_response('instaton/submit.html', {'form': form}, context_instance=RequestContext(request)) That's the view (which is being correctly linked to by urls.py) Right now, I do nothing when the form submits. I just check to make sure it's valid. If it is, I forward to the main page of the app. <form action="/django/instaton/submit/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value"Submit" /> </form> And there's my template (in the correct location). When I try to actually fill out the form and just validate it, even if I do so correctly, it sends me back to the form and says "This field is required" between Name and Content. I assume it's referring to Content, but I'm not sure. What's my problem? Is there a better way to do this?

    Read the article

  • Modify the filter chain - Or select servlet to respond to request using filter

    - by klonq
    I am trying to use a filter to map requests. I am trying to do this for two reasons, firstly to dynamically generate URI's and have them mapped to the appropriate servlet and secondly to catch URI's which are not registered and handle them appropriately. So I'm using a catch-all filter to process the URI and determine the response. I would like some way of modifying the filter chain, or some way to set the servlet which responds to the request from within the filter. I have been unsuccessful using filterConfig.getServletContext().getRequestDispatcher().forward() to send to jsp, ideally though I would like to map to a servlet but can't figure out how. The reason I am not doing this from within a servlet is that I have some URIs which are fixed within web.xml and if I use a catch-all servlet those URIs do not get mapped. Is this possible, is it clean or it going to get really messy?

    Read the article

  • Creating a QuerySet based on a ManyToManyField in Django

    - by River Tam
    So I've got two classes; Picture and Tag that are as follows: class Tag(models.Model): pics = models.ManyToManyField('Picture', blank=True) name = models.CharField(max_length=30) # stuff omitted class Picture(models.Model): name = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') tags = models.ManyToManyField('Tag', blank=True) content = models.ImageField(upload_to='instaton') #stuff omitted And what I'd like to do is get a queryset (for a ListView) given a tag name that contains the most recent X number of Pictures that are tagged as such. I've looked up very similar problems, but none of the responses make any sense to me at all. How would I go about creating this queryset?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >