Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'logout' with no arguments not found. 1 pattern(s) tried: ['$logout/$']
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.11.4 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\contrib\admin\sites.py" in wrapper 242. return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\contrib\admin\sites.py" in inner 214. if request.path == reverse('admin:logout', current_app=self.name): File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\urls\base.py" in reverse 91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "C:\Users\Priyanshu\projects\ecommerce\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix 497. raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /admin/ Exception Value: Reverse for 'logout' with no arguments not found. 1 pattern(s) tried: ['/$logout/$'] -
Django is not connecting with mongodb
I am trying setup my project in virtual env, I created project RestUserAPI and an app UserAPI. I want to use mongodb as my default database so i changed my settings.py file and used djongo. Problem is, i am not using db.sqlite3 database and i even deleted sqlite3 file from my repository but still django is not connecting with mongodb and some how also storing data somewhere else and not throwing any error when i run python manage.py runserver, It should return error like can not connect to mongodb. here is my files. settings.py """ Django settings for RestUserAPI project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os, mongoengine # mongoengine.connect( # db='UserDataBase', # host='localhost', # ) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6!muk4-tdycxan2auyj38q!148dxucc#2r@knax@n0$(btvx1a' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
Reverse foreign key with cross reference table - Django Rest Framework
I'm trying to create an API endpoint which will provide summary data about a user and the groups they are in. My current models have User and UserGroup connected with a Membership Model. My current problem is I can't seem to get the list of group members to work. Am I on the right track here? Or is there a better way to handle serialization/querying of models with many to many relationships? Models: class UserGroup(models.Model): group_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) description = models.CharField(max_length=200) deleted = models.BooleanField(default=False) class Membership(models.Model): group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name="members") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_groups") isAdmin = models.BooleanField(default=False) Serializers: class MemberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name') class MembershipSerializer(serializers.HyperlinkedModelSerializer): name = serializers.ReadOnlyField(source='group.name') description = serializers.ReadOnlyField(source='group.description') members = MemberSerializer(source='group.members', read_only=True, many=True) class Meta: model = Membership fields = ('name', 'description', 'members') class UserSerializer(serializers.ModelSerializer): groups = MembershipSerializer(source='user_groups', read_only=True, many=True) class Meta: model = User fields = ('username', 'groups') Current Output: { "username": "User 1", "groups": [ { "name": "Group 1", "description": "Test Group", "members": [ {} ] }, { "name": "Group 2", "description": "Test Group 2", "members": [ {} ] } ] } Expected: 'members' contains a list of users who are in the UserGroup. -
NoReverseMatch error at URL, X is not registered namespace
I'm trying to add simple shopping cart functionality to my django app, and have been following this pretty straight forward tutorial. When attemting to access my cart page however, I get the error that: NoReverseMatch at /cart/ 'main_page' is not a registered namespace main_page is the name of my primary app, as opposed to 'shop' in the tutorial. In my models.py for main_page, after defining all my fields I have: def get_absolute_url(self): return reverse('main_page:collection_detail', args=[self.id]) Which seems to be in line with the example shown in the tutorial here The code in my template which is causing the error is: <a href="{% url "main_page:collection_detail" %}" class="btn btn-default">Continue Shopping</a> Everything seems to line up as far as I can see. What am I missing? -
how to use auth_user from another database(not default database)
I have two databases (default database and sample database) . i want to use auth_user table from sample database not from default database (by default , it is taking from default database ).how is this possible? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': 'test@123', 'HOST': '10.40.40.170', 'PORT': '3306', }, 'sample': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test1', 'USER': 'root', 'PASSWORD': 'test@123', 'HOST': '10.40.40.170', 'PORT': '3306', }, } i have added one extra column for auth_user table from sample database.so i want to use that table. (i cant use auth_user from default database, because my requirement is like that) i referred this link < https://docs.djangoproject.com/en/2.1/ref/models/options/ > -
How to create multiple versions of a site in django but run under same domain but different url
I have a website i developed with django and i want it to have 2 different front-end designs but same functionality. something very similar to django multi-language functionality. So i want a user to be able to access the two designs from different url by specifying the version i.e localhost:8000/v1 localhost:8000/v2 I created a middleware to check the current version and revert to a default if non is found. middleware class VersioningMiddleware(MiddlewareMixin): def process_request(self, request): path = request.get_full_path() tokens = path.split("/") if len(tokens) > 1: if tokens[1] in APP_VERSIONS: # APP_VERSION is a list ['v1','v2',...] request.app_version = tokens[1] new_url = "v1%s" % path return HttpResponseRedirect(new_url) and also i mapped out all app url conf using this urlpatterns = [ path('admin/', admin.site.urls), url(r'^(?P<version>[a-z][0-9])?/', include('base.all_urls','')),] So the problem with this approach is that all my views are expected to take an optional parameter version which i dont like. So i need a better way to achieve this without having to have different codebase for different version. If i could pass the version to the view without having to specify the optional parameter to all my views, my plan is to use that version to render the appropriate template that each view render. … -
How do I implement text forms(?) using django or HTML
First sorry for my bad english and my unclear question. I am trying to make my own blog, and to make article posting feature. Using django basic form is convenient, but its form is just plane. I want to use underline, change colors, use images. So basically I want to implement the feature inside the picture below. the picture I want to implement the thing in the black oval(I don't know its specific name... T.T). So is there any APIs or feature implemented in django itself? Or can you tell me what it is called? I don't know what it is called in english so I can't search for it at all.. Thank you for reading my question. -
How can I jump to another line of a python code while the previous line is still running
I am trying to create a python script to auto-run all my Django commands, but the script execution stops at os.system('python manage.py runserver') and does not run the next line because os.system('python manage.py runserver') needs to keep running. How do I run the next line of code while os.system('python manage.py runserver') is still running? I tried using the python sleep method to wait a few seconds and then run the next line, but it did not work. Here is my code: import os, webbrowser, time os.system('pipenv shell') os.system('python manage.py runserver') time.sleep(5) webbrowser.open('http://127.0.0.1:8000', new=1, autoraise=True) The execution stops at os.system('python manage.py runserver') but I want it to run webbrowser.open('http://127.0.0.1:8000', new=1, autoraise=True) while os.system('python manage.py runserver') is still running. -
after django upgrade 1.8 to 1.11.17 , my program can't start
from django.template.base import TagHelperNode, VariableNode ImportError: cannot import name TagHelperNode I had upgrade Django from 1.8.14 to 1.11.17 -
Better 500 messages with DRF api view
So I would like for all my API's to send back nice 500 messages if something goes wrong, ideally, in my current set-up of Python 3.7 Django app using DRF (Django rest framework). To solve this I have tried to make a decorator (overwriting the api_view decorator would probably be better though). But it does not work as intended. For instance, if I put in an intentional error of 0/0 I get: TypeError: Object of type 'ZeroDivisionError Here are my functions @api_view(["POST"]) @view_500_wrapper def foobar(request: Request, foo_id: UUID): if request.method == "POST": data = dostuff() 0/0 return Reponse(data,status=201) def view_500_wrapper(f): def wrapper(*args, **kw): try: return f(*args, **kw) except Exception as inst: exception_dict = get_exception_dict(f, inst, *args, **kw) return Response(exception_dict, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return wrapper I have a feeling it is a combination of the order of executing between the two decorators, their inputs and return objects that are wrong. Here is the full error message Error Traceback (most recent call last): File "/opt/project/middletier/tests/test_views.py", line 660, in foobar format='json' File "/usr/local/lib/python3.6/dist-packages/rest_framework/test.py", line 300, in post path, data=data, format=format, content_type=content_type, **extra) File "/usr/local/lib/python3.6/dist-packages/rest_framework/test.py", line 213, in post return self.generic('POST', path, data, content_type, **extra) File "/usr/local/lib/python3.6/dist-packages/rest_framework/test.py", line 238, in generic method, path, data, content_type, secure, … -
Azure Cosmo Db with Django
I want to know how to connect Azure Cosmo Db with Django Project locally And also in cloud..I need a Example projectvideo or explanation I know only cosmos db with c# I need code for coonectivity Django with cosmodb -
No Module found error while deploying django on apache
I have been trying to deploy django on apache, this is my httpd.conf file <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess app1 python-path=/home/naveen/cloudserver:/home/naveen/cloudserver WSGIScriptAlias /radi /home/naveen/cloudserver/cloudserver/wsgi.py application-group=%{GLOBAL} process-group=app1 <Directory /home/naveen/cloudserver/> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot /home/naveen/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined and this is my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cloudserver.settings') application = get_wsgi_application() when i try to open this application i get internal server error, this is my log file which shows the following errors [Wed Dec 26 08:42:42.730573 2018] [wsgi:error] [pid 1846] File "<frozen importlib._bootstrap>", line 969, in _find_and_load [Wed Dec 26 08:42:42.730578 2018] [wsgi:error] [pid 1846] File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked [Wed Dec 26 08:42:42.730595 2018] [wsgi:error] [pid 1846] ImportError: No module named 'cloudserver' it says module not found cloudserver, how to resolve this error? cloudserver module is present in that folder?I have been stuck in this stage for almost 2 days, every tutorial i try to use endup in this error.How to properly configure my django project to run on apache? -
Django get_attribute after Post
How can I disable the automatic get_attribute right after I perform a post request? I have disabled get request by specifying viewset/mixins -
'NoneType' object has no attribute 'from_settings_file' (boxsdk.JWTAuth)
I'm attempting to use django to upload files to box.com using boxsdk, while deploying the app to heroku. The problem is that my code works fine on local dev server, but not on heroku. For local dev server, I'm able to import a json file for auth. For heroku, since it wont accept conf files, I have used heroku:config to store the file as an environment variable. from boxsdk import JWTAuth, Client from io import StringIO import os jsonpath = f'{STATIC_ROOT}/conf/box.json' try: auth = JWTAuth.from_settings_file(jsonpath) except: BOXCONF = os.environ.get('BOXCONF') msg = f'The value of BOXCONF is {BOXCONF}' capture_message(msg) auth = JWTAuth.from_settings_file(StringIO.new(BOXCONF)) client = Client(auth) service_account = client.user().get() print('Service Account user ID is {0}'.format(service_account.id)) I have tested that BOXCONF is set, by using capture_message of Sentry, and it displays the following: The value of BOXCONF is { "boxAppSettings": { "clientID": "abcd", "clientSecret": "abc", "appAuth": { "publicKeyID": "xyz", "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nblabla\n-----END ENCRYPTED PRIVATE KEY-----\n", "passphrase": "1234" } }, "enterpriseID": "1234" } The error message I receive is: AttributeError: 'NoneType' object has no attribute 'from_settings_file' File "django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 124, in _get_response response … -
Is there any way to know the status of a password reset in Django?
I use non-standard registration procedure. Basically, the webadmin registers the user, and then the user gets sent an email with a password reset. I'd like to give the information whether that password reset has happened or not to the webadmin, but can't seem to find anything on the official Django docs. Does anybody know whether this is possible? Thanks in advance. -
Include a simple function inside Django HTML template
I currently have a function called "copyright" (a dynamic copyright message) that I am trying to include into my base Django template, like below: def copyright(): some code some more code print(finaloutput) I have it sitting in my modules/utils.py which is in my assets directory which I have registered in my static directories. I want to be able to call that function like {{ copyright }} straight in my top level base.html inside my main templates folder. I have tried everything to ensure I am loading the staticfiles with no luck. Am I approaching this the wrong way? -
Cannot access object.id in postgreSQL with django app deployed to Heroku (internal server error 500)
I deployed a Django blog app to Heroku and having problem accessing the objects through the objects' id. When Debug=True in settings.py, everything works fine. And even when Debug=False, there is no other problem such as static files issue, things are working fine. I searched many articles but most of them are about static files issues, not same as my situation. First, My models.py: class Post(models.Model): title = models.CharField(verbose_name='TITLE', max_length=120) slug = models.SlugField(verbose_name='SLUG', unique=True, allow_unicode=True, max_length=120) content = RichTextUploadingField(verbose_name='POST CONTENT') create_date = models.DateTimeField(verbose_name='Created date', auto_now_add=True) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) class Bookmark(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(verbose_name='SLUG', unique=True, allow_unicode=True, max_length=100) address = models.URLField(verbose_name='url', unique=True) description = models.CharField(max_length=256) category = models.ForeignKey(BookmarkCategory, on_delete=models.CASCADE, null=True, blank=True) And in the urls.py: path('post/<int:id>/', views.PostDetailView.as_view(), name='post_detail'), path('bookmark/<int:id>/update/', views.BookmarkUpdateView.as_view(), name='bookmark_update'), The problem occurs when I try to access my Post or Bookmark object in the templates using id, like: {% url 'myblog:post_detail' post.id %} or {% url 'myblog:bookmark_update' bookmark.id %} What I'm expecting is the DetailView or UpdateView of the objects, but instead I have internal server error (my 500.html shows up.)I tried int:pk instead of int:id too, but just same error. Again, things are totally fine when Debug=True, and also everything else works fine even … -
Django Serialize return id of user, but i need username
this is my model: class HighScore(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE) highScore = models.IntegerField(blank=True, null=True) createDate = models.DateTimeField() def __str__(self): return "{}_HighScore".format(self.user) and this is my view: def pullUserNames(request): top_score = createHighScore() top_users = (HighScore.objects.order_by('-highScore').filter(highScore__in=top_score[:10])) top_users_serialized = serializers.serialize('json', top_users) top_users_json = json.loads(top_users_serialized) data = json.dumps(top_users_json) return HttpResponse(data) response is: [{"model": "scoremg.highscore", "pk": 2, "fields": {"user": 2, "highScore": 650, "createDate": "2018-12-25T20:34:51.826Z"}}, {"model": "scoremg.highscore", "pk": 1, "fields": {"user": 1, "highScore": 271, "createDate": "2018-12-17T21:48:34.406Z"}}] in this response {"user": 2, "highScore": 650, "createDate": "2018-12-25T20:34:51.826Z"} , highScore and createDate have good face, but user is id not username, how can i edit it to return username? i test print(top_users) after line two in above view, and it print --> user2_HighScoreuser1_HighScore thanks -
How can I compress this python, django code?
I'm creating a simple tag in django. Here's my code but I think it's possible to shorten it a little bit. items = [] for vote in choice.vote_set.all(): if vote not in items: items.append(vote.user) types = {} for user in items: if user.userprofile.typeOfPerson not in types: types[user.userprofile.typeOfPerson] = Vote.objects.filter(Choice=choice).count() percent = 0 for type, value in types.items(): percent += value if percent == 0: percent = 1 values = {} for type, value in types.items(): if type not in values: values[type] = value / percent * 100 return values -
Django: how save bytes object to models.FileField?
My web application has the following structure: backend with Django frontend with React. I have a form with React. I send a file from client form and I receive the file in my Django application with an APIView. I receive a m3u file as bytes object. b'------WebKitFormBoundaryIaAPDyj9Qrx8DrWA\r\nContent-Disposition: form-data; name="upload"; filename="test.m3u"\r\nContent-Type: audio/x- mpegurl\r\n\r\n#EXTM3U\n#EXTINF:-1 tvg-ID="" tvg-name="... I would save the file in a Django model to a models.FileField and convert bytes object to m3u file. How you do it? -
after extending base.html ,my child html thiings are not showing
before extending i have checked all connections and file paths but after extending my child codes vanises base.html <!DOCTYPE html> {% load staticfiles%} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="icon" type="image/x-icon" href="{% static '/images/icon.png' %}" /> <title>hiremyprofile.com</title> <link href="{% static "/css/base.css" %}" rel="stylesheet" type="text/css"/> </head> <body> <div class="header"> <span class="name">allgood</span> <button class="btn1 ">Resume</button> <button class="btn2 ">Portfolio</button> <span class="profileimage"><img src="{%static '/images/profile1.png' %}" alt="hiremyprofile.com" style="width:40px;height:40px"></span> </div> </body> </html> skills.html {% extends 'app/base.html' %} {% block content %} <p>skills</p> <p>skills</p> <p>skills</p> {% endblock %} -
Django: KeyError when creating DB Table from CSV
I need to create a table from a CSV file. I think I can do it with different libraries, but in this case I've choosen to use pandas, as I'll need it more in the near future for some data analysis. I've a script but I'm getting this error: Traceback (most recent call last): File "/home/gonzales/Escritorio/virtual_envs/stickers_gallito_env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3078, in get_loc return self._engine.get_loc(key) File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 1867 Data in Dropbox: https://www.dropbox.com/s/o3iga509qi8suu9/ubigeo-peru-2018-12-25.csv?dl=0 script: import pandas as pd import csv from shop.models import Peru from django.core.management.base import BaseCommand tmp_data=pd.read_csv('static/data/ubigeo-peru-2018-12-25.csv',sep=',', encoding="utf-8") class Command(BaseCommand): def handle(self, **options): products = [ Peru( departamento=tmp_data.ix[row]['departamento'], provincia=tmp_data.ix[row]['provincia'], distrito=tmp_data.ix[row]['distrito'], ) for row in tmp_data['id'] ] Peru.objects.bulk_create(products) models.py class Peru(models.Model): departamento = models.CharField(max_length=100, blank=False) provincia = models.CharField(max_length=100, blank=False) distrito = models.CharField(max_length=100, blank=False) def __str__(self): return self.departamento -
Django passing string arguments
Please how can I pass a string arguments to django path path('mysite/?$', search, name='search') instead of the ?$ I want to pass the argument that the get methode has ! how can I do that ?? -
play audio in vc discord using discord.py
i tired to play while i join in voice chat, but i faced many problem, hope it work, please i need help, i searched alote without positive result. import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio import time import random from discord import Game Client = discord.client client = Bot('.') Clientdiscord = discord.Client() @client.command(pass_context=True) async def yt(ctx): url = ctx.message.content url = url.strip('yt') author = ctx.message.author voice_channel = author.voice_channel vc = await client.join_voice_channel(voice_channel) player = await vc.create_ytdl_player(url) player.start() client.run('my Token') =-=-=-= after that i tired to play video after i joined the voice channel (.yt https://www.youtube.com/watc........) Error list : Ignoring exception in command yt `Traceback (most recent call last): File "C:\Users\Hema\AppData\Local\Programs\Python\Python36-32\lib\site- packages\discord\ext\commands\core.py", line 50, in wrapped ret = yield from coro(*args, **kwargs) File "C:\Users\Hema\Desktop\Music - Copy - Copy.py", line 21, in yt vc = await client.join_voice_channel(voice_channel) File "C:\Users\Hema\AppData\Local\Programs\Python\Python36-32\lib\site- packages\discord\client.py", line 3172, in join_voice_channel raise InvalidArgument('Channel passed must be a voice channel') discord.errors.InvalidArgument: Channel passed must be a voice channel The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Hema\AppData\Local\Programs\Python\Python36-32\lib\site- packages\discord\ext\commands\bot.py", line 846, in process_commands yield from command.invoke(ctx) File "C:\Users\Hema\AppData\Local\Programs\Python\Python36-32\lib\site- packages\discord\ext\commands\core.py", line 374, in invoke yield from injected(*ctx.args, **ctx.kwargs) … -
Wagtail - made custom slug but page not serving from it
I made a custom slug because the default slug does not meet my needs and already set the url_path with the new slug. But the page is still serving with the default slug. I've already set the url_path with the following code: def set_url_path(self, parent): super().set_url_path(self) if parent: self.url_path = parent.url_path + self.custom_slug + '/' return self.url_path But when I publish the page, it still returns the page with the default slug value. I thought Wagtail serves the page on url_path. What other methods or variables do I have to override for the page to be served on my custom slug?