Search Results

Search found 3554 results on 143 pages for 'django modelforms'.

Page 27/143 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • Django: ordering by backward related field property

    - by Silver Light
    Hello! I have two models related one-to-many: a Post and a Comment: class Post(models.Model): title = models.CharField(max_length=200); content = models.TextField(); class Comment(models.Model): post = models.ForeignKey('Post'); body = models.TextField(); date_added = models.DateTimeField(); I want to get a list of posts, ordered by the date of the latest comment. If I would write a custom SQL query it would look like this: SELECT `posts`.`*`, MAX(`comments`.`date_added`) AS `date_of_lat_comment` FROM `posts`, `comments` WHERE `posts`.`id` = `comments`.`post_id` GROUP BY `posts`.`id` ORDER BY `date_of_lat_comment` DESC How can I do same thing using django ORM?

    Read the article

  • Edit the opposite side of a many to many relationship with django generic form

    - by Ed
    I have two models: class Actor(models.Model): name = models.CharField(max_length=30, unique = True) event = models.ManyToManyField(Event, blank=True, null=True) class Event(models.Model): name = models.CharField(max_length=30, unique = True) long_description = models.TextField(blank=True, null=True) In a previous question: http://stackoverflow.com/questions/2503243/django-form-linking-2-models-by-many-to-many-field, I created an EventForm with a save function: class EventForm(forms.ModelForm): class Meta: model = Event def save(self, commit=True): instance = forms.ModelForm.save(self) instance.actors_set.clear() for actor in self.cleaned_data['actors']: instance.actors_set.add(actors) return instance This allowed me to add m2m links from the other side of the defined m2m connection. Now I want to edit the entry. I've been using a generic function: def generic_edit(request, modelname, object_id): modelname = modelname.lower() form_class = form_dict[modelname] return update_object(request, form_class = form_class, object_id = object_id, template_name = 'createdit.html' ) but this pulls in all the info except the many-to-many selections saved to this object. I think I need to do something similar to this: http://stackoverflow.com/questions/1700202/editing-both-sides-of-m2m-in-admin-page, but I haven't figured it out. How do I use the generic update_object to edit the other side of many-to-many link?

    Read the article

  • Evaluating Django Chained QuerySets Locally

    - by jnadro52
    Hello All: I am hoping someone can help me out with a quick question I have regarding chaining Django querysets. I am noticing a slow down because I am evaluating many data points in the database to create data trends. I was wondering if there was a way to have the chained filters evaluated locally instead of hitting the database. Here is a (crude) example: pastries = Bakery.objects.filter(productType='pastry') # <--- will obviously always hit DB, when evaluated cannoli = pastries.filter(specificType='cannoli') # <--- can this be evaluated locally instead of hitting the DB when evaluated, as long as pastries was evaluated? I have checked the docs and I do not see anything specifying this, so I guess it's not possible, but I wanted to check with the 'braintrust' first ;-). BTW - I know that I can do this myself by implementing some methods to loop through these datapoints and evaluate the criteria, but there are so many datapoints that my deadline does not permit me manually implementing this. Thanks in advance.

    Read the article

  • ImportError and Django driving me crazy

    - by John Peebles
    OK, I have the following directory structure (it's a django project): - project -- app and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py I'm trying to do the following: import urllib2 import os import sys import time import datetime import re import BeautifulSoup sys.path.append('/home/userspace/Development/') os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' from project.app.models import ClassName and this code just isn't working. I get an error of: Traceback (most recent call last): File "scraper.py", line 14, in from project.app.models import ClassName ImportError: No module named project.app.models This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.

    Read the article

  • Django database caching

    - by hekevintran
    I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method: class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is the first call to get MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): id_a = self.cleaned_data['id_a'] # here is the second call to get my_model_object = MyModel.objects.get(id=id_a) # do other stuff I wasn't sure whether this hits the database two times or one time so I returned the object itself in the clean method so that I could avoid a second get() call. Does calling get() hit the database two times? Or is the object cached in the thread? class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is my workaround return MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): # looking up the cleaned value returns the model object my_model_object = self.cleaned_data['id_a'] # do other stuff

    Read the article

  • How do I find the "concrete class" of a django model baseclass

    - by Mr Shark
    I'm trying to find the actual class of a django-model object, when using model-inheritance. Some code to describe the problem: class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass If I create various objects of the two Child classes and the create a queryset containing them all: Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass. I have come up with the following code: def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass But it feels brittle and I'm not sure of what happens when if I inherit in more levels.

    Read the article

  • In django models, how to make all table names not have the app label?

    - by Luigi
    I have a database that was already being used by other applications before i began writing a web interface with django for it. The table names follow simple naming standards, so the django model Customer should map to the table "customer" in the db. At the same time I'm adding new tables/models. Since I find it cumbersome to use app_customer every time i have to write a query (django's ORM is definitely not enough for them) in the other applications and I don't want to rename the existing tables, what is the best way to make all models in my django app use tables without applabel_, besides adding a Meta class with db_table= to each model? Is there any reason why I shouldn't do this? I have only one web app that needs to access this db, everything else doesn't use django models.

    Read the article

  • how to change display text in django admin foreignkey dropdown

    - by FurtiveFelon
    Hi all, I have a task list, with ability to assign users. So i have foreignkey to User model in the database. However, the default display is username in the dropdown menu, i would like to display full name (first last) instead of the username. If the foreignkey is pointing to one of my own classes, i can just change the str function in the model, but User is a django authentication model, so i can't easily change it directly right? Anyone have any idea how to accomplish this? Thanks a lot!

    Read the article

  • Django: cannot pass variable to included template?

    - by duy
    Hi, I got a problem where I want to use template including in Django. Here is the real example: I got 3 file: home.html (will get the context variable passed from Views), base.html (the skeleton template file) and the header.html (included by base.html). If if put the code below directly in base.html without including the header.html, the {{title}} variable passing from home is correctly called. But if I include the header.html in base.html, the {{title}} variable's value cannot be called. <title>{% block title %}{% endblock %} | {{ SITE_INFO_TITLE }}</title> Is there any solution to this problem? Thanks.

    Read the article

  • Incremement Page Hit Count in Django

    - by Andrew C
    I have a table with an IntegerField (hit_count), and when a page is visited (ie. http://site/page/3) I want record id 3 'hit_count' column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id=3 Can I do this with the standard Django Model conventions? Or should I just write the query by hand? I'm starting a new project, so I am trying to avoid hacks. We'll see how long this lasts! Thanks!

    Read the article

  • Django gives "I/O operation on closed file" error when reading from a saved ImageField

    - by Rob Osborne
    I have a model with two image fields, a source image and a thumbnail. When I update the new source image, save it and then try to read the source image to crop/scale it to a thumbnail I get an "I/O operation on closed file" error from PIL. If I update the source image, don't save the source image, and then try to read the source image to crop/scale, I get an "attempting to read from closed file" error from PIL. In both cases the source image is actually saved and available in later request/response loops. If I don't crop/scale in a single request/response loop but instead upload on one page and then crop/scale in another page this all works fine. This seems to be a cached buffer being reused some how, either by PIL or by the Django file storage. Any ideas on how to make an ImageField readable after saving?

    Read the article

  • I get a 400 Bad Request error while using django-piston

    - by Cheezo
    Hello, I am trying to use Piston to provide REST support to Django. I have implemented my handlers as per the documentation provided . The problem is that i can "read" and "delete" my resource but i cannot "create" or "update". Each time i hit the relevant api i get a 400 Bad request Error. I have extended the Resource class for csrf by using this commonly available code snippet: class CsrfExemptResource(Resource): """A Custom Resource that is csrf exempt""" def init(self, handler, authentication=None): super(CsrfExemptResource, self).init(handler, authentication) self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True) My class (code snippet) looks like this: user_resource = CsrfExemptResource(User) class User(BaseHandler): allowed_methods = ('GET', 'POST', 'PUT', 'DELETE') @require_extended def create(self, request): email = request.GET['email'] password = request.GET['password'] phoneNumber = request.GET['phoneNumber'] firstName = request.GET['firstName'] lastName = request.GET['lastName'] self.createNewUser(self, email,password,phoneNumber,firstName,lastName) return rc.CREATED Please let me know how can i get the create method to work using the POST operation?

    Read the article

  • Correct redirect after posting comment - django comments framework

    - by Sachin
    I am using django comments framework for allowing users to comment on my site, but there is a problem with the url to which user is redirected after posting the comment. If I render my comment form as {% with comment.content_object.get_absolute_url as next %} {% render_comment_form for comment.content_object %} {% endwith %} Then the url to which it is redirected after the comment is posted is <comment.content_object.get_absolute_url/?c=<comment.id> For example I posted a comment on a post with url /post/256/a-new-post/ then the url to which I am redirected after posting the comment is /post/256/a-new-post/?c=99 where assume 99 is the id comment just posted. Instead what I want is something like this /post/256/a-new-post/#c99. Secondly when I do comment.get_absolute_url() I do not get the proper url instead I get a url like /comments/cr/58/14/#c99 and this link is broken. How can I get the correct url as mentioned in the documentation. Am i doing something wrong. Any help is appreciated.

    Read the article

  • Django adminsite customize search_fields query

    - by dArignac
    Howdy! In the django admin you can set the search_fields for the ModelAdmin to be able to search over the properties given there. My model class has a property that is not a real model property, means it is not within the database table. The property relates to another database table that is not tied to the current model through relations. But I want to be able to search over it, so I have to somehow customize the query the admin site creates to do the filtering when the search field was filled - is this possible and if, how? I can query the database table of my custom property and it then returns the ids of the model classes fitting the search. This then, as I said, has to flow into the admin site search query. Thanks!

    Read the article

  • Django User "per project" group assignation

    - by Ben G
    Hi, Here's my problem : my site has users, which can create projects, and access other user's projects. Each project can assign different rights to users. So, i could have Project A : user "John" is in group "manager" , and Project "B" user "John" is in group "worker". How could I use the Django User authentication model to do that ? From a SQL point a view, what i would like is to be able to add "project_id" in the primary key for the "auth_user_groups" table. I don't think profile is of any help here. Any advice ? UPDATE : "worker" and "manager" are just two examples of the permission group (or "roles") that my application defines. There will be more in the future. Eg : i will probably also have "admin", "reporting", etc...

    Read the article

  • Django paging object has issues with Postgresql QuerySets

    - by pivotal
    I have some django code that runs fine on a SQLite database or on a MySQL database, but it runs into problems with Postgres, and it's making me crazy that no one has has this issue before. I think it may also be related to the way querysets are evaluated by the pager. In a view I have: def index(request, page=1): latest_posts = Post.objects.all().order_by('-pub_date') paginator = Paginator(latest_posts, 5) try: posts = paginator.page(page) except (EmptyPage, InvalidPage): posts = paginator.page(paginator.num_pages) return render_to_response('blog/index.html', {'posts' : posts}) And inside the template: {% for post in posts.object_list %} {# some rendering jazz #} {% endfor %} This works fine with SQLite, but Postgres gives me: Caught TypeError while rendering: 'NoneType' object is not callable To further complicate things, when I switch the Queryset call to: latest_posts = Post.objects.all() Everything works great. I've tried re-reading the documentation, but found nothing, although I admit I'm a bit clouded by frustration at this point. What am I missing? Thanks in advance.

    Read the article

  • Not work variables in django templates

    - by ??????? ???????
    My context dictionary not sending to my templates. I have function from django.shortcuts import render_to_response def home(request): return render_to_response('home.html',{'test':'test'}) and i have simple template such as: <html> <body> my test == {{test}} </body> </html> When i open my site in browser, i have "my test == ". settings.py is default. I dont use something custom. What the problem? Server is apache with wsgi module.

    Read the article

  • Problems using User model in django unit tests

    - by theycallmemorty
    I have the following django test case that is giving me errors: class MyTesting(unittest.TestCase): def setUp(self): self.u1 = User.objects.create(username='user1') self.up1 = UserProfile.objects.create(user=self.u1) def testA(self): ... def testB(self): ... When I run my tests, testA will pass sucessfully but before testB starts, I get the following error: IntegrityError: column username is not unique It's clear that it is trying to create self.u1 before each test case and finding that it already exists in the Database. How do I get it to properly clean up after each test case so that subsequent cases run correctly?

    Read the article

  • Django remove list_editable on a per row basis.

    - by Jason Leveille
    On the back of Django 1.2RC1, I have built a great administrator for my client! It's awesome. The client has one request that, if not satisfied, could bring this house of cards crashing down. I have a list of swim meet results. A meet result is added by a superuser. A team rep can edit a meet result (which they must be able to do inline, with list_editable), but after they edit the meet result inline and save, they should no longer be able to edit that result inline. They can only perform one edit. So, my question ... can I turn off list_editable on a per row basis?

    Read the article

  • Django - Passing arguments to models through ForeignKey attributes

    - by marshall
    I've got a class like this: class Image (models.Model): ... sizes = ((90,90), (300,250)) def resize_image(self): for size in sizes: ... and another class like this: class SomeClassWithAnImage (models.Model): ... an_image = models.ForeignKey(Image) what i'd like to do with that class is this: class SomeClassWithAnImage (models.Model): ... an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120))) where i'm can specify the sizes that i want the Image class to use to resize itself as a argument rather than being hard coded on the class. I realise I could pass these in when calling resize_image if that was called directly but the idea is that the resize_image method is called automatically when the object is persisted to the db. if I try to pass arguments through the foreign key declaration like this i get an error straight away. is there an easy / better way to do this before I begin hacking down into django?

    Read the article

  • Access to field in extended flatpage in django

    - by Stanislav Feldman
    How to access field in extended flatpage in django? I wrote this: class ExtendedFlatPage(FlatPage): teaser = CharField(max_length=150) class ExtendedFlatPageForm(FlatpageForm): teaser = CharField(max_length=150) class Meta: model = ExtendedFlatPage class ExtendedFlatPageAdmin(FlatPageAdmin): form = ExtendedFlatPageForm fieldsets = ( (None, {'fields': ('url', 'title', 'teaser', 'content', 'sites',)}), ) admin.site.unregister(FlatPage) admin.site.register(ExtendedFlatPage, ExtendedFlatPageAdmin) And creation in admin is ok. But then in flatpages/default.html I tried this: <html> <body> <h1>{{ flatpage.title }}</h1> <strong>{{ flatpage.teaser }}</strong> <p>{{ flatpage.content }}</p> </body> </html> And there was no flatpage.teaser! What is wrong?

    Read the article

  • (Django) Trim whitespaces from charField

    - by zardon
    How do I strip whitespaces (trim) from the end of a charField in Django? Here is my Model, as you can see I've tried putting in clean methods but these never get run. I've also tried doing name.strip(), models.charField().strip() but these do not work either. Is there a way to force the charField to trim automatically for me? Thanks. class Employee(models.Model): """(Workers, Staff, etc)""" name = models.CharField(blank=True, null=True, max_length=100) # This never gets run def clean_variable(self): data = self.cleaned_data['variable'].strip() return data def __unicode__(self): return self.name class Meta: verbose_name_plural = 'Employees' # This never gets run either class EmployeesForm(forms.ModelForm): class Meta: model = Employee def clean_description(self): #if not self.cleaned_data['description'].strip(): # raise forms.ValidationError('Your error message here') self.cleaned_data['name'].strip()

    Read the article

  • in django am facing url problem.....

    - by dpaksp
    am using django.0.97 version i have model called profile in that i have few fields eg like name ,email...ects and it's backend also ready..i.e database . and all users profile is created...i have given all permission to all users. when i login ,click on profile..i able to see list of all user name thr when i click on it ,it's goin to model page where i can edit the user profile..instead of that i want to navigate to a template when i can display the user details ,i have set the URl for it so that when url of that type request comes it should call a view from view it will call my template to display user details,.....the problem is it's not calling my view.... i think my problem is brief....if any information still required ?? pls ask me....and help me

    Read the article

  • Override Django inlineformset_factory has_changed() to always return True

    - by John
    Hi, I am using the django inlineformset_factory function. a = get_object_or_404(ModelA, pk=id) FormSet = inlineformset_factory(ModelA, ModelB) if request.method == 'POST': metaform = FormSet (instance=a, data=request.POST) if metaform.is_valid(): f = metaform.save(commit=False) for instance in f: instance.updated_by = request.user instance.save() else: metaform = FormSet(instance=a) return render_to_response('nodes/form.html', {'form':metaform}) What is happening is that if I change any of the data then everything works ok and all the data gets updated. However if I don't change any of the data then the data is not updated. i.e. only entries which are changed go through the for loop to be saved. I guess this makes sense as there is no point saving data if it has not changed. However I need to go through and save every object in the form regardless of whether it has any changes on not. So my question is how do I override this so that it goes through and saves every record whether it has any changes or not? Hope this makes sense Thanks

    Read the article

  • Django: query spanning multiple many-to-many relationships

    - by Brant
    I've got some models set up like this: class AppGroup(models.Model): users = models.ManyToManyField(User) class Notification(models.Model): groups_to_notify = models.ManyToManyField(AppGroup) The User objects come from django's authentication system. Now, I am trying to get all the notifications pertaining to the groups that the current user is a part of. I have tried.. notifications = Notification.objects.filter(groups_to_notify=AppGroup.objects.filter(users=request.user)) But that gives an error: more than one row returned by a subquery used as an expression Which I suppose is because the groups_to_notify is checking against several groups. How can I grab all the notifications meant for the user based on the groups he is a part of?

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >