Search Results

Search found 8719 results on 349 pages for 'django views'.

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

  • 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

  • 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

  • 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

  • Drupal Views pulling Data Fields

    - by askon
    I'm a little new to drupal but have been using things like devel module and theme developer to speed up the learning process. My question, is it possible to theme an entire views BLOCK from a single views tpl.php page OR even a preprocess? When I'm grabbing the $view object I can see results $node-result, it has all of the results, but it doesn't have all my views fields. I'm missing things like, node path, taxonomy titles and paths, etc. From my understanding, Drupal wants you to individually theme EACH output field. It seems rather superfluous to create so many extra templates when I've already got over HALF of my results coming through the $view object Would outputting node over field make this easier? Or am going in the wrong direction with $view-result? Thanks!

    Read the article

  • Django syncdb error

    - by Hulk
    /mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error saying Error: One or more models did not validate: project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'. How can this be solved.. thanks..

    Read the article

  • queries in django

    - by Hulk
    How to query Employee to get all the address related to the employee, Employee.Add.all() doe not work.. class Employee(): Add = models.ManyToManyField(Address) parent = models.ManyToManyField(Parent, blank=True, null=True) class Address(models.Model): address_emp = models.CharField(max_length=512) description = models.TextField() def __unicode__(self): return self.name()

    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

  • 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

  • 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

  • using distinct in django query

    - by Hulk
    There is a column as designation in the defaults table,How to get the distinct designation values from defaults table In the below the distinct applies on the id field, this need to be on designation field def = defaults.objects.filter(name=sc).distinct() And can some one explain what is flat=true condition Thanks..

    Read the article

  • Reorganizing many to many relationships in Django

    - by Galen
    I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages. My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to that part of the video) Here's an illustration Flash Video embedded here Actors... Ted smith: 1:25, 5:30 jon jones: 5:00, 2:00 Here are the pertinent parts of my models class Video(models.Model): actor = models.ManyToManyField( Actor, through='Actor_Video' ) # more stuff removed class Actor_Video(models.Model): actor = models.ForeignKey( Actor ) video = models.ForeignKey( Video) time = models.IntegerField() Here's what my Actor_Video table looks like, maybe it will be easier to see what im doing id actor_id video_id time (in seconds) 1 1 3 34 2 1 3 90 i feel like i have to reorganize the info in my view, but i cant figure it out. It doesn't seem to be possible in the template using djangos orm. I've tried a couple things with creating dictionaries/lists but i've had no luck. Any help is appreciated. Thanks.

    Read the article

  • Django - markup parser in template or view?

    - by Amit Ron
    I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python. Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like: return render_to_response( 'blog/post.html', {'post': post, 'content': parseMyMarkup(post.content) }) Is this the usual convention, or should I do something different?

    Read the article

  • Django templates tag error

    - by Hulk
    def _table_(request,id,has_permissions): dict = {} dict.update(get_newdata(request,rid)) return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)})) In templates the code is as, {% if has_permissions == "1" %} <input type="button" value="Edit" id="edit" onclick="javascript:edit('{{id}}')" style="display:inline;"/>&nbsp;&nbsp;&nbsp;&nbsp; {% endif %} There is a template error in has_permissions line. Can any 1 tell me what is wrong here. has_permissions has the value 1 or 0.

    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

  • Why use NoSQL over Materialized Views?

    - by JustinT
    There has been a lot of talk recently about NoSQL. The #1 reason why I hear people use NoSQL is because they start to de-normalize their DBMS data so much so, to increase performance, that they end up with just one table with all of their data within that single table. With Materialized Views however, you can keep your data normalized, yet have it stored as a single table view for the same reasons why you'd use NoSQL. As such, why would someone use NoSQL over Materialized Views?

    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: Country drop down list?

    - by User
    I have a form for address information. One of the fields is for the address country. Currently this is just a textbox. I would like a drop down list (of ISO 3166 countries) for this. I'm a django newbie so I haven't even used a Django Select widget yet. What is a good way to do this? Hard-code the choices in a file somewhere? Put them in the database? In the template?

    Read the article

  • Django: reverse lookup URL of feeds?

    - by Santa
    I am having trouble doing a reverse URL lookup for Django-generated feeds. I have the following setup in urls.py: feeds = { 'latest': LatestEntries, } urlpatterns = patterns('', # ... # enable feeds (RSS) url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds_view'), ) I have tried using the following template tag: <a href="{% url feeds_view latest %}">RSS feeds</a> But the resulting link is not what want (http://my.domain.com/feeds//). It should be http://my.domain.com/feeds/latest/. For now, I am using a hack to generate the URL for the template: <a href="http://{{ request.META.HTTP_HOST }}/feeds/latest">RSS feeds</a> But, as you can see, it clearly is not DRY. Is there something I am missing?

    Read the article

  • Project name inserted automatically in url when using django template url tag

    - by thebossman
    I am applying the 'url' template tag to all links in my current Django project. I have my urls named like so... url(r'^login/$', 'login', name='site_login'), This allows me to access /login at my site's root. I have my template tag defined like so... <a href="{% url site_login %}"> It works fine, except that Django automatically resolves that url as /myprojectname/login, not /login. Both urls are accessible. Why? Is there an option to remove the projectname? This occurs for all url tags, not just this one.

    Read the article

  • How to customize a many-to-many inline model in django admin

    - by Jonathan
    I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: class Product(models.Model): name = models.TextField() price = models.DecimalField(max_digits=10,decimal_places=2) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) In admin.py: class ProductInline(admin.StackedInline): model = Invoice.products.through class InvoiceAdmin(admin.ModelAdmin): inlines = [FilteredApartmentInline,] admin.site.register(Product, ProductAdmin) The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic. How can I change it so that it'll just display the product's name in the inline table? Which form should I override, and how?

    Read the article

  • django cross-site reverse a url

    - by tutuca
    I have a similar question than django cross-site reverse. But i think I can't apply the same solution. I'm creating an app that lets the users create their own site. After completing the signup form the user should be redirected to his site's new post form. Something along this lines: new_post_url = 'http://%s.domain:9292/manage/new_post %site.domain' logged_user = authenticate(username=user.username, password=user.password) if logged_user is not None: login(request, logged_user) return redirect(new_product_url) Now, I know that "new_post_url" is awful and makes babies cry so I need to reverse it in some way. I thought in using django.core.urlresolvers.reverse to solve this but that only returns urls on my domain, and not in the user's newly created site, so it doesn't works for me. So, do you know a better/smarter way to solve this?

    Read the article

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