Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add user authentication to existing django project?
Can anyone tell me how to add a basic user authentication to existing django project ? Thanks -
Making django's messages appear in Javascript alert rather than html?
I'm trying to display messages to the user when they login/signup using the alert function of javascript. I'm trying something like this, but it doesn't seem to work. What is the correct syntax to pass django's variables to the script in a template? This is what I want but this syntax doesn't work. {% if messages %}{% for message in messages %}<script>alert({{}});</script>{% endfor %}{% endif %} However the following is working: {% if messages %}<ul>{% for message in messages %} <li>{{ message }}</li> {% endfor %}</ul>{% endif %} -
Profiling Django with PyCharm
My app is pretty slow even in a dev environment so I would like to figure out what's slowing it down so I can try and fix it. I know about the debug toolbar and according to what it reports neither the database queries nor the downloaded sources are the issue, so it must be the business logic. However, I cannot run the PyCharm profiler with the Django server because, well, it's not like running a script. How may I profile Django with PyCharm? -
Convert Python project to Cython
I am trying to convert my project that I have written in Python2.7 to Cython as I am working with Pandas and I know that I am able to optimize code.Additionally, I am using Django as Web API layer to expose my program for external HTTP calls. I have followed tutorial which can be found here. It works if I am running IPython, however I am not able to run same code in Pycharm. Am I missing some configuration or it is impossible? Thank you -
making middle-ware based view counter
i try to count every visit of users in my Django website on database and it should be middle-ware based (count every page request) i mean do not counting files and every requests -
Signal when all urls are loaded in Django
I want to perform magic on all url patterns of django: If they don't have a name, then I want to give them an automated name. Unfortunately django seems to load the url patterns lazy. Implementing this magic-add-name-method is easy. The problem: Where to call this method? I need to call this method after all urls have been loaded and before the first request gets handled. Code should work for Django 1.9 and Django 1.10. -
Isolate celery for development and production
Im using the same server for both my development server and production server, using virtualenv. My problem is celery not knowing what project to run the task in. I do not want task from production running on my development server and vice versa. I have tried to use different broker adress, but it does not work correctly: supervisor script for production: [program:production-celery] command=/home/user/.virtualenvs/production.site.com/bin/celery --app=myproject.celeryconfig:app worker -E -n production --loglevel=INFO --without-mingle --without-gossip -Q default,celery directory = /home/user/.virtualenvs/production.site.com/myproject environment=DJANGO_SETTINGS_MODULE='myproject.settings.production' Development: [program:development-celery] command=/home/user/.virtualenvs/development.site.com/bin/celery --app=myproject.celeryconfig:app worker -E -n development --loglevel=INFO --without-mingle --without-gossip -Q default,celery directory = /home/user/.virtualenvs/development.site.com/myproject environment=DJANGO_SETTINGS_MODULE='myproject.settings.development' Production celeryconfig: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.production') app = Celery('myproject', broker='amqp://', backend='amqp') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.update( CELERY_ACCEPT_CONTENT = ['pickle', 'json'], CELERY_TIMEZONE='Europe/Oslo', CELERY_ENABLE_UTC=True, CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler', CELERY_SEND_TASK_ERROR_EMAILS = True, CELERY_SEND_ERROR_EMAILS = True, CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True, CELERY_IGNORE_RESULT = False, CELERY_TASK_RESULT_EXPIRES = 172800, ) Development celeryconfig: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.development') app = Celery('myproject', broker='amqp://development:development@localhost/development') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.update( CELERY_ACCEPT_CONTENT = ['pickle', 'json'], CELERY_TIMEZONE='Europe/Oslo', CELERY_ENABLE_UTC=True, CELERY_SEND_TASK_ERROR_EMAILS = False, CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True, CELERY_IGNORE_RESULT = False, ) Anyone know why task from production would be run on development? -
how to calculate a sum in a template django
I have a table in my template in django that contains a field price and for every book I had a price . this is the example : ---------------------------- book name author price ---------------------------- python X1 20$ --------------------------- django X1 10$ X2 30$ ----------------------------- this is an example. I want to know if there is a way to calculate the sum of the prices istead of showing 10$ and 30$ I want to show 40$ to show this I used : <table> <thead> <tr> <th>book name</th> <th>author</th> <th>price</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ book }}</td> <td> <ul>{% for author in authors %} <li>{{ author }}</li> {% endfor %} </ul> </td> <td class="narrow"> <ul> {% for book in books %} <li>{{ book.price }}</li> {% endfor %} </ul> </td> </tr> {% endfor%} </tbody> -
The way to use background-image in css files with Django
I'd like to use an image file as a background-image on Django. But I do not know how. First, I read this and tried to write like following this in a css file. #third{ background: url("img/sample.jpeg") 50% 0 no-repeat fixed; color: white; height: 650px; padding: 100px 0 0 0; } But this does not work. {% load staticfiles %} #third{ background: url({% static "img/sample.jpeg" %}) 50% 0 no-repeat fixed; } and #third{ background: url("../img/sample.jpeg") 50% 0 no-repeat fixed; } don't work, too. How do you usually write css file when you use background-image on css files? Would you please give me some advices? C:\~~~~~~> dir hello\static\img 2016/09/28 19:56 2,123 logo.png 2016/09/24 14:53 104,825 sample.jpeg C:\~~~~~~> dir hello\static\css 2016/09/29 20:27 1,577 site.css C:\~~~~~~> more lemon\settings.py BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) C:\~~~~~~> more hello\templates\base.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static "css/site.css" %}" /> Django version: 1.9.2 -
Django admin: programatically choose visible fieldsets in inlines
What I want is to be able to choose which formsets to display according to the selection of a ForeignKey selector in the django Admin. I have four models: Product Rating Criterion (question) CriterionAnswer My database is organised as follows: Product <- ManyToOne -- Rating <- ManyToMany -> Criterion - | | -- OneToMany -> CriterionAnswer <- OneToMany -- When I select a Rating in the Product model form of the admin and save the Product, I create all the missing CriterionAnswers that correspond to the Criterions in the chosen Rating. The next time I open the Product, I see the CriterionAnswers as inlines. If I then select another Rating, other CriterionAnswers will be saved and displayed along the old ones. How do I choose to display only the CriterionAnswers which correspond to the chosen Rating? Models: ################ # Product ################ class Product (models.Model): rating = models.ForeignKey( 'Rating', on_delete=models.SET_NULL, null=True, ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) # get all criteria that need an answer in order to create the rating criteriaToAnswer = Criterion.objects.filter(rating=self.rating) # iterate over all criterias and check if the answer exists in database for crit in criteriaToAnswer: # if it doesn't exist, create an answer … -
I want to be python developer.What should I follow?
I am final year student in BSC engineering in computer science and engineering. I know a basic of python and want to be python developer. What should I follow now. -
Parse whole list in querydict dictionary in Django
I have a querydict which I pass to Django's template. This querydict may look like this: <QueryDict: {u'VAR1': [u'val1', u'val2', u'val3'], u'VAR2': u'val4', u'VAR3': [u'val5'], u'VAR4': []}> The dictionary can be larger, shorter, but it will always contain a field which has a list inside, and this list can be empty also. In the previous example it can be seen "key-value" pair containing a list ("VAR1-val1_2_3") a "key-value" pair containing an empty list ("VAR4-[]") a "key-value" pair containing a list with one item ("VAR3-val5") and a "key-value" pair containing a string ("VAR2-val4") In the template I know the key names of all entries in the querydict I would like to parse the whole list from the querydict into a Javascript variable, so it looks like this: var trial = ['val1', 'val2', 'val3'] for key "VAR1" or var trial = ['val5'] for key "VAR3" or var trial = [] for key "VAR4" depending on which is the original list on the dictionary I have tried many options but I haven't succeeded, any help please? -
Load multiple Django environments in sequence
I need to code a standalone Django 1.10 script which loads different separate environments in sequence. In other words, I need to load env1 to access to its models and later in my main script I need to do the same for env2, env3, ... I read that to load an env I could use os.environ.setdefault like here: import os, sys proj_path = "/path/to/my/project/" # This is so Django knows where to find stuff. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "env1.settings") # load models and use the Django ORM for env1 but after that, is there a way to unload env1.settings and to load env2.settings for using the Django ORM for env2? -
Can't make Nginx work with uWSGI
I am having this test file called test.py: def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] and I run uWSGI using this command: uwsgi --http :8001 --wsgi-file test.py I am able to see the "Hello World" in browser by going to xxxx.xxxx.xxxx.xxxx:8001 Now I am trying to add Nginx to this. Here is my file called mysite_nginx.conf: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000 default_server; # the domain name it will serve for server_name _; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/wz/dispatcher/OurAwesomeDjangoApp/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/wz/dispatcher/OurAwesomeDjangoApp/uwsgi_params; # the uwsgi_params file you installed } } When i go to xxxx.xxxx.xxxx.xxxx I see the standard "Welcome to Nginx". However when I go to xxxx.xxxx.xxxx.xxxx:8000 I am unable to connect. Django server … -
Gunicorn Command Fails to run
I cloned the github directory on my server from my github account. After activating the virtualenv and installing gunicorn. I used this command to run this project on port 8001. gunicorn myproject.wsgi:application --bind www.example.com:8001 It shows me an error stating this [23123] [INFO] Starting gunicorn 19.6.0 [2016-09-29 10:52:37 +0000] [23123] [ERROR] Invalid address: ('www.example.com', 8001) Can anyone tell the exact reason of this problem? Thanks -
How to return JsonResponse in Django generic ListView
I'm having trouble returning a valid HttpResponse in my ListView (and am getting a ValueError: The view didn't return an HttpResponse object.... I've overridden get because I want to return a JsonResponse: def get(self, requets, *args, **kwargs): queryset = self.get_queryset() data = serializers.serialize("json", queryset) return JsonResponse(data, status=200, safe=False) I've checked that queryset and data and the JsonResponse are not None. Changing the return statement doesn't work: return HttpResponse(json.dumps(data), content_type="application/json", status=200) Previously, if I ever needed to override get, I would return render(...), which works. So, why is my HttpResponse or JsonResponse not an acceptable HttpResponse as per the error in this instance? The GET request will be an ajax request, and I do need to provide some sensible json in reply. -
pretty much lost : self.parent.parent.__class__
I needed to serialize a self referencing hierarchy class Systm(models.Model): ... parent = models.ForeignKey('self', on_delete=models.CASCADE, blank = True, null = True, related_name="children") and I was able to achieve that with the following code: class RecursiveField(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class SystmSerializer(serializers.ModelSerializer): children = RecursiveField(many = True, read_only = True) class Meta: model = models.Systm fields = ('id', 'name', 'type', 'children') It works and everything is bright except that all I did was to copy and paste the code but no idea how it works and why it works. It is pretty annoying and I want to understand it. I put 'print' commands into 'to_representation(...)' but still not clear. I learnt that that there is recursion when the 'self.parent.parent.__class__(value, context=self.context)' is executed but not sure why. I'd be really grateful if somebody could explain it to me. Thanks, V. -
Django template tags
Im after a way of printing the publication date of a page from djangoCMS. I was thinking something along these lines might pull that information: {{ request.current_page.get_publication_date }} Nothing shows with this so i know this isn't right but I was wondering fi someone could tell me if I'm on the right lines or not? -
Create zip archive with multiple files in Django
I'm using following code where I pass .pdf file names with their paths to create zip file. for f in lstFileNames: with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip: myzip.write(f) It only archives one file though. I need to archive all files in my list in one single zip folder. Before people start to point out, yes I have consulted answers from this and this link but the code given there doesn't work for me. The code runs but I can't find generated zip file anywhere in my computer. A simple straightforward answer would be appreciated. Thanks. -
pip install MySQL-python failed in linux
I've created a Django project and its works as well now I'm trying to config it with MySql so searched in Google and did some ways but when I pip install MySQL-python the below problem occurs: Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-lwubgejh/MySQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/tmp/pip-build-lwubgejh/MySQL-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-lwubgejh/MySQL-python/ couldn't find any solution for this error: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-lwubgejh/MySQL-python/ thank you for help. -
Django messages framework not displaying message?
I'm trying to build a community portal and am working on displaying one-time message to the user such as "login successful" and the like; and am working with Django's messages framework. My template has the following line which currently does nothing: {% if messages %}{% for message in messages %}<script>alert({{ message }});</script>{% endfor %}{% endif %} Strangely, each of the following works: {% if messages %}{% for message in messages %}<script>alert();</script>{% endfor %}{% endif %} {% if messages %}{% for message in messages %}<script>alert("Welcome");</script>{% endfor %}{% endif %} From this, I am concluding that I'm not creating, storing, or passing the messages correctly. However, I'm checking the docs and my syntax seems fine. My message creation; views.py: def login(request): userName = request.POST.get('usrname',None) userPass = request.POST.get('psw',None) user = authenticate(username=sanitize_html(userName), password=userPass) if user is not None: if user.is_active: auth.login(request, user) messages.add_message(request, messages.INFO, 'Successfully logged in!') else: messages.add_message(request, messages.INFO, 'Login not successful. Please try again.') return HttpResponseRedirect('/home/') My message retrieval and passing, views.py (maps to url '/home/'): def test(request): messagealert = [] mess = get_messages(request) for message in mess: messagealert.append(message) if request.user.is_authenticated(): student_user = get_student_user(request.user) student_user.first_name = request.user.first_name student_user.last_name = request.user.last_name student_user.email = request.user.email content = { 'student_user': student_user, 'messages': messagealert, } else: … -
Send data to a modal
I'm using Django and i'm trying to send data in a modal to get informations of an element. My button to open the modal is : <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#informations"> <span class="glyphicon glyphicon-trash" aria-hidden="true">{{registration_id}}</span> </button> And the modal is <div class="modal fade" tabindex="-1" role="dialog" id="information"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <form method="post" action="{% url 'informations_choices' %}"> {% csrf_token %} <input type="hidden" name="registration" value=......> Get info about : ...... </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" onclick="$('#information').modal('hide');$('#informations_choices').submit()"> Get Info </button> </div> </div> </div> </div> The modal open correctly, but how can transform the "......" into value (by exemple with the {{registration_id}} present in the button ? Thanks in advance -
Database connections increases more than number of concurrent users?
I have a django web-server configured with NGINX, gunicorn with postgresql database. The server receives request from client to online execute their program and show them the results. The max_connection in database conf file is set to 1000. but sometimes the number of connection goes beyond 1000 while the maximum number of concurrent user is never beyond 200. Why the db connection goes to such high values because as far as I know by default django closes the db connection as soon as it serves a request ( conn_max_age is also set to 0, so no persistent connection) ? -
How can change profile picture automatically evrywhere when changes one place in django
How can i changes the profile picture at one place and changes it automatically everywhere without reload in django. I am changing profile picture in edit profile section and want to change it everywhere without reload. -
OpenAM oAuth 2.0 authentication failed
I am building a project with OpenAM as access manager and using django oauth2 for authentication. I created an oAuth2 module instance in OpenAM that uses Authentication APIs of my django project. Authentication Endpoint URL and Access Token Endpoint URL work perfectly fine, but the final URL that fetches User Profile gets a 200 status response from the API but OpenAM shows 401 Authentication Failed. My response for User profile service URL is: {'response': {'email': 'abc@abc.com', 'first_name': 'abc', 'last_name': 'def', 'id':'user1', 'name': 'abc def'}, 'error': ''} And scope is "email". Please help what can be wrong in this.