Search Results

Search found 6723 results on 269 pages for 'django models'.

Page 11/269 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • 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: How do I add arbitrary html attributes to input fields on a form?

    - by User
    I have an input field that is rendered with a template like so: <div class="field"> {{ form.city }} </div> Which is rendered as: <div class="field"> <input id="id_city" type="text" name="city" maxlength="100" /> </div> Now suppose I want to add an autocomplete="off" attribute to the input element that is rendered, how would I do that? Or onclick="xyz()" or class="my-special-css-class"?

    Read the article

  • Insert django form into template dynamically using javascript??

    - by qulzam
    I want to add same django form instance on same template. i already add one before and other add dynamically using javascript. for example 'form" is a django form: newcell.innerHTML = {{ form.firstname }}; The problem is that when i submit the form, in view the request object has only one value (that is not add using javascript). how can i get the values of other form elements values that is added dynamically runtime.

    Read the article

  • Django : debugging templatetags

    - by interstar
    How on earth do people debug Django templatetags? I created one, based on a working example, my new tag looks the same to me as the existing one. But I just get a 'my_lib' is not a valid tag library: Could not load template library from django.templatetags.my_lib, No module named my_lib I know that this is probably because of something failing when defining the lib. But how do I see what's going on? What do you use to debug this situation?

    Read the article

  • Django: Generating a queryset from a GET request

    - by Nimmy Lebby
    I have a Django form setup using GET method. Each value corresponds to attributes of a Django model. What would be the most elegant way to generate the query? Currently this is what I do in the view: def search_items(request): if 'search_name' in request.GET: query_attributes = {} query_attributes['color'] = request.GET.get('color', '') if not query_attributes['color']: del query_attributes['color'] query_attributes['shape'] = request.GET.get('shape', '') if not query_attributes['shape']: del query_attributes['shape'] items = Items.objects.filter(**query_attributes) But I'm pretty sure there's a better way to go about it.

    Read the article

  • Parameterized Django models

    - by mgibsonbr
    In principle, a single Django application can be reused in two or more projects, providing functionality relevent to both. That implies that the same database structure (tables and relations) will be re-created identically in different databases, and most times this is not a problem (assuming the projects/databases are unrelated - for instance when someone downloads a complete app to use in their own projects). Sometimes, however, the models must be "tweaked" a little to better fit the problem needs. This can be accomplished by forking the app, but I wondered if there wouldn't be a better option in cases where the app designer can anticipate the most common customizations. For instance, if I have a model that could relate to another as one-to-one or one-to-many, I could specify the unique property as a parameter, that can be specified in the project's settings: class This(models.Model): other = models.ForeignKey(Other, unique=settings.OTHER_TO_THIS) Or if a model can relate to many others, I could create an intermediate table for each of them (thus enforcing referential integrity) instead of using generic fks: for related in settings.MODELS_RELATED_TO_OTHER: model_name = '%s_Other' % related globals()[model_name] = type(model_name, (models.Model,) { me:models.ForeignKey(find_model_class(related)), other:models.ForeignKey(Other), # Some other properties all intersection tables must have }) Etc. Let me stress out that I'm not proposing to change the models at runtime nor anything like that; once the parameters were defined and syncdb called for the first time, those parameters are not to be changed again (unless you're doing a schema migration). Is this a good design? Are there better ways to accomplish the same thing, or maybe drawbacks I coulnd't anticipate? This technique is meant to be used sparingly (only on apps meant to be reused in wildly different contexts, and only when a specific need of customization can be detected while the app model is being designed).

    Read the article

  • Django: DatabaseError column does not exist

    - by Rosarch
    I'm having a problem with Django 1.2.4. Here is a model: class Foo(models.Model): # ... ftw = models.CharField(blank=True) bar = models.ForeignKey(Bar) Right after flushing the database, I use the shell: Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from apps.foo.models import Foo >>> Foo.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 67, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 82, in __len__ self._result_cache.extend(list(self._iter)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 271, in iterator for row in compiler.results_iter(): File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 677, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 732, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute return self.cursor.execute(query, args) DatabaseError: column foo_foo.bar_id does not exist LINE 1: ...t_omg", "foo_foo"."ftw", "foo_foo... What am I doing wrong here?

    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

  • How to make a model instance read-only after saving it once?

    - by Ryszard Szopa
    One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, Newsletter and a function, send_newsletter, which I have registered to listen to Newsletter's post_save signal. When the newsletter object is saved via the admin interface, send_newsletter checks if created is True, and if yes it actually sends the mail. However, it doesn't make much sense to edit a newsletter that has already been sent, for the obvious reasons. Is there a way of making the Newsletter object read-only once it has been saved? Edit: I know I can override the save method of the object to raise an error or do nothin if the object existed. However, I don't see the point of doing that. As for the former, I don't know where to catch that error and how to communicate the user the fact that the object wasn't saved. As for the latter, giving the user false feedback (the admin interface saying that the save succeded) doesn't seem like a Good Thing. What I really want is allow the user to use the Admin interface to write the newsletter and send it, and then browse the newsletters that have already been sent. I would like the admin interface to show the data for sent newsletters in an non-editable input box, without the "Save" button. Alternatively I would like the "Save" button to be inactive.

    Read the article

  • Django attribute error: 'module' object has no attribute 'is_usable'

    - by Robert A Henru
    Hi, I got the following error when calling the url in Django. It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are. Thanks before for the help, Robert Environment: Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'djlearn.books'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/Users/rhenru/Workspace/django/djlearn/src/djlearn/../djlearn/views.py" in current_datetime 16. return render_to_response('current_datetime.html',{'current_date':now,}) File "/Library/Python/2.6/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/Library/Python/2.6/site-packages/django/template/loader.py" in render_to_string 181. t = get_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in get_template 157. template, origin = find_template(template_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template 128. loader = find_template_loader(loader_name) File "/Library/Python/2.6/site-packages/django/template/loader.py" in find_template_loader 111. if not func.is_usable: Exception Type: AttributeError at /time/ Exception Value: 'module' object has no attribute 'is_usable'

    Read the article

  • Django: Filtering datetime field by *only* the year value?

    - by unclaimedbaggage
    Hi folks, I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.ForeignKey(Business) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'client_note' @property def note_year(self): return self.created.strftime('%Y') def __unicode__(self): return '%s' % self.note I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values. Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated.

    Read the article

  • Djangoo Foreign key queries

    - by Hulk
    In the following model: class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() class options(models.Model): opt_details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() If there is a row in the database for table header as Id=1, title=value-mart , createdby=CEO How do i query criteria and options tables to get all the values related to header table id=1 Also can some one please suggest a good link for queries examples, Thanks..

    Read the article

  • Applying prerecorded animations to models with the same skeleton

    - by Jeremias Pflaumbaum
    well my question sounds a bit like, how do I apply mo-cap animations to my model, but thats not really it I guess. Animations and model share the same skeleton, but the models vary in size and proportion, but I still want to be able to apply any animation to any model. I think this should be possible since the models got the same skeleton bone structure and the bones are always in the same area only their position varies from model to model. In particular Im trying to apply this to 2D characters that got 2arm, 2legs, a head and a body, but if you got anything related to that topic even if its 3D related or keywords, articles, books whatever Im gratefull for everything cause Im a bit stuck at the moment. cheers Jery

    Read the article

  • Django's post_save signal behaves weirdly with models using multi-table inheritance

    - by hekevintran
    Django's post_save signal behaves weirdly with models using multi-table inheritance I am noticing an odd behavior in the way Django's post_save signal works when using a model that has multi-table inheritance. I have these two models: class Animal(models.Model): category = models.CharField(max_length=20) class Dog(Animal): color = models.CharField(max_length=10) I have a post save callback called echo_category: def echo_category(sender, **kwargs): print "category: '%s'" % kwargs['instance'].category post_save.connect(echo_category, sender=Dog) I have this fixture: [ { "pk": 1, "model": "animal.animal", "fields": { "category": "omnivore" } }, { "pk": 1, "model": "animal.dog", "fields": { "color": "brown" } } ] In every part of the program except for in the post_save callback the following is true: from animal.models import Dog Dog.objects.get(pk=1).category == u'omnivore' # True When I run syncdb and the fixture is installed, the echo_category function is run. The output from syncdb is: $ python manage.py syncdb --noinput Installing json fixture 'initial_data' from '~/my_proj/animal/fixtures'. category: '' Installed 2 object(s) from 1 fixture(s) The weird thing here is that the dog object's category attribute is an empty string. Why is it not 'omnivore' like it is everywhere else? As a temporary (hopefully) workaround I reload the object from the database in the post_save callback: def echo_category(sender, **kwargs): instance = kwargs['instance'] instance = sender.objects.get(pk=instance.pk) print "category: '%s'" % instance.category post_save.connect(echo_category, sender=Dog) This works but it is not something I like because I must remember to do it when the model inherits from another model and it must hit the database again. The other weird thing is that I must do instance.pk to get the primary key. The normal 'id' attribute does not work (I cannot use instance.id). I do not know why this is. Maybe this is related to the reason why the category attribute is not doing the right thing?

    Read the article

  • What is causing this OverflowError in Django?

    - by orokusaki
    I'm using a normal ModelForm.save() to create an object, and this exception comes up. It worked fine before until I added commit_manually, transaction.rollback() and transaction.commit() to my view. Has anyone else ran into this? Is this because of sqlite3? OverflowError: long too big to convert C:\Python26\Lib\site-packages\django-trunk\django\db\backends\sqlite3\base.py in execute, line 197 params: (203866156270872165269663274649746494334L,) query: u'SELECT (1) AS "a", "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = ? LIMIT 1' self <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x015D5A98> Why would that L param be passed in, and

    Read the article

  • Django - provide additional information in template

    - by Ninefingers
    Hi all, I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the address type is to the that contact (home, work etc). What I'm trying to do is pass this information out to a view, so in my full view of a contact I can do this: def contact_view_full(request, contact_id): c = get_object_or_404(Contact, id=contact_id) a = [] links = ContactAddressLink.objects.filter(ContactID=c.id) for link in links: b = Address.objects.get(id=link.AddressID_id) a.append(b) return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request)) And so I can do the equivalent of c.Addresses.all() or however the ManyToManyField works. What I'm interested to know is how can I pass out information about the link in the link object with the 'addresses' : a information, so that when my template does this: {% for address in addresses %} <!-- ... --> {% endfor %} and properly associate the correct link object data with the address. So what's the best way to achieve this? I'm thinking a union of two objects might be an idea but I haven't enough experience with Django to know if that's considered the best way of doing it. Suggestions? Thanks in advance. Nf

    Read the article

  • Django + Postgres: How to specify sequence for a field

    - by Giovanni Di Milia
    I have this model in django: class JournalsGeneral(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField("Code", max_length=50) name = models.CharField("Name", max_length=2000) url = models.URLField("Journal Web Site", max_length=2000, blank=True) online = models.BooleanField("Online?") active = models.BooleanField("Active?") class Meta: db_table = u'journals_general' verbose_name = "Journal General" ordering = ['code'] def __unicode__(self): return self.name My problem is that in the DB (Postgres) the name of the sequence connected to jid is not journals_general_jid_seq as expected by Django but it has a different name. Is there a way to specify which sequence Django has to use for an AutoField? In the documentation I read I was not able to find an answer.

    Read the article

  • Django - transactions in the model?

    - by orokusaki
    Models (disregard typos / minor syntax issues. It's just pseudo-code): class SecretModel(models.Model): some_unique_field = models.CharField(max_length=25, unique=True) # Notice this is unique. class MyModel(models.Model): secret_model = models.OneToOneField(SecretModel, editable=False) # Not in the form spam = models.CharField(max_length=15) foo = models.IntegerField() def clean(self): SecretModel.objects.create(some_unique_field=self.spam) Now if I go do this: MyModel.objects.create(spam='john', foo='OOPS') # Obviously foo won't take "OOPS" as it's an IntegerField. #.... ERROR HERE MyModel.objects.create(spam='john', foo=5) # So I try again here. #... IntegrityError because SecretModel with some_unique_field = 'john' already exists. I understand that I could put this into a view with a request transaction around it, but I want this to work in the Admin, and via an API, etc. Not just with forms, or views. How is it possible?

    Read the article

  • Do Django Models inherit managers? (Mine seem not to)

    - by Zach
    I have 2 models: class A(Model): #Some Fields objects = ClassAManager() class B(A): #Some B-specific fields I would expect B.objects to give me access to an instance of ClassAManager, but this is not the case.... >>> A.objects <app.managers.ClassAManager object at 0x103f8f290> >>> B.objects <django.db.models.manager.Manager object at 0x103f94790> Why doesn't B inherit the objects attribute from A?

    Read the article

  • In Django-pagination Paginate does not working...

    - by mosg
    Hello. Python 2.6.2 django-pagination 1.0.5 Question: How to force pagination work correctly? The problem is that {% paginate %} does not work, but other {% load pagination_tags %} and {% autopaginate object_list 10 %} works! Error message appeared, when I add {% paginate %} into html page: TemplateSyntaxError at /logging Caught an exception while rendering: pagination/pagination.html What I have done: Install django-pagination without any problems. When I do in python import pagination, it's work well. Added pagination to INSTALLED_APP in settings.py: INSTALLED_APPS = ( # ..., 'pagination', ) Added in settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request" ) Also add to settings.py middleware: MIDDLEWARE_CLASSES = ( # ... 'pagination.middleware.PaginationMiddleware', ) Add to top in views.py: from django.template import RequestContext And finally add to my HTML template page lines: {% load pagination_tags %} ... {% autopaginate item_list 50 %} {% for item in item_list %} ... {% endfor %} {% paginate %} Thanks. PS: some edits required, because I can't django code style work well here :)

    Read the article

  • Django query: Count and Group BY

    - by Tyler Lane
    I have a query that I'm trying to figure the "django" way of doing it: I want to take the last 100 calls from Call. Which is easy: calls = Call.objects.all().order_by('-call_time')[:100] However the next part I can't find the way to do it via django's ORM. I want to get a list of the call_types and the number of calls each one has WITHIN that previous queryset i just did. Normally i would do a query like this: "SELECT COUNT(id),calltype FROM call WHERE id IN ( SELECT id FROM call ORDER BY call_time DESC LIMIT 100 ) GROUP BY calltype;" I can't seem to find the django way of doing this particular query. Here are my 2 models: class Call( models.Model ): call_time = models.DateTimeField( "Call Time", auto_now = False, auto_now_add = False ) description = models.CharField( max_length = 150 ) response = models.CharField( max_length = 50 ) event_num = models.CharField( max_length = 20 ) report_num = models.CharField( max_length = 20 ) address = models.CharField( max_length = 150 ) zip_code = models.CharField( max_length = 10 ) geom = models.PointField(srid=4326) calltype = models.ForeignKey(CallType) objects = models.GeoManager() class CallType( models.Model ): name = models.CharField( max_length = 50 ) description = models.CharField( max_length = 150 ) active = models.BooleanField() time_init = models.DateTimeField( "Date Added", auto_now = False, auto_now_add = True ) objects = models.Manager()

    Read the article

  • django objects.all() method issue

    - by xlione
    after I saved one item using MyModelClass.save() method of django in one view/page , at another view I use MyModelClass.objects.all() to list all items in MyModelClass but the newly added one always is missing at the new page. i am using django 1.1 i am using mysql middleware setting MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', ) my model: class Company(models.Model): name = models.CharField(max_length=500) description = models.CharField(max_length=500,null=True) addcompany view def addcompany(request): if request.POST: form = AddCompanyForm(request.POST) if form.is_valid(): companyname = form.cleaned_data['companyname'] c = Company(name=companyname,description='description') c.save() return HttpResponseRedirect('/admins/') else: form = AddCompanyForm() return render_to_response('user/addcompany.html',{'form':form},context_instance=RequestContext(request)) after this page in another view i called this form in another view class CompanyForm(forms.Form): companies=((0,' '),) for o in CcicCompany.objects.all(): x=o.id,o.name companies+=(x,) company = forms.ChoiceField(choices=companies,label='Company Name') to list all companies but the recently added one is missing. The transaction should be successful, since after i do a apache server reboot , i can see the newly added company name Thanks for any help...

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >