Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin panel- Adding a custome field in 'list_display' widget which is not an attribute of models class(without altering models.py)
I want to add a field named 'count' to 'genre' class that gives the count of movies in that genre. models.py class genre(models.Model): genre_name = models.CharField(max_length=20, verbose_name='Genre') def __str__ (self): return(self.genre_name) class movie(models.Model): movie_name = models.CharField(max_length=50, verbose_name='Movie Name') movie_rating = models.IntegerField(default=1) movie_genres = models.ManyToManyField(genre, verbose_name='Genre(s)') added_by = models.CharField(max_length=20, blank=True) email = models.EmailField(blank=True) Date = models.DateTimeField(default=datetime.now) def __str__ (self): return(self.movie_name) admin.py from __future__ import unicode_literals from django.contrib import admin from . models import movie, genre from django import forms class movieAdmin(admin.ModelAdmin): list_display=('movie_name', 'movie_rating','Date') search_fields=('movie_name',) filter_horizontal=('movie_genres',) list_filter=('Date',) date_hierarchy='Date' ordering=('-movie_name',) fields=('movie_name','movie_rating') admin.site.register(movie, movieAdmin) admin.site.register(genre) I want to add count field in list_display -
Nginx still displaying welcome page even after deleting default from sites-enabled
I am new to nginx. i followed the following tutorial. http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ The problem is that instead of displaying my site's homepage, nginx always displays its welcome page. I have deleted the default symbolic link from /etc/nginx/sites-enabled and restarted nginx but i still have not been able to get rid of the welcome page. Can anyone advise, what can I do to see my actual website? -
Is there a easy way to change the path in django?
I get the templates files, I divide them to static files and templates files. As you know I can not correct open the html in browser now, because thier path all changed. I can in the templates files to change every link or script and image path one by one, but its a trouble things, takes our away many time. Is there a simple way to do that? -
I am getting a SyntaxError in my model.py where could be the issue with my code
iam writing my code in model.py but this error that i getting in my development server.Any suggestions are welcome.I have followed previous suggections in stackflow but i can't get any answer that is solving my code. Error:the code below is the error i am getting. Unhandled exception in thread started by <function wrapper at 0x7fe6d63e4938> Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib64/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/lib64/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/harrugg2/projects/django/church/tithe/models.py", line 24 def print(self): ^ SyntaxError: invalid syntax below is my code for model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.db import models # Create your models here. class tithe(models.models): genarationNo = models(ForeignKey('generationNo.User')) memberid = models.IntField() membername = models.VacharField() tithe = models.IntField() combinedoffering = models.IntField(max_length=45) campmeetingoffering = models.IntField(IntField=45) churchbuilding = models.IntField(max_length=45) conference = models.IntField(max_length=45) localchurch = models.IntField(max_length=45) funds = models.IntField(max_length=45) total = models.IntField(max_length=45) created_date = models.DateTimeField( default=timezone.now) printed_date = models.DateTimeField( … -
CMS_PLACEHOLDER_CONF placeholders start or end with
Is there any way to set all placeholders that starts with 'foo' or end with 'bar' in CMS_PLACEHOLDER_CONF example: CMS_PLACEHOLDER_CONF = { 'foo_*': { 'name': "Starts with", 'default_plugins': [ { 'plugin_type': 'TextPlugin', 'values': { 'body': '<h1>Jason start</h1>' }, }, ] }, '*_bar': { 'name': "Ends with", 'default_plugins': [ { 'plugin_type': 'TextPlugin', 'values': { 'body': '<h1>Jason end</h1>' }, }, ] }, } Any help will be appreciated -
How to properly add template tags to a django project
I am playing with django-gentelella and try to add custom template tags to the project. According to the latest django documentation, one should add a "templatetags" directory, at the same level as models.py, views.py, etc. Also, an init.py file should be placed in the directory. I added my template tags into a file called "template_tags.py" and restarted the server. In my templates I load the fule using "{% load template_tags %}" at the top of the file. Unfortunately, this does not work yet. According to the django documentation it is also required to add the template_filters to the INSTALLED APPS. My problem is that I cannot figure out how to get the right path in dot notation. Can anyone point me into the right direction? -
How do you filter out or not include certain records in a model admin multiselect widget in Django Admin?
How do you filter out or not include certain records in a model admin multi-select widget. For example a recursive relationship will include edited or added field to the multi-select widget but should not include its exact self, class A(models.Model): a = models.ManyToManyField('self') -
Django-Cms user wise instance
Currently, I am developing a website with Django CMS. Now I want to customize Django CMS in such a way that the user which is customizing a website has only access to get their pages and plugins. In short, I want a different instance of Django CMS for each individual admin user. I want to make a portal in which different organizations can log in and customize their own website using Django CMS -
Django Server - How to prevent caching on csv files?
I have a server which generates some data on a daily basis. I am using D3 to visualise the data (d3.csv("path")). The problem is I can only access the files if they are under my static_dir in the project. However, if I put them there, they do eventually get cached and I stop seeing the updates, which is fine for css and js files but not for the underlying data. Is there a way to put these files maybe in a different folder and prevent caching on them? Under what path will I be able to access them? Or alternatively how would it be advisable to structure my project differently in order to maybe avoid this operation in the first place. Atm, I have a seperate process that generates the data and stores it the given folder which is independent from the server. Many thanks, Tony -
Insert values from list to nested json
I have a nested json that looks like this: [ { 'Name':'Anders', 'Type':'Hunter', 'Race':'Cyborg', }, { 'Name':'Karin', 'Type':'Titan', 'Race':'Human', }, { 'Name':'Jenny', 'Type':'Warlock', 'Race':'Marsian', }, ] And I have a string that looks like this: ['1', 'Ham', 'Spam', 'Bacon', '1', 'Ham', 'Cucumber', 'Tomato', '1', 'Wood', 'Potato', 'Herring'] I want to insert the string into the json with a name for the value. Each four in the string is for each person in the json. Final result should look like this: [ { 'Name':'Anders', 'Type':'Hunter', 'Race':'Cyborg', 'string1':'1', 'Food_1':'Ham', 'Food_2':'Spam', 'Food_3':'Bacon', }, { 'Name':'Karin', 'Type':'Titan', 'Race':'Human', 'string1':'1', 'Food_1':'Ham', 'Food_2':'Cucumber', 'Food_3':'Tomato', }, { 'Name':'Jenny', 'Type':'Warlock', 'Race':'Marsian', 'string1':'1', 'Food_1':'Wood', 'Food_2':'Potato', 'Food_3':'Herring', }, ] I have tryied with some iterations, but fails all the time :/ Hope you can help me! -
Circular imports and class fields in python3
Okay, I do understand that this topic is old as hell, but I couldn't find an answer to the particular question that I am asking. Let's say that we have a very simple structure: two files, a.py and b.py, their contents being: a.py import b class C: lal = 4 class A: kek = 12 lol = b.B() b.py import a class B: aa = a.C() Trying to run python b.py, we get: Traceback (most recent call last): File "b.py", line 1, in <module> import a File ".../a.py", line 1, in <module> import b File ".../b.py", line 3, in <module> class B: File ".../a.py", line 5, in A aa = a.C() AttributeError: module 'a' has no attribute 'C' BUT if we move the import b line AFTER the C class, the script launches and produces no errors. I have not found any mention of this whatsoever in any answers here on SO. The question here is: Why does this happen and how to escape this? This is a particularly important question for the Django framework. When I have many models, I try splitting them into many files. It is very easy to get a cyclic import there. -
__unicode__ function works locally but not on Heroku
I have done a simple app with an admin interface that works great locally. I have deployed it on heroku successfully. this is my models.py class Club(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name=_("name")) def __unicode__(self): return self.name class Party(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name=_("name")) club = models.ForeignKey(Club, verbose_name=_('club')) def __unicode__(self): return self.name Locally, in the admin interface, in the Parties table, I can see Club's name under the club column, which is the result of the __unicode__ But, In heroku, the __unicode__ method doesn't work, I get ClubObject in the party's club column instead. I'm using python 2.7. Any help? -
Visualize data on map in Django application
I am working on a Django application which organizes informations about concerts. I am relatively new to Django and web development in general. I have implemented models to store the informations in the database. Now I want to visualize it and I think the best way would be to show the data on a map. Each Concert object has a Place attribute which stores the location of the concert as longitude and latitude coordinates. Is there a library that can visualize data like this as points on a map? On the map there should only be a number which indicates how many concerts took place at this location. If the user clicks on a location, he should get redirect to a detail view. -
OneToManyField relationship in Django?
Is there a OneToManyField relationship in Django? There is a ManyToOneField relationship but that restrict you declare the relationship on the Many side. -
Why python scheduler runs just once?
I use the python scheduler to run a proces in an interval of 3 seconds. But the ouput ( just a hello world ) run just one times. I run this function after the start of my django webserver, so it is necessary that this script run in the background. Question 1: Why my script run just one, an not each second (value of delay is 3) Question 2: Is this a good practice to run a script in the background or in an interval? I expact, that the script needs not more than 3 second to execute. import sched, time def startProcess(self): print("START PROCESS") print(time.time()) s = sched.scheduler(time.time, time.sleep) s.enter(3,1, self.initProcessHelloWorld) s.run() print(time.time()) print("END PROCESS") -
Automatically run Django project in Debug when in PyCharm
Is it possible to run my Django project in DEBUG mode, when in PyCharm? If not in PyCharm, say in production, then of course the DEBUG mode should not be True. How can this be done most neatly? -
Failed to deploy django application on aws elasticbeanstalk
I have deployed a project to aws elasticbeanstalk and it was working. But when I delete one app and deployed again getting this error "django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint'). container_command 01_migrate in .ebextensions/03_python.config failed". Please I have deleted the locat db and previous migrations too. Hope some body can help me, Thank you... -
2checkout INS notification failed in sandbox
I have integrated 2checkout (mode:sandbox) with django. I am not getting INS notifications (INS Failed). In 2checkout sandbox i am able to see all the successful created sales I have given order success URL as https://mywebsitename/success for INS notification in django: urls.py url(r'^success$', views.success, name='success') Views.py @require_POST @csrf_exempt def success(request): jsondata = request.body params = json.loads(jsondata) params['secret'] = 'mysecretWord' result = twocheckout.Passback.check(params) return HttpResponse(status=204) also please tell me what is twocheckout.Charge.submit(params) -
Equivalent of PostGIS ST_MakeValid in Django GEOS
Upon checking polygon object validity using Objects.polygon.valid, it throws an error an error GEOS_NOTICE: Self-intersection. I know this can be fixed by using ST_MakeValid in PostGIS. I'm using Django 1.11 with GEOS support and can't find its equivalent in Django docs. Is there any equivalent function for ST_MakeValid in Django GEOS? Thanks in advance. -
django ORM queryset group by month, week, TruncMonth
How group by queryset on datetime field in Django ORM? models class test1(models.Model): id = models.AutoField(primary_key=True, unique=True, verbose_name='id') name = models.CharField(verbose_name='name', max_length=200) cdate = models.DateField(verbose_name='date', default=timezone.now) queryset data for i in test1.objects.all(): print i.id, i.name, i.cdate 2 a 2017-08-11 3 b 2017-08-11 4 c 2017-08-11 5 a 2017-08-11 6 a 2017-08-11 need group by month and count IDs with django orm queryset data = test1.objects.annotate(month=TruncMonth('cdate')).values('month').annotate(c=Count('id')) for i in data: print i result {'c': 1, 'month': datetime.date(2017, 8, 1)} {'c': 1, 'month': datetime.date(2017, 8, 1)} {'c': 1, 'month': datetime.date(2017, 8, 1)} {'c': 1, 'month': datetime.date(2017, 8, 1)} {'c': 1, 'month': datetime.date(2017, 8, 1)} why not? {'c': 5, 'month': datetime.date(2017, 8, 1)} -
Django REST Framework documentation not displaying certain methods
I wonder why Django REST Framework build-in documentation doesn't display methods for a User. I have only available list, create, read, update for these URLs: url(r'^users$', views.UserList.as_view()), url(r'^users/(?P<user_id>\w+)$', views.UserDetail.as_view()), views.py: @permission_classes([CustomPermission]) class UserList(GenericAPIView): """ get: Return all users. post: Create a user. """ serializer_class = UserSerializer def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @permission_classes([UserPermission]) class UserDetail(GenericAPIView): """ get: Return user by ID. put: Update user by ID. delete: Delete user by ID. """ serializer_class = UserSerializer def get(self, request, user_id): try: user = User.objects.get(id=user_id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = UserSerializer(user) return Response(serializer.data) def put(self, request, user_id): try: user = User.objects.get(id=user_id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, user_id): try: user = User.objects.get(id=user_id) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) However example shown below is not visible in build-in documentation. I have also Swagger documentation in the project and everything is displayed properly. urls.py: url(r'^users/(?P<user_id>[0-9]+)/object$', views.UserObject.as_view()), views.py: @permission_classes([UserPermission]) class UserObject(GenericAPIView): """ post: Create a user object by his ID. get: Return a user object by his ID. put: … -
Do QuerySet operations on prefetched relationships hit the database?
Let's say I query Workplaces in a City and prefetch all their Workers, which is a many-to-many relationship: workplaces = list(city.workerplace_set.filter(num_employees__lte=350).prefetch_related('Worker')) If I use any QuerySet operation on Workers from any of the Workplaces, will the database be hit or not? I could not make out a clear answer from the docs. workplaces_with_interns = [workplace for workplace in workplaces # is this filter going to query the database? if workplace.worker_set.filter(salary=0).exists()] PS: someone is probably going to point out that I can reach the same answer by simply making a query for city.workerplace_set instead of making it a list. Yes, I know, but that is not possible because I am caching the workplaces so that the database is not hit every time the function that does all this is called. -
Django view unable to fetch complete value from html
I am new at django and am unable to understand as to why my following code request.POST.getlist('sport') is returning "table" instead of "table tennis"? I have given checkbox in my HTML form with name='sport' value='table tennis' -
Using the same method but get different result
I use {extends 'xxx.html'} to make all templates have the same 'head' and 'tail', there's an user avatar area {{ avatar }} in head, but I use the same method to pass this avatar in every views, my index.html can't correctly show the avatar, but the other can, so I assume is something wrong with my index views. Here's the index view: def index(request): if request.method == 'GET': all_user = UserInfo.objects.all() user = all_user.filter(username=request.user.username) return render(request, 'index.html', { "icon": user.icon, "user": user.username, }) And here's a part of views which could correctly show the avatar: if request.user.is_authenticated(): my_fav = UserFavorite.objects.all() my_fav_num = my_fav.filter(user=request.user).count() my_posts_num = all_posts.filter(user=request.user).count() my_msg = UserMessage.objects.all() my_msg_num = my_msg.filter(user=request.user, has_read=False).count() all_user = UserInfo.objects.all() user = all_user.get(username=request.user.username) return render(request, 'community.html', { "all_posts": posts, "post_num": post_num, "animal_kind": animal_kind, "post_kind": post_kind, "sort": sort, "my_fav_num": my_fav_num, "my_posts_num": my_posts_num, "my_msg_num": my_msg_num, "icon": user.icon, "user": user.username, }) else: my_fav_num = 0 my_msg_num = 0 my_posts_num = 0 return render(request, 'community.html', { "all_posts": posts, "post_num": post_num, "animal_kind": animal_kind, "post_kind": post_kind, "sort": sort, "my_fav_num": my_fav_num, "my_posts_num": my_posts_num, "my_msg_num": my_msg_num, }) can't see why the index can't find the avatar. -
Django doesn't use pyodbc as python does
I have a python script using pyodbc to read a 2005 sql server database: import pyodbc con = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=schema;UID=user;PWD=pass') cursor = con.cursor() cursor.execute(str.format("SELECT id FROM schema.dbo.mytable WHERE num = {0}", foo.num) This works fine. When I try to configure a database in my django project settings with the same parameters, I can't read tables from the same database. 'second_db': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'schema', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'servername', 'OPTIONS': { 'driver': 'SQL Server', }, }, Somewhere in django project workspace: from django.db import connection cursor = connection.cursor() cursor.execute(str.format("SELECT id FROM schema.dbo.mytable WHERE num = {0}", obj.num) I get: [42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'schema.dbo.mytable'. (208) (SQLExecDirectW) Can anyone help me to detect what's the difference between both? Django is running in the same machine where I run the script, so I believe it isn't a permissions problem... I would like to use the django connections instead of define a standard cursor, because I prefer to have all the database settings within the django settings, not spread out around the code.