Search Results

Search found 21 results on 1 pages for 'autofield'.

Page 1/1 | 1 

  • django admin gives warning "Field 'X' doesn't have a default value"

    - by noam
    I have created two models out of an existing legacy DB , one for articles and one for tags that one can associate with articles: class Article(models.Model): article_id = models.AutoField(primary_key=True) text = models.CharField(max_length=400) class Meta: db_table = u'articles' class Tag(models.Model): tag_id = models.AutoField(primary_key=True) tag = models.CharField(max_length=20) article=models.ForeignKey(Article) class Meta: db_table = u'article_tags' I want to enable adding tags for an article from the admin interface, so my admin.py file looks like this: from models import Article,Tag from django.contrib import admin class TagInline(admin.StackedInline): model = Tag class ArticleAdmin(admin.ModelAdmin): inlines = [TagInline] admin.site.register(Article,ArticleAdmin) The interface looks fine, but when I try to save, I get: Warning at /admin/webserver/article/382/ Field 'tag_id' doesn't have a default value

    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

  • Filter across three tables using Django

    - by Vanessa MacDougal
    I have 3 django models, where the first has a foreign key to the second, and the second has a foreign key to the third. Like this: class Book(models.Model): year_published = models.IntField() author = models.ForeignKey(Author) class Author(models.Model): author_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) agent = models.ForeignKey(LitAgent) class LitAgent(models.Model): agent_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) I want to ask for all the literary agents whose authors had books published in 2006, for example. How can I do this in Django? I have looked at the documentation about filters and QuerySets, and don't see an obvious way. Thanks.

    Read the article

  • Django ForeignKey TemplateSyntaxError and ProgrammingError

    - by Daniel Garcia
    This is are my models i want to relate. i want for collection to appear in the form of occurrence. class Collection(models.Model): id = models.AutoField(primary_key=True, null=True) code = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True) collection_name = models.CharField(max_length=100) def __unicode__(self): return self.collection_name class Meta: db_table = u'collection' ordering = ('collection_name',) class Occurrence(models.Model): id = models.AutoField(primary_key=True, null=True) reference = models.IntegerField(null=True, blank=True, editable=False) collection = models.ForeignKey(Collection, null=True, blank=True, unique=True), modified = models.DateTimeField(null=True, blank=True, auto_now=True) class Meta: db_table = u'occurrence' Every time i go to check the Occurrence object i get this error TemplateSyntaxError at /admin/hotiapp/occurrence/ Caught an exception while rendering: column occurrence.collection_id does not exist LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc.. And every time i try to add a new occurrence object i get this error ProgrammingError at /admin/hotiapp/occurrence/add/ column occurrence.collection_id does not exist LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll... What am i doing wrong? or how does ForeignKey works?

    Read the article

  • Migration for creating and deleting model in South

    - by Almad
    I've created a model and created initial migration for it: db.create_table('tvguide_tvguide', ( ('id', models.AutoField(primary_key=True)), ('date', models.DateField(_('Date'), auto_now=True, db_index=True)), )) db.send_create_signal('tvguide', ['TVGuide']) models = { 'tvguide.tvguide': { 'channels': ('models.ManyToManyField', ["orm['tvguide.Channel']"], {'through': "'ChannelInTVGuide'"}), 'date': ('models.DateField', ["_('Date')"], {'auto_now': 'True', 'db_index': 'True'}), 'id': ('models.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['tvguide'] Now, I'd like to drop it: db.drop_table('tvguide_tvguide') However, I have also deleted corresponding model. South (at least 0.6.2) is however trying to access it: (venv)[almad@eva-03 project]$ ./manage.py migrate tvguide Running migrations for tvguide: - Migrating forwards to 0002_removemodels. > tvguide: 0001_initial Traceback (most recent call last): File "./manage.py", line 27, in <module> execute_from_command_line() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/management/commands/migrate.py", line 91, in handle skip = skip, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 581, in migrate_app result = run_forwards(mapp, [mname], fake=fake, db_dry_run=db_dry_run, verbosity=verbosity) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 388, in run_forwards verbosity = verbosity, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 287, in run_migrations orm = klass.orm File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 62, in __get__ self.orm = FakeORM(*self._args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 45, in FakeORM _orm_cache[args] = _FakeORM(*args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 106, in __init__ self.models[name] = self.make_model(app_name, model_name, data) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 307, in make_model tuple(map(ask_for_it_by_name, bases)), File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 23, in ask_for_it_by_name ask_for_it_by_name.cache[name] = _ask_for_it_by_name(name) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 17, in _ask_for_it_by_name return getattr(module, bits[-1]) AttributeError: 'module' object has no attribute 'TVGuide' Is there a way around?

    Read the article

  • Default value for hidden field in Django model

    - by Daniel Garcia
    I have this Model: class Occurrence(models.Model): id = models.AutoField(primary_key=True, null=True) reference = models.IntegerField(null=True, editable=False) def save(self): self.collection = self.id super(Occurrence, self).save() I want for the reference field to be hidden and at the same time have the same value as id. This code works if the editable=True but if i want to hide it it doesnt change the value of reference. how can i fix that?

    Read the article

  • Django: Only one of two fields can be filled in

    - by Giovanni Di Milia
    I have this model: class Journals(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField("Code", max_length=50) name = models.CharField("Name", max_length=2000) publisher = models.CharField("Publisher", max_length=2000) price_euro = models.CharField("Euro", max_length=2000) price_dollars = models.CharField("Dollars", max_length=2000) Is there a way to let people fill out either price_euro or price_dollars? I do know that the best way to solve the problem is to have only one field and another table that specify the currency, but I have constraints and I cannot modify the DB. Thanks!

    Read the article

  • Django Forms, Foreign Key and Initial retuen all associated values

    - by gramware
    I a working with Django forms. The issue I have is that Foreign Key fields and those using initial take all associated entries (all records associated with that record other then the one entry i wanted e.g instead of getting a primary key, i get the primary key, post subject, post body and all other values attributed with that record). The form and the other associated queries still work well, but this behaviour is clogging my database. How do i get the specific field i want instead of all records. An example of my models is here: A form field for childParentId returns postID, postSubject and postBody instead of postID alone. Also form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), }) returns all records related to postID. class forum(models.Model): postID = models.AutoField(primary_key=True) postSubject = models.CharField(max_length=25) postBody = models.TextField() postPoster = models.ForeignKey(UserProfile) postDate = models.DateTimeField(auto_now_add=True) child = models.BooleanField() childParentId = models.ForeignKey('self',blank=True, null=True) deleted = models.BooleanField() def __unicode__(self): return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID

    Read the article

  • Django Forms, Foreign Key and Initial return all associated values

    - by gramware
    I a working with Django forms. The issue I have is that Foreign Key fields and those using initial take all associated entries (all records associated with that record other then the one entry i wanted e.g instead of getting a primary key, i get the primary key, post subject, post body and all other values attributed with that record). The form and the other associated queries still work well, but this behaviour is clogging my database. How do i get the specific field i want instead of all records. An example of my models is here: A form field for childParentId returns postID, postSubject and postBody instead of postID alone. Also form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), }) returns all records related to postID. class forum(models.Model): postID = models.AutoField(primary_key=True) postSubject = models.CharField(max_length=25) postBody = models.TextField() postPoster = models.ForeignKey(UserProfile) postDate = models.DateTimeField(auto_now_add=True) child = models.BooleanField() childParentId = models.ForeignKey('self',blank=True, null=True) deleted = models.BooleanField() def __unicode__(self): return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID

    Read the article

  • Django South Foreign Keys referring to pks with Custom Fields

    - by Rory Hart
    I'm working with a legacy database which uses the MySQL big int so I setup a simple custom model field to handle this: class BigAutoField(models.AutoField): def get_internal_type(self): return "BigAutoField" def db_type(self): return 'bigint AUTO_INCREMENT' # Note this won't work with Oracle. This works fine with django south for the id/pk fields (mysql desc "| id | bigint(20) | NO | PRI | NULL | auto_increment |") but the ForeignKey fields in other models the referring fields are created as int(11) rather than bigint(20). I assume I have to add an introspection rule to the BigAutoField but there doesn't seem to be a mention of this sort of rule in the documentation (http://south.aeracode.org/docs/customfields.html). Update: Currently using Django 1.1.1 and South 0.6.2

    Read the article

  • Default value for field in Django model

    - by Daniel Garcia
    Suppose I have a model: class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.IntegerField(max_length=10) b = models.CharField(max_length=7) Currently I am using the default admin to create/edit objects of this type. How do I set the field 'a' to have the same number as id? (default=???) Other question Suppose I have a model: event_date = models.DateTimeField( null=True) year = models.IntegerField( null=True) month = models.CharField(max_length=50, null=True) day = models.IntegerField( null=True) How can i set the year, month and day fields by default to be the same as event_date field?

    Read the article

  • Can't set up image upload in Django

    - by culebrón
    I can't understand what's not working here: 1) settings MEDIA_ROOT = '/var/www/satel/media' MEDIA_URL = 'http://media.satel.culebron' ADMIN_MEDIA_PREFIX = '/media/' 2) models class Photo(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length = 200) desc = models.TextField(max_length = 1000) img = models.ImageField(upload_to = 'upload') 3) access rights: drwxr-xrwx 3 culebron culebron 4.0K 2010-04-14 21:13 media drwxr-xrwx 2 culebron culebron 4.0K 2010-04-14 19:04 upload 4) SQL: CREATE TABLE "photos_photo" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(200) NOT NULL, "desc" text NOT NULL, "img" varchar(100) NOT NULL ); 4) run Django test server as myself. 5) result: SuspiciousOperation at /admin/photos/author/add/ Attempted access to '/var/www/satel/upload/OpenStreetMap.png' denied. Not a PIL & jpeg issue, seems not to be access rights issue. But what's wrong?

    Read the article

  • django models objects filter

    - by ha22109
    Hello All, I have a model 'Test' ,in which i have 2 foreignkey models.py class Test(models.Model): id =models.Autofield(primary_key=True) name=models.ForeignKey(model2) login=models.ForeignKey(model1) status=models.CharField(max_length=200) class model1(models.Model): id=models.CharField(primary_key=True) . . is_active=models.IntergerField() class model2(model.Model): id=models.ForeignKey(model1) . . status=model.CharField(max_length=200) When i add object in model 'Test' , if i select certain login then only the objects related to that objects(model2) should be shown in field 'name'.How can i achieve this.THis will be runtime as if i change the login field value the objects in name should also change.

    Read the article

  • Django save, column specified twice

    - by realshadow
    Hey, I would like to save a modified model, but I get Programming error - that a field is specified twice. class ProductInfo(models.Model): product_info_id = models.AutoField(primary_key=True) language_id = models.IntegerField() product_id = models.IntegerField() description = models.TextField(blank=True) status = models.IntegerField() model = models.CharField(max_length=255, blank=True) label = models.ForeignKey(Category_info, verbose_name = 'Category_info', db_column = 'language_id', to_field = 'node_id', null = True) I get this error because the foreign key uses as db_column language_id. If I will delete it, my object will be saved properly. I dont quite understand whats going on and since I have defined almost all of my models this way, I fear its totally wrong or maybe I just missunderstood it... Any ideas? Regards

    Read the article

  • Django db encoding

    - by realshadow
    Hey, I have a little problem with encoding. The data in db is ok, when I select the data in php its ok. Problem comes when I get the data and try to print it in the template, I get - Å port instead of Šport, etc. Everything is set to utf-8 - in settings.py, meta tags in template, db table and I even have unicode method specified for the model, but nothing seems to work. I am getting pretty hopeless here... Here is some code: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() class Meta: db_table = 'objtree_labels' def __unicode__(self): return self.label I have even tried with return u"%s" % self.label. Here is the view: def categories_list(request): categories_list = Category.objects.filter(parent_id = 1, status = 1) paginator = Paginator(categories_list, 10) try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 try: categories = paginator.page(page) except (EmptyPage, InvalidPage): categories = paginator.page(paginator.num_pages) return render_to_response('categories_list.html', {'categories': categories}) Maybe I am just blind and/or stupid, but it just doesnt work. So any help is appreciated, thanks in advance. Regards

    Read the article

  • foreignkey problem

    - by realshadow
    Hey, Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = models.CharField(max_length = 45) lft = models.IntegerField(max_length = 20) rgt = models.IntegerField(max_length = 20) depth = models.IntegerField(max_length = 20) added_on = models.DateTimeField(auto_now = True) updated_on = models.DateTimeField(auto_now = True) status = models.IntegerField(max_length = 20) node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id' The important part is the foreignkey. When I try: Category.objects.filter(type_id = 15, parent_id = offset, status = 1) I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model) Here it is: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1. Here is what I want in sql: SELECT c.*, ci.* FROM category c JOIN category_info ci ON (c.node_id = ci.node_id) WHERE c.type_id = 15 AND c.parent_id = 50 AND ci.type_id = 1 Any help is GREATLY appreciated. Regards

    Read the article

  • Django - foreignkey problem

    - by realshadow
    Hey, Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = models.CharField(max_length = 45) lft = models.IntegerField(max_length = 20) rgt = models.IntegerField(max_length = 20) depth = models.IntegerField(max_length = 20) added_on = models.DateTimeField(auto_now = True) updated_on = models.DateTimeField(auto_now = True) status = models.IntegerField(max_length = 20) node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id' The important part is the foreignkey. When I try: Category.objects.filter(type_id = type_g.type_id, parent_id = offset, status = 1) I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model) Here it is: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1. Here is what I want in sql: SELECT n.*, l.* FROM objtree_nodes n JOIN objtree_labels l ON (n.node_id = l.node_id) WHERE n.type_id = 15 AND n.parent_id = 50 AND l.type_id = 1 Any help is GREATLY appreciated. Regards

    Read the article

  • Matching blank entries in django queryset for optional field with corresponding ones in a required

    - by gramware
    I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments. Here is my views.py def forums(request ): post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate')) user = UserProfile.objects.get(pk=request.session['_auth_user_id']) newpostform = PostForm(request.POST) deletepostform = PostDeleteForm(request.POST) DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId')) readform = ReadForumForm(request.POST) comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))) if request.user.is_staff== True : staff = 1 else: staff = 0 staffis = 1 if newpostform.is_valid(): topic = request.POST['postSubject'] poster = request.POST['postPoster'] newpostform.save() return HttpResponseRedirect('/forums') else: newpostform = PostForm(initial = {'postPoster':user.id}) if request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId'))) if request.method == 'POST': delpostformset = DelPostFormSet(request.POST) if delpostformset.is_valid(): delpostformset.save() return HttpResponseRedirect('/forums') else: delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0')) """if readform.is_valid(): user=get_object_or_404(UserProfile.objects.all()) readform.save() else: readform = ReadForumForm()""" post= zip( post_list,comments, delpostformset.forms) paginator = Paginator(post, 10) # Show 10 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: post = paginator.page(page) except (EmptyPage, InvalidPage): post = paginator.page(paginator.num_pages) return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user, },context_instance = RequestContext( request )) I realised that the issue was with the comments queryset comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))) which will only returns values for posts that have comments. so i now need a way to return 0 comments when a value in post-list post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate')) does not have any comments (optional field). Here is my models.py class forum(models.Model): postID = models.AutoField(primary_key=True) postSubject = models.CharField(max_length=100) postBody = models.TextField() postPoster = models.ForeignKey(UserProfile) postDate = models.DateTimeField(auto_now_add=True) child = models.BooleanField() childParentId = models.ForeignKey('self',blank=True, null=True) deleted = models.BooleanField() def __unicode__(self): return u' %d' % ( self.postID)

    Read the article

  • Django: CharField with fixed length, how?

    - by Giovanni Di Milia
    Hi everybody, I wold like to have in my model a CharField with fixed length. In other words I want that only a specified length is valid. I tried to do something like volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me an error (it seems that I can use both max_length and min_length at the same time). Is there another quick way? Thanks EDIT: Following the suggestions of some people I will be a bit more specific: My model is this: class Volume(models.Model): vid = models.AutoField(primary_key=True) jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal") volumenumber = models.CharField('Volume Number') date_publication = models.CharField('Date of Publication', max_length=6, blank=True) class Meta: db_table = u'volume' verbose_name = "Volume" ordering = ['jid', 'volumenumber'] unique_together = ('jid', 'volumenumber') def __unicode__(self): return (str(self.jid) + ' - ' + str(self.volumenumber)) What I want is that the volumenumber must be exactly 4 characters. I.E. if someone insert '4b' django gives an error because it expects a string of 4 characters. So I tried with volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me this error: Validating models... Unhandled exception in thread started by <function inner_run at 0x70feb0> Traceback (most recent call last): File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors self._populate() File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate self.load_app(app_name, True) File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app models = import_module('.models', app_name) File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module> class Volume(models.Model): File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) TypeError: __init__() got an unexpected keyword argument 'min_length' That obviously doesn't appear if I use only "max_length" OR "min_length". I read the documentation on the django web site and it seems that I'm right (I cannot use both together) so I'm asking if there is another way to solve the problem. Thanks again

    Read the article

  • django image upload forms

    - by gramware
    I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files my models class UserProfile(User): """user with app settings. """ DESIGNATION_CHOICES=( ('ADM', 'Administrator'), ('OFF', 'Club Official'), ('MEM', 'Ordinary Member'), ) onames = models.CharField(max_length=30, blank=True) phoneNumber = models.CharField(max_length=15) regNo = models.CharField(max_length=15) designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES) image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True) course = models.CharField(max_length=30, blank=True, null=True) timezone = models.CharField(max_length=50, default='Africa/Nairobi') smsCom = models.BooleanField() mailCom = models.BooleanField() fbCom = models.BooleanField() objects = UserManager() #def __unicode__(self): # return '%s %s ' % (User.Username, User.is_staff) def get_absolute_url(self): return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id) def get_download_url(self): return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name) ... class reports(models.Model): repID = models.AutoField(primary_key=True) repSubject = models.CharField(max_length=100) repRecepients = models.ManyToManyField(UserProfile) repPoster = models.ForeignKey(UserProfile,related_name='repposter') repDescription = models.TextField() repPubAccess = models.BooleanField() repDate = models.DateField() report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' ) deleted = models.BooleanField() def __unicode__(self): return u'%s ' % (self.repSubject) my forms from django import forms from django.http import HttpResponse from cms.models import * from django.contrib.sessions.models import Session from django.forms.extras.widgets import SelectDateWidget class UserProfileForm(forms.ModelForm): class Meta: model= UserProfile exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups') ... class reportsForm(forms.ModelForm): repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput()) repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here') repDate = forms.DateField(widget=SelectDateWidget()) class Meta: model = reports exclude = ('deleted') my views @login_required def reports_media(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) if request.user.is_staff== True: repmedform = reportsForm(request.POST, request.FILES) if repmedform.is_valid(): repmedform.save() repmedform = reportsForm(initial = {'repPoster':user.id,}) else: repmedform = reportsForm(initial = {'repPoster':user.id,}) return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()}) else: return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()}) ... @login_required def settingchng(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) form = UserProfileForm(instance = user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance = user) if form.is_valid(): form.save() return HttpResponseRedirect('/settings/') else: form = UserProfileForm(instance = user) if request.user.is_staff== True: return render_to_response('staffsettingschange.html', {'form': form}) else: return render_to_response('settingschange.html', {'form': form}) ... @login_required def useradd(request): if request.method == 'POST': form = UserAddForm(request.POST,request.FILES ) if form.is_valid(): password = request.POST['password'] request.POST['password'] = set_password(password) form.save() else: form = UserAddForm() return render_to_response('staffadduser.html', {'form':form}) Example of my templates {% if form.errors %} <ol> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p> </H3> {% endfor %} </ol> {% endif %} <form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm"> {{ repfrm.as_p }} <input type="submit" value="Submit" /> </form>

    Read the article

  • UnicodeEncodeError when uploading files in Django admin

    - by Samuel Linde
    Note: I asked this question on StackOverflow, but I realize this might be a more proper place to ask this kind of question. I'm trying to upload a file called 'Testaråäö.txt' via the Django admin app. I'm running Django 1.3.1 with Gunicorn 0.13.4 and Nginx 0.7.6.7 on a Debian 6 server. Database is PostgreSQL 8.4.9. Other Unicode data is saved to the database with no problem, so I guess the problem must be with the filesystem somehow. I've set http { charset utf-8; } in my nginx.conf. LC_ALL and LANG is set to 'sv_SE.UTF-8'. Running 'locale' verifies this. I even tried setting LC_ALL and LANG in my nginx init script just to make sure locale is set properly. Here's the traceback: Traceback (most recent call last): File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/handlers/base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 307, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 93, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/views/decorators/cache.py", line 79, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 197, in inner return view(request, *args, **kwargs) File "/srv/django/letebo/app/cms/admin.py", line 81, in change_view return super(PageAdmin, self).change_view(request, obj_id) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 28, in _wrapper return bound_func(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 93, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 24, in bound_func return func(self, *args2, **kwargs2) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/transaction.py", line 217, in inner res = func(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 985, in change_view self.save_formset(request, form, formset, change=True) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 677, in save_formset formset.save() File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 482, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 613, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 717, in save_new obj.save() File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 460, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 504, in save_base self.save_base(cls=parent, origin=org, using=using) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 543, in save_base for f in meta.local_fields if not isinstance(f, AutoField)] File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/fields/files.py", line 255, in pre_save file.save(file.name, file, save=False) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/fields/files.py", line 92, in save self.name = self.storage.save(name, content) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 48, in save name = self.get_available_name(name) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 74, in get_available_name while self.exists(name): File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 218, in exists return os.path.exists(self.path(name)) File "/srv/.virtualenvs/letebo/lib/python2.6/genericpath.py", line 18, in exists st = os.stat(path) UnicodeEncodeError: 'ascii' codec can't encode characters in position 52-54: ordinal not in range(128) I tried running Gunicorn with debugging turned on, and the file uploads without any problem at all. I suppose this must mean that the issue is with Nginx. Still beats me where to look, though. Here are the raw response headers from Gunicorn and Nginx, if it makes any sense: Gunicorn: HTTP/1.1 302 FOUND Server: gunicorn/0.13.4 Date: Thu, 09 Feb 2012 14:50:27 GMT Connection: close Transfer-Encoding: chunked Expires: Thu, 09 Feb 2012 14:50:27 GMT Vary: Cookie Last-Modified: Thu, 09 Feb 2012 14:50:27 GMT Location: http://my-server.se:8000/admin/cms/page/15/ Cache-Control: max-age=0 Content-Type: text/html; charset=utf-8 Set-Cookie: messages="yada yada yada"; Path=/ Nginx: HTTP/1.1 500 INTERNAL SERVER ERROR Server: nginx/0.7.67 Date: Thu, 09 Feb 2012 14:50:57 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: close Vary: Cookie 500 UPDATE: Both locale.getpreferredencoding() and sys.getfilesystemencoding() outputs 'UTF-8'. locale.getdefaultlocale() outputs ('sv_SE', 'UTF8'). This seem correct to me, so I'm still not sure why I keep getting these errors.

    Read the article

1