Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jwt Decode using PyJWT raises Signature verification failed
I'm running into a weird issue with decoding the jwt token in the django views. If I try jwt.decode('encoded_token', 'secret') then I see the "Signature verification failed" message. In order to escape from this issue I've set the verify flag to False: jwt.decode('eroded_token', 'secret', verify=False) This gives the decoded payload with no error but I'm trying to figure out how I can verify the token successfully without setting the verify flag to False. Any Ideas? Thanks -
django collectstatic with settings flag throws logging path error using incorrect logging path
I've recently started restructuring a project to use two scoops style configuration, with a config package, with settings inside it. Within that package, there's _base.py, development.py, staging.py and production.py. Since this is deployed as a WSGI app with Apache, I'm using a json file for environment variables, such as AWS credentials, db username/passwords and such. In short, following suggestions listed at https://medium.com/@ayarshabeer/django-best-practice-settings-file-for-multiple-environments-6d71c6966ee2 When deploying on staging, I have the wsgi app running through apache. In addition, manage.py $COMMAND is working with the --settings=config.settings.staging flag set. That is, with the exception of collectstatic. It's apparently trying to access an invalid logging path, and I can't figure out why its using that particular path which is not defined in the settings file being used. Current output of collectstatic run: (staging)ubuntu@farmer-stage:~/public_html/django/project$ ./manage.py collectstatic --help Using configuration [config.settings.staging] Using configuration [config.settings.staging] Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/.virtualenvs/staging/lib/python2.7/site-packages/django/utils/log.py", line 86, in configure_logging logging_config_func(logging_settings) File "/usr/local/lib/python2.7.11/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/local/lib/python2.7.11/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure … -
Extending Django filer image model to add category
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could you help me with this topic? -
Using Django-bootstrap3 . How to target individual form fields to adjust CSS
Here is my code below. I need to be able to adjust the appearance of the individual fields and labels in the CSS but I am not sure how to do this for the code below. Basically the question how to I know what class or ID selector I need to target or what settings I need to use <form action="/post/" method="post" class="form"> {% csrf_token %} {% for field in form %} {% bootstrap_field field layout='inline' %} {% endfor %} {% buttons %} <button type="submit" class="btn btn-success"> {% bootstrap_icon "pencil" %} Post </button> <button type="reset"> {% bootstrap_icon "erase" %} Clear </button> {% endbuttons %} </form> I am a complete newbie for this. I have been through the docs but I am not sure where to start -
Django runnning on heroku: have to login again after every dyno restart
I am running a django web app on Heroku. I'm using the hobby-dev plan, so the dyno doesn't go to sleep after inactivity, but it does restart once per day. After every restart, I need to re-enter my login credentials to use the admin interface. How can I make my login session persist after a dyno restart? -
Problems with MongoDB and Python
Good evening guys, I need some help. I need to implement a MongoDB database as a default or secondary (if possible) in an application made in Django. Currently my Django application works with Tweepy, I need to save the captured data in the NoSQL database. I chose MongoDb, but I found several information saying that it is only possible to use with python 2.7 (my application was built in python 3.5). Is there any way to do it? I have already tried to use pymongo, mongodbengine, among others without success ... I believe that I am not doing correct. I need guidance in this process (I did not find information for newer versions of django and python, and the documentation has not been updated) -
Delete confirmation in django
I am working on a project in django. I have this part of code, when I want to delete an album, it shows Yes or No to choose, but the problem is, whatever the choice I make, it always delete the album. I know I have to add something to the confirmation option but I don't want where or what. <form action="{% url 'music:delete_album' album.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}" /> <button type="submit" onclick="confirm('Are you sure ?')" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> and this is the delete_album view : def delete_album(request, album_id): album = Album.objects.get(pk=album_id) album.delete() albums = Album.objects.filter(user=request.user) return render(request, 'music/index.html', {'albums': albums}) -
Calculate Django Data query according to date
This is my models.py file. class CustomerInfo(models.Model): customer_name=models.CharField('Customer Name', max_length=50) customer_mobile_no = models.CharField('Mobile No', null=True, blank=True,max_length=12) customer_price=models.IntegerField('Customer Price') customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10) customer_sell_date = models.DateTimeField('date-published') customer_product_id=models.CharField('Product ID',max_length=150,null=True, blank=True) customer_product_name=models.CharField('Product Name', max_length=50) def __str__(self): return self.customer_name When I find data query information by date, I want to calculate "customer_price" by only selected date. Then I will show to my HTML page. This is my search query by date. customers = CustomerInfo.objects.filter(customer_sell_date__day=datelist) Now, Calculate all ""customer_price"" within my selected date. -
Heroku sais: "Requested setting LOGGING_CONFIG" but it is set?
I'm trying to setup a Django site on Heroku. I get this error message: 2017-10-07T21:03:33.416585+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. But if I run Heroku config, the var is set. Why is it not recognized? === dagenssalg Config Vars DISABLE_COLLECTSTATIC: 0 LOGGING_CONFIG: off Many answers in here mention the wsgi.py file, but I can't see anything wrong with that: import os from django.core.wsgi import get_wsgi_application from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) os.environ.setdefault("DJANGO_SETTINGS_MODULE","dagenssalg.settings") application = get_wsgi_application() Any help is most appreciated. Best regards Kresten -
Filter objects by exact position of character through a variable
code: 1)CSE-101 2)CSE-102 3)CSE-101 4)CSE-204 5)CSE-106 6)CSE-201 position: 012345678 i want to make a search for the value which is stored in variable . suppose,I want' to make a search for all the codes with 2 at position 4. So the search should return the 4th and 6th code. I've looked at django look_up functions. Is there a way to make a search like this? this is correct regular expression for desired output,in the case of direct use of numerical number 2. Model.objects.filter(code__regex=r'^.{4}2') but i want make a regular expression like that .suppose s=2, then i want to include s with this regular expression. -
how to solve django social auth error on facebook?
i installed social-auth-app-django and followed the guide here to integrate facebook login to django 1.8.18 .The problem is when i go to "http://localhost:8000/social-auth/login/facebook/" I get below error Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Here is my settings.py file # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print (BASE_DIR) SECRET_KEY = 'x220#z=kwd)kjiu#u+p$)v0lu+rspyosg+)l*k$ux9j)1h' DEBUG = True ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = ( ... 'account', 'social_django', #social classes ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) ROOT_URLCONF = 'bookmark.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, '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', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', # <-- ], }, }, ] WSGI_APPLICATION = 'bookmark.wsgi.application' STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') from django.core.urlresolvers import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', #< --facebook 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) SOCIAL_AUTH_FACEBOOK_KEY='1742581762468139' SOCIAL_AUTH_FACEBOOK_SECRET='eae7dsfdsfdsf90b219becb84' urls.py file from django.conf.urls import include, url from django.contrib import admin from django.conf import … -
Using another apps model as Foreign Key
The error I'm getting. insert or update on table "soccer_game" violates foreign key constraint "soccer_game_match_id_7834e80f_fk_soccer_match_id" DETAIL: Key (match_id)=(6) is not present in table "soccer_match". I have an app for creating matches called home. It has a Match model in it. # home.models.py from django.db import models class Match(models.Model): pick = models.CharField(max_length=30, choices=GAMES) name = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True) players = models.IntegerField(choices=NUM_PLAYERS) def __str__(self): return self.name class Meta: verbose_name_plural = "matches" The GAMES choices is a list of all the other sport/game apps. One of them is soccer which has these models. # soccer.models.py from django.conf import settings from django.db import models from home.models import Match class Player(models.Model): name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number = models.IntegerField(default=0) score = models.IntegerField(default=0) def __str__(self): return self.name.username class Settings(models.Model): match = models.ForeignKey('home.Match') time = models.IntegerField(default=0) class Meta: verbose_name_plural = 'settings' def __str__(self): return self.match.name class Game(models.Model): match = models.ForeignKey('home.Match') player = models.ForeignKey(Player) def __str__(self): return self.match.name Then in the home app the view to create a match. # home.views.py from .forms import MatchForm from home.models import Match from soccer.models import Game, Player, Settings # Create your views here. @login_required def create_match(request): form = MatchForm(request.POST or None) context = { 'form': form, } if request.method == 'POST': … -
Fail to create a superuser in django, when use a router
I tring to create mongodb/mysql project on Djago 1.11.4 with python3. I intended to use mysql for user authentification and mongodb for all other purposes. I master to create a users but failed in creating a superuser. Here is what happend, when I tried to create a superuser: $ python3 manage.py createsuperuser username=Admin System check identified some issues: WARNINGS: ?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs. Email address: admin@example.com Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 170, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user user.save(using=self._db) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 834, in save_base with transaction.atomic(using=using, savepoint=False): File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 158, … -
Django include - render content inside block
How can I render contents of header-actions block in page.html to master template. Currently, the block isn't rendered. header.html <header> {% block header-actions %}{% endblock %} </header> master.html <html> <body> {% include 'header.html' %} Some content </body> </html> page.html {% extends 'master.html' %} {% block header-actions %} Extra action {% endblock %} -
Consume kafka messages from django app
I'm designing a django based web application capable of serving via Web sockets data that need to be consumed from Kafka topic. At this time, I came up with a solution splitted in two components: one component which consumes from kafka, perform some basic operations over retrieved data, and send the result to the django app using an http request. After request have been received, a message is written over a specific django channel. Is there a better architecture to address this kind of scenario? Should I enclose all the Kafka part in a "while True" loop in a celery async task? Should I spawn a new process when django starts? If so, can I still use the django signals to send the data via web socket? Thanks, Fb -
Setting up sockets on Django
Have a django project with django-channels (using redis) allows uset to start background process and should get back a live feed of this on the page. Here's a recording of this: https://youtu.be/eKUw5QyqRcs Sockets disconnects with a 404. Here's the socket's code: $('.test-parse').unbind().click(function() { ... $.ajax({ url: "/start-render-part", type: "POST", dataType: 'json', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, data: JSON.stringify(data), success: function(response){ if (response['status'] == 'ok') { if (response['unique-id']) { unique_processing_id = response['unique-id']; } if (response['task_id']) { task_id = response['task_id']; } var add_to_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'task_id': task_id, 'command': 'add_to_group', }); var socket = new WebSocket("ws://{HOST}/render-part/".replace('{HOST}', window.location.host)); socket.onopen = function() { console.log('opened'); var add_to_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'task_id': task_id, 'command': 'add_to_group', }); socket.send(add_to_group_msg); var get_status_msg = JSON.stringify({ 'task_id': task_id, 'unique_processing_id': unique_processing_id, 'command': 'check_status', }); socket.send(get_status_msg); }; socket.onmessage = function(event) { console.log("onmessage. Data: " + event.data); var data = JSON.parse(event.data); if (data.state == 'PROGRESS') { console.log(data.status); update_progress(data.current); } else if (data.state == 'FINISHED') { var remove_from_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'command': 'remove_from_group', }); socket.send(remove_from_group_msg); unique_processing_id = … -
SECURE_SSL_REDIRECT in Django forwarding traffic to localhost
I have introduced SSL in my website, and I need make redirection from HTTP to HTTPS. I have website on Django 1.4.5. I have installed djangosecure package using pip and added to settings.py MIDDLEWARE_CLASSES = ( ...., 'djangosecure.middleware.SecurityMiddleware', ) INSTALLED_APPS = ( .... 'djangosecure', ) SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') ALLOWED_HOSTS = ['*'] but now when when I'm trying open website I have redirection to https://127.0.0.1:8756 instead of my domain with https. -
DRF view returns Invalid username/password with @permission_classes((AllowAny, ))
So I have this method-like api view with AllowAny as permisson class decorator: @api_view(['POST']) @permission_classes((AllowAny, )) But when I reach with the browser to the url it renders the DRF api template with a 403 HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } What I am missing? I dont need to specify a setting DEFAULT_PERMISSION_CLASSES if I am forcing one through the decorator right? -
Heroku Deployment Issue - Python version
I have been working on a Django project that I am trying to deploy to Heroku. I've followed a tutorial from Python Crash Course. When I enter git push heroku master, I get the following as a response: Counting objects: 73, done. Delta compression using up to 4 threads. Compressing objects: 100% (65/65), done. Writing objects: 100% (73/73), 26.20 KiB | 0 bytes/s, done. Total 73 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.2 (you are using Python-2.7.12, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.2). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing Python-2.7.12 remote: ! Requested runtime (Python-2.7.12) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fathomless-scrubland-11916. remote: When I Python --version the cmd line returns 2.7.14 which is the most up-to-date version. I feel like this error is telling me I need to use Python3 but their site says that 2.7.14 is … -
Holoview chart won't appear in Django site
i know there is probably something simple i am doing wrong, but i don't know where else to get an answer. I created a django site and the following function returns holoview html: from django.shortcuts import render from django.http import HttpResponseRedirect from charts.models import Ord from IPython.display import display_html import pandas as pd import holoviews as hv hv.extension('bokeh') renderer = hv.renderer('bokeh') # Create your views here. def displayChart(request): df = pd.DataFrame(list(Ord.objects.using('DB').all().values('ordtyp')[:500])) df = df.groupby([df.ordtyp]).size().reset_index(name='counts') bars = hv.Bars(df, kdims=[('ordtyp', 'Order Type')], vdims=[('counts', 'Count of Orders')]) hv.Store.registry['bokeh'][hv.Bars] html = renderer.html(bars) return render(request, 'charts/charts.html', {'html': html}) i put a block in the charts.html file as: {{ html |safe }} and all i get is a blank page. i then took the raw html that the renderer is returning and tried to copy and paste it directly into my html file, and got the same thing. the html is below. Also, the chart does work in Jupyter Notebook... can you tell me what i am doing wrong? charts.html: > <!DOCTYPE html> > <html> > <head> > <title>Charts</title> > </head> > <body> > {{html|safe}} > </body> > </html> raw html that the renderer returned: <div style='display: table; margin: 0 auto;'> <div class="bk-root"> <div class="bk-plotdiv" id="0dd69ef6-4d30-48f5-a95a-1201437920de"></div> … -
Load Content automatically in Django app
I'm working on a Django (1.10 & Python3) project in which I need to implement a logic as: We have articles from various categories, the user needs to tag these articles, mean when user read articles then he needs to provide his feedback rather it's relevant or irrelevant to his situation. We have to provide user's a list of categories when user select a category then all of the articles from that particular category will be available one by one to the user, mean it will show the first article to the user, when he tagged this article it will load next article automatically and also keep the user's tagging info because it's not necessary to tag all articles at once, user can tag few at a time when he can start from where has was stopped again. In simple: Would it be possible to send the user straight from their choice of a Category to the "Article Tagging" page with the next article to be tagged automatically loaded up and ready to be tagged, and the system keeps track of what the next article is that needs to be tagged? How can I accomplish this bit of functionality in … -
django admin listfilter dropdown
I'm currently trying to implement dropdown list filters in my django app but somehow can't get it to work. Tried at first with the diy approach but decided to try the django-admin-list-filter-dropdown app but still no succes settings.py INSTALLED_APPS = [ ... 'django_admin_listfilter_dropdown', ... ] admin.py from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter @admin.register(models.Project) class ProjectAdmin(admin.ModelAdmin): list_display = ( "name", "entry_date", ) list_filter = ( ("name", DropdownFilter), "entry_date", ) Any suggestions? Thanks in advance -
Django Main Page Not Loading in IE
Recently discovered my Django site will not load in IE. It is only the index page. I can browse every other page without issue. Chrome and Firefox load the site without issue. When in IE, visiting the main page prompts a download with a random file name which contains the rendered html code. -
Django + Arduino
I am trying to build a project that involves Arduino, GSM module and Django. If someone texts the number of the sim in the GSM module, I want to see it in my local web app(Django) and be able to reply to the sender's number using the web app. Is there any way that my GSM module connected on Arduino can connect/communicate with my Django project? Any Advice or Suggestions will be greatly appreciated. -
Javascript go to Django URL without redirecting the user
i created a upvote button in my blog, that send the user to a url then redirect the user to the previous page but i want to know if i can do this without redirecting the user in javascript i mean without using the a tag but using 'onClick' the button: <a href="{% url 'upvote' Post.id %}"><button>upvote</button></a> my view: def upvote(request, post_id): post = Post.objects.get(id=post_id) post.votes += 1 post.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))