Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use DRF to create a page based site (e.g. a blog)?
Can I use Django Rest Framework to create an "ordinary" site - like a blog, with templated HTML pages ala "normal" django? The reason I ask this is that I am building a website (sort of a blog), but for sections of the site, the functionality will be provided by making CALLS to a REST API. So, my question essentially is this: Is DRF equivalent to (all the features/functionality of django) + ability to create/use RESTful APIs? -
Convert JSON list of integers to String in Django Rest Framework
I am trying to get list of integers from user and convert those to comma separated string before save model in Django Rest Framework. My model is like this: class Message(models.Model): name = models.CharField(max_length=100) regions = models.TextField(validators=[RegexValidator(regex='^[0-9,]+$')]) created_at = models.DateTimeField(auto_now_add=True) and my Serializer: class MessageSerializer(ModelSerializer): regions_list = serializers.ListField(child=serializers.IntegerField()) class Meta: model = Message fields = ('id', 'name', 'regions_list', 'created_at') read_only_fields = ('created_at') My input: { "name": "TEST", "regions_list": [1, 2, 3, 4] } How can I convert regions_list to comma separated string (regions) in db? -
Moving a web site from Java to Django
I am not from a tech background. Need your help for a particular task. I got a website, which was built using java, hosted on Apache and Tomcat using Mysql server. Now I know Django and successfully built some project using it. I am considering to re-code the existing website from Java to Django. Coding, template everything is done. I need your help regarding data migration from Mysql to Postgres and how to migrate models in Django. Basically if someone have done it in past, how I should proceed? Currently website receives 1250 visits daily from Google and site goes down twice a week. -
How to hide duplicates in django template - table?
I have dict: my_dict = { '1': [], '2': [], '3': ['some_text'], '4': ['some_text'], '5': ['some_text'], '6': [], '7': ['other_text'], '8': [] } And I want to display this in template: +--------+------------------------------+ | 1 | | +--------+------------------------------+ | 2 | | +--------+------------------------------+ | 3 | some_text | +--------+ + | 4 | | +--------+ + | 5 | | +--------+------------------------------+ | 6 | | +--------+------------------------------+ | 7 | other_text | +--------+------------------------------+ | 8 | | +--------+------------------------------+ For now I have: {% for skey, svalue in sdict.items %} <tr> <td> {{ skey }} </td> <td> {% for val in svalue %} {{ val }} {% endfor %} </td> </tr> {% endfor %} and output: +--------+------------------------------+ | 1 | | +--------+------------------------------+ | 2 | | +--------+------------------------------+ | 3 | some_text | +--------+------------------------------+ | 4 | some_text | +--------+------------------------------+ | 5 | some_text | +--------+------------------------------+ | 6 | | +--------+------------------------------+ | 7 | other_text | +--------+------------------------------+ | 8 | | +--------+------------------------------+ How to do it? -
Why Django Swagger is not showing docs for urls that has permissions IsAuthenticated?
In my api default permmision class is 'rest_framework.permissions.IsAuthenticated' and django swagger is not showing docs for any url. My REST_FRAMEWORK settings is: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } And my swagger_settings is : SWAGGER_SETTINGS = { 'USE_SESSION_AUTH': False, 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, So how can I show authenticated endpoints in django swagger. -
Django images not loading
I can upload an image through the admin page, but the image can not be found when I navigate to the url that is generated by django. (404 error) The files are being uploaded to the folder: project_root/media/eventbanner/1/ I have tried multiple solutions but none seem to work for my situation. Django 1.10 is being run local on Ubuntu 16.04. The url I get is: http://localhost:8000/media/eventbanner/1/banner_image.jpg Media root folder is located at: /home/username/xxx/xxx/project_name/media Code in HTML file: <div class="banner-image"> <img src="{{ event.eventbanner.banner_image.url }}"/> </div> url.py code: from django.conf.urls import url, include from django.contrib import admin from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'events' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<event_id>[0-9]+)/$', views.details, name='details'), url(r'^details/(?P<event_id>[0-9]+)/addcomment/$', views.add_comment, name='add_comment'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR, 'static'),] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' models.py def validate_only_one_instance(obj): model = obj.__class__ if (model.objects.count() > 0 and obj.id != model.objects.get().id): raise ValidationError("Can only create 1 %s instance" % model.__name__) class EventBanner(models.Model): event = models.OneToOneField(Event, unique=True) banner_image = models.ImageField(upload_to=get_image_path, blank=True, null=True) def clean(self): validate_only_one_instance(self) -
Django and nginx using sock file: not created during startup
I'm setting up django 1.7.1 on aws ubuntu server. There's an issue however when trying to set it up. Note that start-project doesn't create a sock file and during example on setting up wasn't created. Here's the nginx error log 2017/01/04 10:49:02 [crit] 8196#8196: *1 connect() to unix:/tmp/sock/kb.sock failed (2: No such file or directory) while connecting to upstream, client: 197.232.12.165, server: kenyabuzz.nation.news, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/tmp/sock/kb.sock:", host: "kenyabuzz.nation.news:8080" The sock file is missing, I've checked online documentation on this but none seems to fix this. It's supposed to be created when you run sudo service uwsgi start however I get an error Failed to start uwsgi.service: Unit uwsgi.service not found. Here's the config for uwsgi /etc/uwsgi/sites/kb.ini [uwsgi] project = kb base = /home/ubuntu chdir = %(base)/%(project) home = %(base)/%(project)/kbenv module = %(project).wsgi:application master = true processes = 5 socket = /tmp/sock/kb.sock chmod-socket = 664 vacuum = true and in /etc/init/uwsgi.conf description "uWSGI application server in Emperor mode" start on runlevel [2345] stop on runlevel [!2345] setuid ubuntu setgid www-data exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Nginx check shows it's okay here's the settings server { listen 8080; server_name kenyabuzz.nation.news; location = /favicon.ico { access_log off; log_not_found off; } location … -
when integrating into frontend did not get proper output
i have this code to show product image {% if products %} {% for product in products %} <div class="col-md-4 p-border"> {% block product_image %} <div class="img"> {% with image=product.primary_image %} {% thumbnail image.original "x300" upscale=False as thumb %} <a href="{{ product.get_absolute_url }}"> <img src="{{ image.original.url }}" alt="{{ product.get_title }}" class="img-responsive"> </a> {% endthumbnail %} {% endwith %} </div> {% endblock %} <p>{% if product.title > 20 %}{{ product.title|slice:":20" }}{{ '. . .' }}{% else %}{{ product.title }}{% endif %}<span class="pull-right glyphicon glyphicon-heart-empty" style="color:maroon;"></span></p> <p>{% if product.title > 30 %}{{ product.description|striptags|title|slice:":30" }}{{ '. . .' }}{% else %}{{ product.description|striptags|title }}{% endif %} {% purchase_info_for_product request product as session %} <span class="pull-right">{{ session.price.incl_tax|currency:session.price.currency }}</span></p> </div> {% endfor %} {% else %} <p class="nonefound">{% trans "No products found." %}</p> {% endif %} I have made a new template to show this detail into new format. but i am unable to get proper ouput. my new html design is <div class="col-md-9 col-sm-12 col-xs-12 xs-zero-p " data-href="items"> <div class="col-md-4 col-sm-6 col-xs-6 product"> <div class="thumbnail product-parent"> <a href="assets/images/product.jpg" style="text-decoration: none"> <div class="img-parent"> <img src="assets/images/product.jpg" class="img img-responsive product-image" alt="Lights" > </div> <div class="caption"> <p style=" white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"> Proactively integrate world-class markets for frictionless human … -
CSS doesn't work with xhtml2pdf Django
I'm trying to improve my generated PDF created by xhtml2pdf with some CSS style in my Django Project. I would like for example to justify a text block, but apparently, it doesn't work and I don't find why. I'm reading lots of documentations about this library, I wrote some CSS scripts but still nothing. This is my HTML file : <html> <head> {% load staticfiles %} <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" /> <style> p {text-align: justify;} </style> </head> <font face="Courier New, monospace" <body> <logo class="logo"> <img src='/Users/valentinjungbluth/Desktop/Django/Etat_civil/Etat_civil/static/images/logo.png' /> </logo> <h2 align="center"> <font color="red" size="6"> ACTE DE NAISSANCE <br /> COPIE INTEGRALE </font></align> </h2> <br></br> <br></br> {% block content %} <h3 align="left"> ACTE DE NAISSANCE N° {{birthcertificate.id}} / {% now "Y" %} {{birthcertificate.firstname}} {{birthcertificate.lastname}}</align> </h3> <br></br> <p>Le {{birthcertificate.birthday}} est né, {{birthcertificate.firstname}} {{birthcertificate.lastname}}, du sexe {{birthcertificate.sex}}, <br /> de {{birthcertificate.fk_parent1.firstname}} {{birthcertificate.fk_parent1.lastname}}, né à {{birthcertificate.fk_parent1.birthcity}} ({{birthcertificate.fk_parent1.country}}) le {{birthcertificate.fk_parent1.birthday}}, {{birthcertificate.fk_parent1.job}},<br /> et de {{birthcertificate.fk_parent2.firstname}} {{birthcertificate.fk_parent2.lastname}}, née à {{birthcertificate.fk_parent2.birthcity}} ({{birthcertificate.fk_parent2.country}})<br /> le {{birthcertificate.fk_parent2.birthday}}, {{birthcertificate.fk_parent2.job}}, domiciliés au {{birthcertificate.fk_parent1.adress}}. </p> <br></br> Dressé le {% now "SHORT_DATETIME_FORMAT" %} à ... , lecture faite et invité à lire l'acte, a signé avec Nous, <br /> {{user}}, chevalier de la Légion d'honneur, officier de l'Etat Civil. <h3> … -
django: Unit tests for web app with different database types
I have a django web backend application which connects to two databases: MySQL and PostGreSQL. I want to run some unit tests which check for object creation and reading them for models in the PostGreSQL database. While I run them, the test database is not getting created with the following error: django.db.utils.ProgrammingError: (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 'jsonb NULL, `processed_payload` jsonb NULL, `scheduled_time` datetime(6) NULL, `' at line 1") My settings.py file has the database entries like the following (putting alias instead of actual values): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name_1', 'USER': 'user_1', 'PASSWORD': 'user_pwd_1', 'HOST': 'host_1', 'PORT': '3306', }, 'payouts': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name_2', 'USER': 'user_2', 'PASSWORD': 'user_pwd_2', 'HOST': 'host_2', 'PORT': '5432', } How can I make sure that the database is created for PostGreSQL instead of MySQL so that the create table query does not fail? -
How to add "add new" icon to Django forms fields?
How can I add an "add new" icon next to the Django form field? I mean something like in Django admin. But I don't want to call Django admin's built in popup, I want to handle it myself using modal and JQuery. So the only thing I want is probably to create a widget which adds plus icon next to the field so I don't have to decompose the form (just render it this way {{ form }}): <div class="panel-body"> <form action="" method="post">{% csrf_token %} {{ form | as_bootstrap }} <button type="submit" class="btn btn-success">Submit</button> </form> </div> -
How to constantly update data in a website with django
So I should start off with what I'm making. Basically it's a local network computer monitor, mostly for rasberry pis. Anyway, I'm using django and what I'm trying to do is have the cpu gauges update every 5 seconds but I can't figure out or find how to do it, aside from having javascript reload the whole page every 5 seconds. -
Ajax don't transmit data
I'm using ajax to pass data to a view for save in database. In javascript the data look correct but in the view is null. Read the comments in code for other questions and informations My javascript: ... var changed_element=[]; var changed_value=[]; document.getElementById('tabella').addEventListener('change', function(event){ ... changed_element.push(element); //list of list of string changed_value.push(elem[elem.value].text); //list of string ... }); document.getElementById('btn-save').addEventListener('click', function() { console.log('changed_element', changed_element) //print the right value $.ajax({type: 'POST', url: '/salva-conoscenze-rapporti/', data: { changed_element: changed_element, changed_value: changed_value //<= comma? }, success: function(msg) { console.log(msg) //prints 'It works' document.getElementById('btn-save').style.display = 'none'; } //<= comma? }); }); My view: @staff_member_required @ensure_csrf_cookie #I need this? def salva_conoscenze_rapporti(request): if request.is_ajax(): changed_element = request.POST.get('changed_element', None) changed_value = request.POST.get('changed_value', None) msg='it works' print(changed_element) #prints None instead of array print(changed_value) else: msg='it doesn't work' return HttpResponse(msg) My template base.html: ... <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); </script> ... My template: {% extends 'base.html' %} Basically print(changed_element) should gives the data instead gives None. -
How to cache api using django memcached
1st time writing question on stackoverflow. I using python 2.7.11 and djnago 1.10.2. I created product models and saved 1000 products in my database.(postgrelsql) Actually, I used Django memcached but its not working. Following steps:- 1. Added settings.py in caches backends. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'product_cache_table', } } Then "Creating the cache table." Database caching using Django Memcached:- Django can store its cached data in your database. This works best if you’ve got a fast, well-indexed database server.To use a database table as your cache backend: Set "BACKEND" to "django.core.cache.backends.memcached.MemcachedCache". Set "LOCATION" to "tablename", the name of the database table. This name can be whatever you want, as long as it’s a valid table name that’s not already being used in your database. In this example, the cache table’s name is "product_cache_table:" CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'product_cache_table', } } Then "Creating the cache table." Before using the database cache, you must create the cache table with this command: python manage.py createcachetable Write business login. (product/views.py) django.views.decorators.cache.cache_page()¶ def heavy_view(request): cache_key = 'product' cache_time = 18 # time to live in seconds result = Product.objects.all() # some calculations here for l in result: a … -
dict in django request.session resets to previous value
According to the task I have to make Django chat with Long polling technology (without the use of redis, websokets and so on). For the authorized user I store in the request.session dict with last message ID in each thread (dialogue): request.session['admin_lastid'] = {'dialogue1': 112, 'dialogue2': 34} I have two views with long polling. One (def get_new(request)) scans the ongoing dialogue and updates the dict when a new message: request.session['admin_lastid']['dialogue1'] = current_thread.lastid request.session.save() request.session.modified = True Another view (def scan_threads(request)) scans all the dialogue for new messages and this view reads the values from the request.session['admin_lastid']. But I see the strange behavior of the session. When the view get_new is recorded in the request.session['admin_lastid'] a new value, the next view scan_threads considered the updated value. But when the view get_new start up again, he saw the old value. Why? Can not understand... -
How to add a steam login button to a website (django site)
I would like to add a Steam login button to a web site I created with django. Could you show me a source of this? Thank you. -
How to change admin templates directory folder
I set an address for the DIRS in TEMPLATES setting in my project's settings.py file and also i change APP_DIRS to False. now, all of the templates will running but when i go to localhost:8000/admin, it generates an error that said "Template Does Note Exists". TemplateDoesNotExist at /admin/ admin/index.html i dont want to APP_DIRS be True. how can i solve this problem? this is the settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Save Image in django from android app
I was having problem while saving picture in django from android app. I searched for 2 days and finally solved the problem. I am sharing this so that it might help. Please see the answer below -
nginx is giving django-axes (access logging middleware) a null ip address
I'm having trouble accessing the login page of my site. It has django-axes access logging middleware watching it: from axes.decorators import watch_login @method_decorator(watch_login, name="dispatch") class UserLogin(FormView): ... A GET request to the login page results in: DataError at /path/to/login/ invalid input syntax for type inet: "b''" The ip address in the traceback (as per the error) is b''; so I guess the nginx proxy is not passing this. Here's an extract of my nginx sites-available config (I have not enabled ssl while debugging this): upstream app_servers { server unix:/tmp/gunicorn.sock; } location / { proxy_pass http://app_servers; proxy_redirect off; real_ip_header X-Real-IP; proxy_set_header Host $http_host; proxy_set_header User-Agent $http_user_agent; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } What am I missing from my nginx config to get django-axes working? -
ImportError: No module named compat
I am trying to tracking user activities on my site. for that purpose i am using django-tracking2 package. but after successfully installation of django-tracking2 package,i am getting an error:- No module name compat Here is full trace-back:- This is error message i am getting while hiting runserver command so anyone having idea ? how to solve this please let me know -
Spring Cloud Eureka with Python Django client
Can we discover python Django micro service from spring Eureka registry?(without using Site car or any java library) I try this on also. but I haven't success yet. from eureka.client import EurekaClient import logging logging.basicConfig() ec = EurekaClient("MyApplication", eureka_domain_name="python_client", region="127.0.0.1", vip_address="http://192.168.120.14:8761/eureka", port=8761, ) print ec.get_zones_from_dns() print ec.get_eureka_urls() print ec.register() print ec.update_status("UP") # Or ec.register("UP") print ec.heartbeat() -
Setting up broker url
I would like some help here. All I want is to add Celery and RabbitMQ to my django project. I followed this tutorial Celery - First Step with Django. and It was able to work. However how could I customize this setup? CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' How can I change guest as a real given userId and password? Where should I configure it like: amqp://userid:1234@sample.com:5672 -
Scalable user relationship architecture
I am building a relationship between User models. The following is the approach I have taken. There exists three models RelationRequest, RelationType, Relationship. RelationRequest: basically like a friend request in facebook. ReltaionType: this can be either friendship or block Relationship: this models holds the relations, all ForeignKeys .user_one to user_two and related by a relationtype so the models looks something like this (ignore max_length and stuff like that for now). from userpackage import User class RelationType(models.Model): """ Friendship, follow etc """ name = models.CharField() slug = models.SlugField() class RelationRequest(models.Model): """ A friend, follow request """ user_one = models.ForeignKey(User) user_two = models.ForeignKey(User) reltaiontype = models.ForeignKey(RelationType) class Relationship(models.Model): user_one = models.ForeignKey(User) user_two = models.ForeignKey(User) relation = models.ForeignKey(RelationType) The working is as described below, user_one initiate a RelationRequest named Friendship user_two accepts the request and a Relationship object is created. So my questions are the following, Is this database design scalable with django and postgres? Will the increased use of ForeignKeys make the system slower? How do people do this job normally? (Industry standard) What can I do to make it scalable? Thank you for any directions. -
Allauth authentication on homepage not working
So to allow Django's allauth to work on my homepage, I copied the allauth HTML for the login and signup forms to my own base.html (the login form can be seen here: https://github.com/pennersr/django-allauth/blob/master/allauth/templates/account/login.html#L36) So this successfully renders the form and its fields on my homepage. However when I click submit on the login form, it just redirects me to allauth's /accounts/login URL, which renders the same form. Only after that does submitting the form work. It's the same with the signup form, when I submit the signup form on my homepage, it redirects me to /accounts/signup and then the signup works after submitting again. How can I make the login/signup work initially from my homepage? -
How to catch email sending exceptions in Django 1.10
I am sending email messages at different places in my application. msg.send(fail_silently=True) helps to avoid error page from displaying to end users when there is an error while sending the email. Is it possible to catch this error so that I make a log or execute a custom function? Note: I am using Django 1.10.4 with Python 3.5.