Search Results

Search found 10827 results on 434 pages for 'django fields'.

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

  • 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

  • django-admin - how to modify ModelAdmin to create multiple objects at once?

    - by skrobul
    let's assume that I have very basic model class Message(models.Model): msg = models.CharField(max_length=30) this model is registered with admin module: class MessageAdmin(admin.ModelAdmin): pass admin.site.register(Message, MessageAdmin) Currently when I go into the admin interface, after clicking "Add message" I have only one form where I can enter the msg. I would like to have multiple forms (formset perhaps) on the "Add page" so I can create multiple messages at once. It's really annoying having to click "Save and add another" every single time. Ideally I would like to achieve something like InlineModelAdmin but it turns out that you can use it only for the models that are related to the object which is edited. What would you recommend to use to resolve this problem?

    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 models query

    - by Hulk
    Code: class criteria(models.Model): details = models.CharField(max_length = 512) Headerid = models.ForeignKey(Header) def __unicode__(self): return self.id() the details corresponds to a textarea in the UI and a validation is done for 512 characters but when this is saved. /home/project/django/django/core/handlers/base.py in get_response, line 109 Is this any thing related with schema or number of characters entered from UI

    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

  • Tying in to Django Admin's Model History

    - by akdom
    The Setup: I'm working on a Django application which allows users to create an object in the database and then go back and edit it as much as they desire. Django's admin site keeps a history of the changes made to objects through the admin site. The Question: How do I hook my application in to the admin site's change history so that I can see the history of changes users make to their "content" ?

    Read the article

  • Manditory read-only fields in django

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

    Read the article

  • Django 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 crispy-forms inline forms

    - by abolotnov
    I'm trying to adopt crispy-forms and bootstrap and use as much of their functionality as possible instead of inventing something over and over again. Is there a way to have inline forms functionality with crispy-forms/bootstrap like django-admin forms have? Here is an example: class NewProjectForm(forms.Form): name = forms.CharField(required=True, label=_(u'???????? ???????'), widget=forms.TextInput(attrs={'class':'input-block-level'})) group = forms.ModelChoiceField(required=False, queryset=Group.objects.all(), label=_(u'?????? ????????'), widget=forms.Select(attrs={'class':'input-block-level'})) description = forms.CharField(required=False, label=_(u'???????? ???????'), widget=forms.Textarea(attrs={'class':'input-block-level'})) class Meta: model = Project fields = ('name','description','group') def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_class = 'horizontal-form' self.helper.form_action = 'submit_new_project' self.helper.layout = Layout( Field('name', css_class='input-block-level'), Field('group', css_class='input-block-level'), Field('description',css_class='input-block-level'), ) self.helper.add_input(Submit('submit',_(u'??????? ??????'))) self.helper.add_input(Submit('cancel',_(u'? ?????????'))) super(NewProjectForm, self).__init__(*args, **kwargs) it will display a decent form: How do I go about adding a form that basically represents this model: class Link(models.Model): name = models.CharField(max_length=255, blank=False, null=False, verbose_name=_(u'????????')) url = models.URLField(blank=False, null=False, verbose_name=_(u'??????')) project = models.ForeignKey('Project') So there will be a project and name/url links and way to add many, like same thing is done in django-admin where you are able to add extra 'rows' with data related to your main model. On the sreenshot below you are able to fill out data for 'Question' object and below that you are able to add data for QuestionOption objects -you are able to click the '+' icon to add as many QuestionOptions as you want. I'm not looking for a way to get the forms auto-generated from models (that's nice but not the most important) - is there a way to construct a form that will let you add 'rows' of data like django-admin does?

    Read the article

  • ProgrammingError when aggregating over an annotated & grouped Django ORM query

    - by ento
    I'm trying to construct a query to get the "average, maximum, minimum number of items purchased by a single user". The data source is this simple sales record table: class SalesRecord(models.Model): id = models.IntegerField(primary_key=True) user_id = models.IntegerField() product_code = models.CharField() price = models.IntegerField() created_at = models.DateTimeField() A new record is inserted into this table for every item purchased by a user. Here's my attempt at building the query: q = SalesRecord.objects.all() q = q.values('user_id').annotate( # group by user and count the # of records count=Count('id'), # (= # of items) ).order_by() result = q.aggregate(Max('count'), Min('count'), Avg('count')) When I try to execute the code, a ProgrammingError is raised at the last line: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT sales_records.user_id AS user_id, COUNT(sales_records.`' at line 1") Django's error screen shows that the SQL is SELECT FROM (SELECT `sales_records`.`player_id` AS `player_id`, COUNT(`sales_records`.`id`) AS `count` FROM `sales_records` WHERE (`sales_records`.`created_at` >= %s AND `sales_records`.`created_at` <= %s ) GROUP BY `sales_records`.`player_id` ORDER BY NULL) subquery It's not selecting anything! Can someone please show me the right way to do this? Hacking Django I've found that clearing the cache of selected fields in django.db.models.sql.BaseQuery.get_aggregation() seems to solve the problem. Though I'm not really sure this is a fix or a workaround. @@ -327,10 +327,13 @@ # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. + self._aggregate_select_cache = None + self.aggregate_select_mask = None for alias, aggregate in self.aggregate_select.items(): if aggregate.is_summary: query.aggregate_select[alias] = aggregate - del obj.aggregate_select[alias] + if alias in obj.aggregate_select: + del obj.aggregate_select[alias] ... yields result: {'count__max': 267, 'count__avg': 26.2563, 'count__min': 1}

    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 model operating on a queryset

    - by jmoz
    I'm new to Django and somewhat to Python as well. I'm trying to find the idiomatic way to loop over a queryset and set a variable on each model. Basically my model depends on a value from an api, and a model method must multiply one of it's attribs by this api value to get an up-to-date correct value. At the moment I am doing it in the view and it works, but I'm not sure it's the correct way to achieve what I want. I have to replicate this looping elsewhere. Is there a way I can encapsulate the looping logic into a queryset method so it can be used in multiple places? I have this atm (I am using django-rest-framework): class FooViewSet(viewsets.ModelViewSet): model = Foo serializer_class = FooSerializer bar = # some call to an api def get_queryset(self): # Dynamically set the bar variable on each instance! foos = Foo.objects.filter(baz__pk=1).order_by('date') for item in foos: item.needs_bar = self.bar return items I would think something like so would be better: def get_queryset(self): bar = # some call to an api # Dynamically set the bar variable on each instance! return Foo.objects.filter(baz__pk=1).order_by('date').set_bar(bar) I'm thinking the api hit should be in the controller and then injected to instances of the model, but I'm not sure how you do this. I've been looking around querysets and managers but still can't figure it out nor decided if it's the best method to achieve what I want. Can anyone suggest the correct way to model this with django? Thanks.

    Read the article

  • Asynchronous daemon processing / ORM interaction with Django

    - by perrierism
    I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to achieve asynchrony is? Basically what I need to accomplish is taking a list of users in the db, querying a third party api and then making updates to user-profile rows for those users. As a daemon or background process. Doing this in series per user is easy, but it takes too long to be at all scalable. If the daemon is retrieving and updating the users through the ORM, how do I achieve processing 10-20 users at a time? I would use a standard threading / queue system for this but you can't thread interactions like models.User.objects.get(id=foo) ... Django itself is an asynchronous processing system which makes asynchronous ORM calls(?) for each request, so there should be a way to do it? I haven't found anything in the documentation so far. Cheers

    Read the article

  • Accessing updated M2M fields in overriden save() in django's admin

    - by Jonathan
    I'd like to use the user updated values of a ManyToManyField in a model's overriden save() method when I save an instance in admin. It turns out that by design, django does not update the M2M field before calling save(), but only after the save() is complete as part of the form save... How can I access the new values of this field in the override save() ?

    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 access data passed to form

    - by realshadow
    Hey, I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ChoiceField( choices = [ [group.node_id, group.name] for group in Objtree.objects.filter( type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), parent_id = 50 ).distinct()] + [[0, 'Add a new one'] ], widget = forms.Select( attrs = { 'id': 'group_select' } ) ) I would like to change the parent_id that is passed into the Objtree.objects.filter. As you can see I tried in the init function, as well with kwargs['initial']['parent_id'] and then calling it with self, but that doesnt work, since its out of scope... it was pretty much my last effort. I need to acccess it either trough the initial parameter or directly trough parent_id field, since it already holds its value (passed trough initial). Any help is appreciated, as I am running out of ideas.

    Read the article

  • django generic view update/create: update works but create raises IntegrityError

    - by smarber
    I'm using CreateView and UpdateView directely into urls.py of my application whose name is dydict. In the file forms.py I'm using ModelForm and I'm exluding a couple of fields from being shown, some of which sould be set when either creating or updating. So, as mentioned in the title, update part works but create part doesn't which is obvious because required fields that I have exluded are sent empty which is not allowed in my case. So the question here is, how should I do to fill exluded fields into the file forms.py so that I don't have to override CreateView? Thanks in advance.

    Read the article

  • Django admin.py missing field error

    - by user782400
    When I include 'caption', I get an error saying EntryAdmin.fieldsets[1][1]['fields']' refers to field 'caption' that is missing from the form In the admin.py; I have imported the classes from joe.models import Entry,Image Is that because my class from models.py is not getting imported properly ? Need help in resolving this issue. Thanks. models.py class Image(models.Model): image = models.ImageField(upload_to='joe') caption = models.CharField(max_length=200) imageSrc = models.URLField(max_length=200) user = models.CharField(max_length=20) class Entry(models.Model): image = models.ForeignKey(Image) mimeType = models.CharField(max_length=20) name = models.CharField(max_length=200) password = models.URLField(max_length=50) admin.py class EntryAdmin(admin.ModelAdmin): fieldsets = [ ('File info', {'fields': ['name','password']}), ('Upload image', {'fields': ['image','caption']})] list_display = ('name', 'mimeType', 'password') admin.site.register(Entry, EntryAdmin) admin.site.register(Image)

    Read the article

  • Login URL using authentication information in Django

    - by fuSi0N
    I'm working on a platform for online labs registration for my university. Login View [project views.py] from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib import auth def index(request): return render_to_response('index.html', {}, context_instance = RequestContext(request)) def login(request): if request.method == "POST": post = request.POST.copy() if post.has_key('username') and post.has_key('password'): usr = post['username'] pwd = post['password'] user = auth.authenticate(username=usr, password=pwd) if user is not None and user.is_active: auth.login(request, user) if user.get_profile().is_teacher: return HttpResponseRedirect('/teachers/'+user.username+'/') else: return HttpResponseRedirect('/students/'+user.username+'/') else: return render_to_response('index.html', {'msg': 'You don\'t belong here.'}, context_instance = RequestContext(request) return render_to_response('login.html', {}, context_instance = RequestContext(request)) def logout(request): auth.logout(request) return render_to_response('index.html', {}, context_instance = RequestContext(request)) URLS #========== PROJECT URLS ==========# urlpatterns = patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }), (r'^admin/', include(admin.site.urls)), (r'^teachers/', include('diogenis.teachers.urls')), (r'^students/', include('diogenis.students.urls')), (r'^login/', login), (r'^logout/', logout), (r'^$', index), ) #========== TEACHERS APP URLS ==========# urlpatterns = patterns('', (r'^(?P<username>\w{0,50})/', labs), ) The login view basically checks whether the logged in user is_teacher [UserProfile attribute via get_profile()] and redirects the user to his profile. Labs View [teachers app views.py] from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.models import User from accounts.models import * from labs.models import * def user_is_teacher(user): return user.is_authenticated() and user.get_profile().is_teacher @user_passes_test(user_is_teacher, login_url="/login/") def labs(request, username): q1 = User.objects.get(username=username) q2 = u'%s %s' % (q1.last_name, q1.first_name) q2 = Teacher.objects.get(name=q2) results = TeacherToLab.objects.filter(teacher=q2) return render_to_response('teachers/labs.html', {'results': results}, context_instance = RequestContext(request)) I'm using @user_passes_test decorator for checking whether the authenticated user has the permission to use this view [labs view]. The problem I'm having with the current logic is that once Django authenticates a teacher user he has access to all teachers profiles basically by typing the teachers username in the url. Once a teacher finds a co-worker's username he has direct access to his data. Any suggestions would be much appreciated.

    Read the article

  • CodeIgniter & Datamapper as frontend, Django Admin as backend, database tables inconsistent

    - by Rasiel
    I created a database for a site i'm doing using Django as the admin backend. However because the server where the site is hosted on, won't be able to support Python, I find myself needing to do the front end in PHP and as such i've decided to use CodeIgniter along with Datamapper to map the models/relationship. However DataMapper requires the tables to be in a specific format for it to work, and Django maps its tables differently, using the App name as the prefix in the table. I've tried using the prefix & join_prefix vars in datamapper but still doesn't map them correctly. Has anyone used a combination of this? and if so how have the fixed the issue of db table names being inconsistent? Is there anything out there that i can use to make them work together?

    Read the article

  • Django: Summing values of records grouped by foreign key

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

    Read the article

  • 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

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