Search Results

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

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

  • Upload Image with Django Model Form

    - by jmitchel3
    I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access. #Models.py class Profile(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User) profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/') #views.py def create_profile(request): try: profile = Profile.objects.get(user=request.user) except: pass form = CreateProfileForm(request.POST or None, instance=profile) if form.is_valid(): new = form.save(commit=False) new.user = request.user new.save() return render_to_response('profile.html', locals(), context_instance=RequestContext(request)) #Profile.html <form enctype="multipart/form-data" method="post">{% csrf_token %} <tr><td>{{ form.as_p }}</td></tr> <tr><td><button type="submit" class="btn">Submit</button></td></tr> </form> Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!

    Read the article

  • Django Managers

    - by owca
    I have the following models code : from django.db import models from categories.models import Category class MusicManager(models.Manager): def get_query_set(self): return super(MusicManager, self).get_query_set().filter(category='Music') def count_music(self): return self.all().count() class SportManager(models.Manager): def get_query_set(self): return super(MusicManager, self).get_query_set().filter(category='Sport') class Event(models.Model): title = models.CharField(max_length=120) category = models.ForeignKey(Category) objects = models.Manager() music = MusicManager() sport = SportManager() Now by registering MusicManager() and SportManager() I am able to call Event.music.all() and Event.sport.all() queries. But how can I create Event.music.count() ? Should I call self.all() in count_music() function of MusicManager to query only on elements with 'Music' category or do I still need to filter through them in search for category first ?

    Read the article

  • django modelformset - one form per related table row

    - by Toby
    Hello, I have two models: class Model1(): name = CharField() url = CharField() class Model2(): model1 = ForeignKey(Model1) user = ForeignKey(User) zzz = CharField() There are 5 rows for model1 in the database, these are fixed and will rarely change. I need to display a formset for model2 that allows users to enter the zzz value, the formset must always show one form per row in the model1 table, the label for each form in the formset must be the name of the related model1. If the user deletes a model2 in the formset the next time the page loads it will render an empty zzz value for that form and the user must be able to edit the previous zzz value - meaning it must be pre populated with all model2 rows associated with the user. The idea is to print each row in the model1 table as a form instead of the user selecting the related model1 name in a select box. I know its not that complicated, but I'm seriously stumped and keep going round in circles!! Many thanks in advance. Similar to http://stackoverflow.com/questions/298779/form-or-formset-to-handle-multiple-table-rows-in-django

    Read the article

  • Django: Adding inline formset rows without javascript

    - by Brant
    This post relates to this: http://stackoverflow.com/questions/520421/add-row-to-inlines-dynamically-in-django-admin Is there a way to achive adding inline formsets WITHOUT using javascript? Obviously, there would be a page-refresh involved. So, if the form had a button called 'add'... I figured I could do it like this: if request.method=='POST': if 'add' in request.POST: PrimaryFunctionFormSet = inlineformset_factory(Position,Function,extra=1) prims = PrimaryFunctionFormSet(request.POST) Which I thought would add 1 each time, then populate the form with the post data. However, it seems that the extra=1 does not add 1 to the post data.

    Read the article

  • Django: Overriding the save() method: how do I call the delete() method of a child class

    - by Patti
    The setup = I have this class, Transcript: class Transcript(models.Model): body = models.TextField('Body') doPagination = models.BooleanField('Paginate') numPages = models.PositiveIntegerField('Number of Pages') and this class, TranscriptPages(models.Model): class TranscriptPages(models.Model): transcript = models.ForeignKey(Transcript) order = models.PositiveIntegerField('Order') content = models.TextField('Page Content', null=True, blank=True) The Admin behavior I’m trying to create is to let a user populate Transcript.body with the entire contents of a long document and, if they set Transcript.doPagination = True and save the Transcript admin, I will automatically split the body into n Transcript pages. In the admin, TranscriptPages is a StackedInline of the Transcript Admin. To do this I’m overridding Transcript’s save method: def save(self): if self.doPagination: #do stuff super(Transcript, self).save() else: super(Transcript, self).save() The problem = When Transcript.doPagination is True, I want to manually delete all of the TranscriptPages that reference this Transcript so I can then create them again from scratch. So, I thought this would work: #do stuff TranscriptPages.objects.filter(transcript__id=self.id).delete() super(Transcript, self).save() but when I try I get this error: Exception Type: ValidationError Exception Value: [u'Select a valid choice. That choice is not one of the available choices.'] ... and this is the last thing in the stack trace before the exception is raised: .../django/forms/models.py in save_existing_objects pk_value = form.fields[pk_name].clean(raw_pk_value) Other attempts to fix: t = self.transcriptpages_set.all().delete() (where self = Transcript from the save() method) looping over t (above) and deleting each item individually making a post_save signal on TranscriptPages that calls the delete method Any ideas? How does the Admin do it? UPDATE: Every once in a while as I'm playing around with the code I can get a different error (below), but then it just goes away and I can't replicate it again... until the next random time. Exception Type: MultiValueDictKeyError Exception Value: "Key 'transcriptpages_set-0-id' not found in " Exception Location: .../django/utils/datastructures.py in getitem, line 203 and the last lines from the trace: .../django/forms/models.py in _construct_form form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) .../django/utils/datastructures.py in getitem pk = self.data[pk_key]

    Read the article

  • Django, want to upload eather image (ImageField) or file (FileField)

    - by Serg
    I have a form in my html page, that prompts user to upload File or Image to the server. I want to be able to upload ether file or image. Let's say if user choose file, image should be null, and vice verso. Right now I can only upload both of them, without error. But If I choose to upload only one of them (let's say I choose image) I will get an error: "Key 'attachment' not found in <MultiValueDict: {u'image': [<InMemoryUploadedFile: police.jpg (image/jpeg)>]}>" models.py: #Description of the file class FileDescription(models.Model): TYPE_CHOICES = ( ('homework', 'Homework'), ('class', 'Class Papers'), ('random', 'Random Papers') ) subject = models.ForeignKey('Subjects', null=True, blank=True) subject_name = models.CharField(max_length=100, unique=False) category = models.CharField(max_length=100, unique=False, blank=True, null=True) file_type = models.CharField(max_length=100, choices=TYPE_CHOICES, unique=False) file_uploaded_by = models.CharField(max_length=100, unique=False) file_name = models.CharField(max_length=100, unique=False) file_description = models.TextField(unique=False, blank=True, null=True) file_creation_time = models.DateTimeField(editable=False) file_modified_time = models.DateTimeField() attachment = models.FileField(upload_to='files', blank=True, null=True, max_length=255) image = models.ImageField(upload_to='files', blank=True, null=True, max_length=255) def __unicode__(self): return u'%s' % (self.file_name) def get_fields(self): return [(field, field.value_to_string(self)) for field in FileDescription._meta.fields] def filename(self): return os.path.basename(self.image.name) def category_update(self): category = self.file_name return category def save(self, *args, **kwargs): if self.category is None: self.category = FileDescription.category_update(self) for field in self._meta.fields: if field.name == 'image' or field.name == 'attachment': field.upload_to = 'files/%s/%s/' % (self.file_uploaded_by, self.file_type) if not self.id: self.file_creation_time = datetime.now() self.file_modified_time = datetime.now() super(FileDescription, self).save(*args, **kwargs) forms.py class ContentForm(forms.ModelForm): file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20})) file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25})) class Meta: model = FileDescription exclude = ('subject', 'subject_name', 'file_uploaded_by', 'file_creation_time', 'file_modified_time', 'vote') def clean_file_name(self): name = self.cleaned_data['file_name'] # check the length of the file name if len(name) < 2: raise forms.ValidationError('File name is too short') # check if file with same name is already exists if FileDescription.objects.filter(file_name = name).exists(): raise forms.ValidationError('File with this name already exists') else: return name views.py if request.method == "POST": if "upload-b" in request.POST: form = ContentForm(request.POST, request.FILES, instance=subject_id) if form.is_valid(): # need to add some clean functions # handle_uploaded_file(request.FILES['attachment'], # request.user.username, # request.POST['file_type']) form.save() up_f = FileDescription.objects.get_or_create( subject=subject_id, subject_name=subject_name, category = request.POST['category'], file_type=request.POST['file_type'], file_uploaded_by = username, file_name=form.cleaned_data['file_name'], file_description=request.POST['file_description'], image = request.FILES['image'], attachment = request.FILES['attachment'], ) return HttpResponseRedirect(".")

    Read the article

  • Django 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

  • Django FileField not saving to upload_to location

    - by Erik
    I have an Attachment model that has a FileField in a Django 1.4.1 app. This FileField has a callable upload_to parameter which, per the Django docs should be called when the form (and therefore the model) is saved. When I run FormTest below, the upload_to callable is never called and the file therefore does not appear in the location provided by the upload_to method. What am I doing wrong? Notice that in the passing tests in ModelTest (also below), the upload_to method works as expected. Test: from core.forms.attachments import AttachmentForm from django.test import TestCase import unittest from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.storage import default_storage def suite(): return unittest.TestSuite( [ unittest.TestLoader().loadTestsFromTestCase(FormTest), ] ) class FormTest(TestCase): def test_form_1(self): filename = 'filename' f = file(filename) data = {'name':'name',} file_data = {'attachment_file':SimpleUploadedFile(f.name,f.read()),} form = AttachmentForm(data=data,files=file_data) self.assertTrue(form.is_valid()) attachment = form.save() root_directory = 'attachments' upload_location = root_directory + '/' + attachment.directory + '/' + filename self.assertTrue(attachment.attachment_file) # Fails self.assertTrue(default_storage.exists(upload_location)) # Fails Attachment Model: from django.db import models from parent_mixins import Parent_Mixin import uuid from django.db.models.signals import pre_delete,pre_save from dirtyfields import DirtyFieldsMixin def upload_to(instance,filename): return 'attachments/' + instance.directory + '/' + filename def uuid_directory_name(): return uuid.uuid4().hex class Attachment(DirtyFieldsMixin,Parent_Mixin,models.Model): attachment_file = models.FileField(blank=True,null=True,upload_to=upload_to) directory = models.CharField(blank=False,default=uuid_directory_name,null=False,max_length=32) name = models.CharField(blank=False,default=None,null=False,max_length=128) class Meta: app_label = 'core' def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): return unicode(self.name) @models.permalink def get_absolute_url(self): return('core_attachments_update',(),{'pk': self.pk}) # def save(self,*args,**kwargs): # super(Attachment,self).save(*args,**kwargs) def pre_delete_callback(sender, instance, *args, **kwargs): if not isinstance(instance, Attachment): return if not instance.attachment_file: return instance.attachment_file.delete(save=False) def pre_save_callback(sender, instance, *args, **kwargs): if not isinstance(instance, Attachment): return if not instance.attachment_file: return if instance.is_dirty(): dirty_fields = instance.get_dirty_fields() if 'attachment_file' in dirty_fields: old_attachment_file = dirty_fields['attachment_file'] old_attachment_file.delete() pre_delete.connect(pre_delete_callback) pre_save.connect(pre_save_callback) Attachment Form: from ..models.attachments import Attachment from crispy_forms.helper import FormHelper from crispy_forms.layout import Div,Layout,HTML,Field,Fieldset,Button,ButtonHolder,Submit from django import forms class AttachmentFormHelper(FormHelper): form_tag=False layout = Layout( Div( Div( Field('name',css_class='span4'), Field('attachment_file',css_class='span4'), css_class='span4', ), css_class='row', ), ) class AttachmentForm(forms.ModelForm): helper = AttachmentFormHelper() class Meta: fields=('attachment_file','name') model = Attachment class AttachmentInlineFormHelper(FormHelper): form_tag=False form_style='inline' layout = Layout( Div( Div( Field('name',css_class='span4'), Field('attachment_file',css_class='span4'), Field('DELETE',css_class='span4'), css_class='span4', ), css_class='row', ), ) class AttachmentInlineForm(forms.ModelForm): helper = AttachmentInlineFormHelper() class Meta: fields=('attachment_file','name') model = Attachment UPDATE I also do testing on the Attachment model class with these unit tests -- which all pass: from core.models.attachments import Attachment from core.models.attachments import upload_to from django.test import TestCase import unittest from django.core.files.storage import default_storage from django.core.files.base import ContentFile def suite(): return unittest.TestSuite( [ unittest.TestLoader().loadTestsFromTestCase(ModelTest), ] ) class ModelTest(TestCase): def test_model_minimum_fields(self): attachment = Attachment(name='name') attachment.attachment_file.save('test.txt',ContentFile("hello world")) attachment.save() self.assertEqual(str(attachment),'name') self.assertEqual(unicode(attachment),'name') self.assertTrue(attachment.directory) # def test_model_full_fields(self): # attachment = Attachment() # attachement.save() def test_file_operations_basic(self): root_directory = 'attachments' filename = 'test.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename,ContentFile('test')) attachment.save() upload_location = root_directory + '/' + attachment.directory + '/' + filename self.assertEqual(upload_to(attachment,filename),upload_location) self.assertTrue(default_storage.exists(upload_location)) def test_file_operations_delete(self): root_directory = 'attachments' filename = 'test.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename,ContentFile('test')) attachment.save() upload_location = upload_to(attachment,filename) attachment.delete() self.assertFalse(default_storage.exists(upload_location)) def test_file_operations_change(self): root_directory = 'attachments' filename_1 = 'test_1.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename_1,ContentFile('test')) attachment.save() upload_location_1 = upload_to(attachment,filename_1) self.assertTrue(default_storage.exists(upload_location_1)) filename_2 = 'test_2.txt' attachment.attachment_file.save(filename_2,ContentFile('test')) attachment.save() upload_location_2 = upload_to(attachment,filename_2) self.assertTrue(default_storage.exists(upload_location_2)) self.assertFalse(default_storage.exists(upload_location_1))

    Read the article

  • Django not recognizing django admin urls

    - by colorfulgrayscale
    I just registered my models my models with django admin. I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far. But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying The current URL, admin/auth/user/, didn't match any of these. Its really weird because in my urls.py I have it mapped correctly (r'^admin/', include(admin.site.urls)), I have all the required middleware enabled and have these in my installed apps 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', anyone have any idea? Thanks.

    Read the article

  • django: How to make one form from multiple models containing foreignkeys

    - by Tim
    I am trying to make a form on one page that uses multiple models. The models reference each other. I am having trouble getting the form to validate because I cant figure out how to get the id of two of the models used in the form into the form to validate it. I used a hidden key in the template but I cant figure out how to make it work in the views My code is below: views: def the_view(request, a_id,): if request.method == 'POST': b_form= BForm(request.POST) c_form =CForm(request.POST) print "post" if b_form.is_valid() and c_form.is_valid(): print "valid" b_form.save() c_form.save() return HttpResponseRedirect(reverse('myproj.pro.views.this_page')) else: b_form= BForm() c_form = CForm() b_ide = B.objects.get(pk=request.b_id) id_of_a = A.objects.get(pk=a_id) return render_to_response('myproj/a/c.html', {'b_form':b_form, 'c_form':c_form, 'id_of_a':id_of_a, 'b_id':b_ide }) models class A(models.Model): name = models.CharField(max_length=256, null=True, blank=True) classe = models.CharField(max_length=256, null=True, blank=True) def __str__(self): return self.name class B(models.Model): aid = models.ForeignKey(A, null=True, blank=True) number = models.IntegerField(max_length=1000) other_number = models.IntegerField(max_length=1000) class C(models.Model): bid = models.ForeignKey(B, null=False, blank=False) field_name = models.CharField(max_length=15) field_value = models.CharField(max_length=256, null=True, blank=True) forms from mappamundi.mappa.models import A, B, C class BForm(forms.ModelForm): class Meta: model = B exclude = ('aid',) class CForm(forms.ModelForm): class Meta: model = C exclude = ('bid',) B has a foreign key reference to A, C has a foreign key reference to B. Since the models are related, I want to have the forms for them on one page, 1 submit button. Since I need to fill out fields for the forms for B and C & I dont want to select the id of B from a drop down list, I need to somehow get the id of the B form into the form so it will validate. I have a hidden field in the template, I just need to figure how to do it in the views

    Read the article

  • Querying many to many fields in django

    - by Hulk
    In the models there is a many to many fields as, from emp.models import Name def info(request): name = models.ManyToManyField(Name) And in emp.models the schema is as class Name(models.Model): name = models.CharField(max_length=512) def __unicode__(self): return self.name Now when i want to query a particular id say for ex: info= info.objects.filter(id=a) for i in info: logging.debug(i.name) //gives an error how should the query be to get the name Thanks..

    Read the article

  • Simple Observation in Django: How Can I Correctly Modify The `attrs` sent to __new__ of a Django Mod

    - by DGGenuine
    Hello, I'm a strong proponent of the observer pattern, and this is what I'd like to be able to do in my Django models.py: class AModel(Model): __metaclass__ = SomethingMagical @post_save(AnotherModel) @classmethod def observe_another_model_saved(klass, sender, instance, created, **kwargs): pass @pre_init('YetAnotherModel') @classmethod def observe_yet_another_model_initializing(klass, sender, *args, **kwargs): pass @post_delete('DifferentApp.SomeModel') @classmethod def observe_some_model_deleted(klass, sender, **kwargs): pass This would connect a signal with sender = the decorator's argument and receiver = the decorated method. Right now my signal connection code all exists in __init__.py which is okay, but a little unmaintainable. I want this code all in one place, the models.py file. Thanks to helpful feedback from the community I'm very close (I think.) (I'm using a metaclass solution instead of the class decorator solution in the previous question/answer because you can't set attributes on classmethods, which I need.) I am having a strange error I don't understand. At the end of my post are the contents of a models.py that you can pop into a fresh project/application to see the error. Set your database to sqlite and add the application to installed apps. This is the error: Validating models... Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 253, in validate raise CommandError("One or more models did not validate:\n%s" % error_text) django.core.management.base.CommandError: One or more models did not validate: local.myothermodel: 'my_model' has a relation with model MyModel, which has either not been installed or is abstract. I've indicated a few different things you can comment in/out to fix the error. First, if you don't modify the attrs sent to the metaclass's __new__, then the error does not arise. (Note even if you copy the dictionary element by element into a new dictionary, it still fails; only using the exact attrs dictionary works.) Second, if you reference the first model by class rather than by string, the error also doesn't arise regardless of what you do in __new__. I appreciate your help. I'll be githubbing the solution if and when it works. Maybe other people would enjoy a simplified way to use Django signals to observe application happenings. #models.py from django.db import models from django.db.models.base import ModelBase from django.db.models import signals import pdb class UnconnectedMethodWrapper(object): sender = None method = None signal = None def __init__(self, signal, sender, method): self.signal = signal self.sender = sender self.method = method def post_save(sender): return _make_decorator(signals.post_save, sender) def _make_decorator(signal, sender): def decorator(view): return UnconnectedMethodWrapper(signal, sender, view) return decorator class ConnectableModel(ModelBase): """ A meta class for any class that will have static or class methods that need to be connected to signals. """ def __new__(cls, name, bases, attrs): unconnecteds = {} ## NO WORK newattrs = {} for name, attr in attrs.iteritems(): if isinstance(attr, UnconnectedMethodWrapper): unconnecteds[name] = attr newattrs[name] = attr.method #replace the UnconnectedMethodWrapper with the method it wrapped. else: newattrs[name] = attr ## NO WORK # newattrs = {} # for name, attr in attrs.iteritems(): # newattrs[name] = attr ## WORKS # newattrs = attrs new = super(ConnectableModel, cls).__new__(cls, name, bases, newattrs) for name, unconnected in unconnecteds.iteritems(): _connect_signal(unconnected.signal, unconnected.sender, getattr(new, name), new._meta.app_label) return new def _connect_signal(signal, sender, receiver, default_app_label): # full implementation also accepts basestring as sender and will look up model accordingly signal.connect(sender=sender, receiver=receiver) class MyModel(models.Model): __metaclass__ = ConnectableModel @post_save('In my application this string matters') @classmethod def observe_it(klass, sender, instance, created, **kwargs): pass @classmethod def normal_class_method(klass): pass class MyOtherModel(models.Model): ## WORKS # my_model = models.ForeignKey(MyModel) ## NO WORK my_model = models.ForeignKey('MyModel')

    Read the article

  • How do I reference Django Model from another model

    - by user313943
    Im looking to create a view in the admin panel for a test program which logs Books, publishers and authors (as on djangoproject.com) I have the following two models defined. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title What I want to do, is change the Book model to reference the first_name of any authors and show this using admin.AdminModels. #Here is the admin model I've created. class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') # Author would in here list_filter = ('publication_date',) date_hierarchy = 'publication_date' ordering = ('-publication_date',) fields = ('title', 'authors', 'publisher', 'publication_date') filter_horizontal = ('authors',) raw_id_fields = ('publisher',) As I understand it, you cannot have two ForeignKeys in the same model. Can anyone give me an example of how to do this? I've tried loads of different things and its been driving me mad all day. Im pretty new to Python/Django. Just to be clear - I'd simply like the Author(s) First/Last name to appear alongside the book title and publisher name. Thanks

    Read the article

  • Django - Form validation error

    - by Igor G.
    Hello, I have a model like this: class Entity(models.Model): entity_name = models.CharField(max_length=100) entity_id = models.CharField(max_length=30, primary_key=True) entity_parent = models.CharField(max_length=100, null=True) photo_id = models.CharField(max_length=100, null=True) username = models.CharField(max_length=100, null=True) date_matched_on = models.CharField(max_length=100, null=True) status = models.CharField(max_length=30, default="Checked In") def __unicode__(self): return self.entity_name class Meta: app_label = 'match' ordering = ('entity_name','date_matched_on') verbose_name_plural='Entities' I also have a view like this: def photo_match(request): ''' performs an update in the db when a user chooses a photo ''' form = EntityForm(request.POST) form.save() And my EntityForm looks like this: class EntityForm(ModelForm): class Meta: model = Entity My template's form returns a POST back to the view with the following values: {u'username': [u'admin'], u'entity_parent': [u'PERSON'], u'entity_id': [u'152097'], u'photo_id': [u'2200734'], u'entity_name': [u'A.J. McLean'], u'status': [u'Checked Out'], u'date_matched_on': [u'5/20/2010 10:57 AM']} And form.save() throws this error: Exception in photo_match: The Entity could not be changed because the data didn't validate. I have been trying to figure out why this is happening, but cannot pinpoint the exact problem. I can change my Entities in the admin interface just fine. If anybody has a clue about this I would greatly appreciate it! Thanks, Igor

    Read the article

  • Annotate over Multi-table Inheritance in Django

    - by user341584
    I have a base LoggedEvent model and a number of subclass models like follows: class LoggedEvent(models.Model): user = models.ForeignKey(User, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class AuthEvent(LoggedEvent): good = models.BooleanField() username = models.CharField(max_length=12) class LDAPSearchEvent(LoggedEvent): type = models.CharField(max_length=12) query = models.CharField(max_length=24) class PRISearchEvent(LoggedEvent): type = models.CharField(max_length=12) query = models.CharField(max_length=24) Users generate these events as they do the related actions. I am attempting to generate a usage-report of how many of each event-type each user has caused in the last month. I am struggling with Django's ORM and while I am close I am running into a problem. Here is the query code: ef usage(request): # Calculate date range today = datetime.date.today() month_start = datetime.date(year=today.year, month=today.month - 1, day=1) month_end = datetime.date(year=today.year, month=today.month, day=1) - datetime.timedelta(days=1) # Search for how many LDAP events were generated per user, last month baseusage = User.objects.filter(loggedevent__timestamp__gte=month_start, loggedevent__timestamp__lte=month_end) ldapusage = baseusage.exclude(loggedevent__ldapsearchevent__id__lt=1).annotate(count=Count('loggedevent__pk')) authusage = baseusage.exclude(loggedevent__authevent__id__lt=1).annotate(count=Count('loggedevent__pk')) return render_to_response('usage.html', { 'ldapusage' : ldapusage, 'authusage' : authusage, }, context_instance=RequestContext(request)) Both ldapusage and authusage are both a list of users, each user annotated with a .count attribute which is supposed to represent how many particular events that user generated. However in both lists, the .count attributes are the same value. Infact the annotated 'count' is equal to how many events that user generated, regardless of type. So it would seem that my specific authusage = baseusage.exclude(loggedevent__authevent__id__lt=1) isn't excluding by subclass. I have tried id_lt=1, id_isnull=True, and others. Halp.

    Read the article

  • Matching 3 out 5 fields - Django

    - by RadiantHex
    Hi folks, I'm finding this a bit tricky! Maybe someone can help me on this one I have the following model: class Unicorn(models.Model): horn_length = models.IntegerField() skin_color = models.CharField() average_speed = models.IntegerField() magical = models.BooleanField() affinity = models.CharField() I would like to search for all similar unicorns having at least 3 fields in common. Is it too tricky? Or is it doable?

    Read the article

  • Making only a part of model field available in Django

    - by Hellnar
    Hello I have a such model: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) class Profile(models.Model): user = models.ForeignKey(User) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class FrontPage(models.Model): female = models.ForeignKey(User,related_name="female") male = models.ForeignKey(User,related_name="male") Once I attempt to add a new FrontPage object via the Admin page, I can select "Female" profiles for the male field of FrontPage, how can I restrict that? Thanks

    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

  • Django Threaded Commenting System

    - by Yasin Ozel
    (and sorry for my english) I am learning Python and Django. Now, my challange is developing threaded generic comment system. There is two models, Post and Comment. -Post can be commented. -Comment can be commented. (endless/threaded) -Should not be a n+1 query problem in system. (No matter how many comments, should not increase the number of queries) My current models are like this: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() child = generic.GenericRelation( 'Comment', content_type_field='parent_content_type', object_id_field='parent_object_id' ) class Comment(models.Model): content = models.TextField() child = generic.GenericRelation( 'self', content_type_field='parent_content_type', object_id_field='parent_object_id' ) parent_content_type = models.ForeignKey(ContentType) parent_object_id = models.PositiveIntegerField() parent = generic.GenericForeignKey( "parent_content_type", "parent_object_id") Are my models right? And how can i get all comment (with hierarchy) of post, without n+1 query problem? Note: I know mttp and other modules but I want to learn this system. Edit: I run "Post.objects.all().prefetch_related("child").get(pk=1)" command and this gave me post and its child comment. But when I wanna get child command of child command a new query is running. I can change command to ...prefetch_related("child__child__child...")... then still a new query running for every depth of child-parent relationship. Is there anyone who has idea about resolve this problem?

    Read the article

  • Django cannot find my templatetags, even though it's in INSTALLED_APPS and has a __init__.py

    - by Vivian Short
    I just installed django-compress (http://code.google.com/p/django-compress) into /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/compress. I added 'compress' to INSTALLED_APPS. In my template file, I wrote {% load compressed %}. I got the error: 'compressed' is not a valid tag library: Could not load template library from django.templatetags.compressed, No module named compressed I verified that there is an init.py in compress, as well as in compress/templatetags/. I tried putting the compress directory into PYTHONPATH. I ran python and wrote "import compress" and that worked. Your suggestions would be very appreciated! What else can I try?

    Read the article

  • Django updating db for selected ids

    - by Hulk
    In the following, New row values in DB are 6,8.They are the ids of a field I want to update these some other fields in the table based on these values row_newid=request.POST.get('row_updated_id') //Array row_newdata=request.POST.get('row_updated_data') //Array for newrow in row_newid: //how to update row_newdata for newrow values No for all the ids in row_newid how do i update row_newdata. row_newdata has the values 'a' and 'b' for example. thanks....

    Read the article

  • Auto filling polymorphic table on save or on delete in django

    - by Mo J. Mughrabi
    Hi, Am working on an project in which I made an app "core" it will contain some of the reused models across my projects, most of those are polymorphic models (Generic content types) and will be linked to different models. Example below am trying to create audit model and will be linked to several models which may require auditing. This is the polls/models.py from django.db import models from django.contrib.auth.models import User from core.models import * from django.contrib.contenttypes import generic class Poll(models.Model): ## TODO: Document question = models.CharField(max_length=300) question_slug=models.SlugField(editable=False) start_poll_at = models.DateTimeField(null=True) end_poll_at = models.DateTimeField(null=True) is_active = models.BooleanField(default=True) audit_obj=generic.GenericRelation(Audit) def __unicode__(self): return self.question class Choice(models.Model): ## TODO: Document choice = models.CharField(max_length=200) poll=models.ForeignKey(Poll) audit_obj=generic.GenericRelation(Audit) class Vote(models.Model): ## TODO: Document choice=models.ForeignKey(Choice) Ip_Address=models.IPAddressField(editable=False) vote_at=models.DateTimeField("Vote at", editable=False) here is the core/modes.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Audit(models.Model): ## TODO: Document # Polymorphic model using generic relation through DJANGO content type created_at = models.DateTimeField("Created at", auto_now_add=True) created_by = models.ForeignKey(User, db_column="created_by", related_name="%(app_label)s_%(class)s_y+") updated_at = models.DateTimeField("Updated at", auto_now=True) updated_by = models.ForeignKey(User, db_column="updated_by", null=True, blank=True, related_name="%(app_label)s_%(class)s_y+") content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(unique=True) content_object = generic.GenericForeignKey('content_type', 'object_id') and here is polls/admin.py from django.core.context_processors import request from polls.models import Poll, Choice from core.models import * from django.contrib import admin class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): inlines = [ChoiceInline] admin.site.register(Poll, PollAdmin) Am quite new to django, what am trying to do here, insert a record in audit when a record is inserted in polls and then update that same record when a record is updated in polls.

    Read the article

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