Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can I create progressive web app in django framework or wagtail which one is best?
I am trying to build for website so I need to know that.what is progressive web app? and all devices or only moniter. -
Ckeditor/ django 2.0 admin body input disappeared
Hi I recently installed Ckeditor on django 2.0, turns out some of the css and js files are not loading properly, I manage to get Ck read the files but now my admin body input was disappeared. missing-admin-body As I am pretty new to django, I was wondering if I were doing anything wrong in the setting. (try to make a blog, url + generic view set up) setting.py > INSTALLED_APPS = [ 'personal', 'blog', 'contact', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'mysite.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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATIC_DIR … -
How do I redirect errors like 404 or 500 or 403 to a custom error page in apache httpd?
I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? I've tried the solutions available on the web but none seems to work -
Empty routes in DRF(Django Rest Framework)
I'm trying to register a simple method into a DRF and I'm having some problems. The route is not showing in API Explorer. It's probably something simple that I'm missing.. How can I get the register route to show in the API? Resuts (empty) GET /api/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept {} Urls from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers from rest_framework_jwt.views import obtain_jwt_token from reservations.views.homepage import HomepageView from users.views import UserViewSet """ API routes """ router = routers.DefaultRouter() router.register(r'test', UserViewSet, base_name='users') """ Route patterns """ urlpatterns = [ url(r'^$', HomepageView.as_view(), name='homepage'), url(r'^api/', include(router.urls)), url(r'^api-token-auth/', obtain_jwt_token), url(r'^admin/', admin.site.urls), ] Viewset # -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): def register(self, request): return Response({ 'status': 'User registered' }) -
Django: BootstrapCDN or
I am trying to make my first website. I am using Django for it. I have a question related to inclusion of css/js from Bootstrap. What is the difference between installing it and linking it using BootstrapCDN? What happens if that link is no longer accessible ? Will it affect the website? Can't I just include those files in statics directory? I have this in base.hml file of my app: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'flatly.css' %}"> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> I am a beginner, sorry if it is too naive to ask such a question. Thank you. -
Django: filtering on `DecimalField` doesn't work well?
This is my model: class Tick(BaseModel): . . trade_coin_volume = models.DecimalField( max_digits=15, decimal_places=8, ) trade_price = models.DecimalField( max_digits=15, decimal_places=8, ) . . I print out trade_coin_volume of all Tick objects: In [9]: for tick in Tick.objects.all(): ...: print(tick.trade_coin_volume) ...: 0.02120853 0.05000000 0.26628998 0.19354556 0.32299392 0.72599405 0.05955935 0.05354201 0.00767441 0.05101970 0.20967645 0.10000001 0.00500000 0.00899999 0.15274410 0.32104315 0.00300000 0.22695384 0.05000000 0.13894616 0.00631414 0.07967759 0.28592241 0.23765636 0.05777923 0.08883787 0.05000000 0.14535185 As you can see above, there are some 0.05000000 values. But when I filter Tick objects based on this field, In [11]: Tick.objects.filter(trade_coin_volume=0.05) Out[11]: <QuerySet []> In [12]: Tick.objects.filter(trade_coin_volume=0.05000000) Out[12]: <QuerySet []> It doesn't show anything! Why does it happen? -
How to test get_success_url in CreateView in Django
I am trying to write a test for the get_success_url method in a CreateView, to make sure it redirects to the newly created page. But the response status code is 405 instead of 302 as I expected. def get_success_url(self): return reverse_lazy('blog:blog-detail', kwargs={'slug': self.object.slug}) -
How to make django login_required decorator raise HTTP401 exception
I use Django login_required decorator, but i don't need login_required redirect to login url instead of raising HTTP401 Unauthorized exception. -
Is there a way to see in the console what objects the queries retrieved by implementing a middleware?
I managed to print out in the console the number of queries, the time it took to complete them and the raw SQL itself by using a middleware and connection.queries. How can I also see in the console what objects the queries retrieved? -
Error in Django 2.0 tutorial, part 7 -- is this a bug
When I follow the 2.0 tutorial, on part 7, I noticed there is an error symbol under "PUBLISHED RECENTLY" in this screenshot: The "was_published_attribute" was set to True in the tutorial. But if set it to False, it can show "False" correctly. Is this a bug? Any suggestion of fixing or workaround? Many thanks! I apologize that I describe this question poorly in the title. I appreciate it if anyone can suggest me a better title. -
Why is Django's authenticate taking too long to resolve?
I have a Django project that uses Django Rest Framework and its @list_route among others to make api calls from my front-end. The very first api call I make is: website.com/api/staffs/authenticate The endpoint code that catches that is: @list_route(permission_classes=(AllowAny,)) def authenticate(self, request): if request.user.is_authenticated: if is_staff_or_admin(request.user): return Response(StaffSerializer(request.user).data) data = {'detail': AuthenticationFailed.default_detail} return Response(status=status.HTTP_401_UNAUTHORIZED, data=data) That block of code takes a whopping 30-42 seconds to resolve! Any idea what might be causing this slowdown? -
django registration form does not save information
I am new to django . here I want to register user and I have a problem whenever the user hit signup button in registration.html nothing happens and when I go to the admin section no user saved so here are my codes note : all functions and templates works as expected , I think the problem in UserFormView or urls.py views.py : from django.http import Http404 from .models import Category, Item , Order from django.shortcuts import render, redirect from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate , login from django.views import generic from django.views.generic import View from .forms import UsrForm class IndexView(generic.ListView) : template_name = 'res/home.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() def detail(request, category_name): try: category = Category.objects.get(category_title = category_name) all_categories = Category.objects.all() items = category.items.all() except Category.DoesNotExist: raise Http404("Category does not exist") return render(request, 'res/menu.html', {'items': items,'all_categories': all_categories}) class UserFormView(View): form_class = UsrForm template_name = 'res/registration.html' def get(self, request): form = self.form_class(None) return render(request , self.template_name, {'form' : form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username , password=password) if user is not None: if user.is_active: login(request , user) return redirect('res') return … -
What is the advantage of using a Django bootstrap module over linking to bootstrap files directly?
I see there are Django bootstrap modules (e.g. crispy_forms, django_bootstrap). I am trying to decide whether to use a module or link directly to bootstrap files in a base html file like the following: <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script I have an understanding that with the modules I would do the styling in the code. With using bootstrap directly, I am thinking I have to style it in the template files. I am trying to see reasons why I should be using a module. Also, with the bootstrap modules would I be able to use all bootstrap features? -
What's the difference between Django ModelForm and models.Model?
I am learning Django but cannot understand ModelForm ans models.Model, could anyone explain the difference between them? Thanks! -
No module named 'social_django' when creating superuser
I'm running a django project and I get this error when I try to add a superuser with the command python manage.py createsuperuser the error I get is >File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) >File "/home/boidot/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) >File "/home/boidot/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) >File "<frozen importlib._bootstrap>", line 994, in _gcd_import >File "<frozen importlib._bootstrap>", line 971, in _find_and_load >File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'social_django' howerever I think I installed all the required packages in a virtual environment. the result of pip freeze certifi==2018.1.18 chardet==3.0.4 click==6.7 dash==0.19.0 dash-core-components==0.14.0 dash-html-components==0.8.0 dash-renderer==0.11.1 dash-table-experiments==0.5.4 decorator==4.2.1 defusedxml==0.5.0 Django==2.0.2 django-admin==1.1.1 django-excel-response2==2.0.8 django-six==1.0.4 django-social-auth==0.7.28 Flask==0.12.2 Flask-Compress==1.4.0 httplib2==0.10.3 idna==2.6 ipython-genutils==0.2.0 itsdangerous==0.24 Jinja2==2.10 jsonschema==2.6.0 jupyter-core==4.4.0 MarkupSafe==1.0 nbformat==4.4.0 numpy==1.14.0 oauth2==1.9.0.post1 oauthlib==2.0.6 panda==0.3.1 pandas==0.22.0 plotly==2.3.0 PyJWT==1.5.3 python-dateutil==2.6.1 python-openid==2.2.5 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2017.3 requests==2.18.4 requests-oauthlib==0.8.0 screen==1.0.1 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.6.0 traitlets==4.3.2 urllib3==1.22 Werkzeug==0.14.1 xlwt==1.3.0 I don't have the social_django in the pip freeze result, however when I run pip3 install social_django I get Could not find a version … -
Publish Messages to Exchanges in RabbitMQ with Celery
I have written a Django-Project which cues different tasks async via my_task.delay(). The problem is as the project is getting bigger it is really difficult to route the tasks properly - I started to write tasks which only purpose is to combine different tasks, which makes the code messy after some time. As I was reading some RabbitMQ documentation I came around a solution which could structure my project a lot better which relies on Exchanges. Exchanges can publish messages to multiple queues on which a Cosumer can consume it, in short: The RabbitMQ-Documentation describes a solution with Pika, which is a more low-level Client for RabbitMQ than Celery. The Celery-Documentation describes this scenario in its Documentation but doesn't describe how to create a Producer which produces Messages which are sent to an Exchange which distributes it to various Queues as seen in the Picture above. It only describes how to message Queues and send tasks - but I want this handeled by the Exchange. I found that Kombu, on which celery relies under the hood, has a function to send messages to an Exchange via a Producer but I can't find any documentation how to use this in celery-django. … -
Python How to send an attachment with mailgun
Good day I need help please. I can't send a message with attachment. This is the relevant resource: def send_email_with_mailgun(sender, recipients, subject, body, mail_gun_url, mailgun_api_key): recipients = recipients if type(recipients) is list else [recipients] try: return requests.post( mail_gun_url, auth=("api", mailgun_api_key), data={"from": sender, "to": recipients, "subject": subject, "text": body}, files=[("attachment", (open("xxxxxxx.pdf", "rb")))],) except: pass If I remove the parameter it does send, otherwise it will not -
How to reference a ForeignKey using a population script with Django
I'm creating a job ticket system and it's all working how I want it to so far, but I can't get my population script to add in several jobs to test with. The first two models get populated as expected. It crashed on the third... I'm not sure how to add in Foreign Key references into this. populate_jobs.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'petiqjobrequest.settings') import django from django.core.files import File django.setup() from jobs.models import Brand, JobType, Job IMG_DIR = os.path.dirname(os.path.realpath(__file__)) IMG_DIR += '/jobs/static/images/' testIMG = IMG_DIR + "local_advecta.png" def populate(): brands = { "Advecta": {"shortname": "ADV", "logo": IMG_DIR + "logo_advecta.png"}, ... } jobtypes = [ { "name": "Assets", "description": "Logos, Product Photography, Stock Images" }, ... ] jobs = [ { "name": "A new job request", "brand": "Advecta", "job_type": "Assets", "due_date": "2018-03-01", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id dolor auctor, mollis nisi sed, vestibulum arcu. Proin sem neque, fermentum a metus et, bibendum varius ligula." }, ... ] for brand, brand_data in brands.items(): b = add_brand(brand, brand_data["shortname"], brand_data["logo"]) print('Brands made') for j in jobtypes: j = add_jobtype(j["name"], j["description"]) print('Jobs Types made') for job in jobs: job = add_job( job["name"], job["brand"], job["job_type"], job["due_date"], ) print("Jobs added") def add_brand(name, … -
Why can't Django 2.0.1 be found when running Circle CI?
I'm running Circle CI on a Django project. The build fails, and the results show that Django 2.0.1 couldn't be installed. Why is the build failing? I was previously using Gitlab CI without any problems. The installation runs from my requirements.txt which contains Django==2.0.1. config.yml # Python CircleCI 2.0 configuration file # # Check https://circleci.com/docs/2.0/language-python/ for more details # version: 2 jobs: build: docker: # specify the version you desire here # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` # - image: circleci/python:3.6.1 - image: python:latest # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images # documented at https://circleci.com/docs/2.0/circleci-images/ # - image: circleci/postgres:9.4 working_directory: ~/repo steps: - checkout # Download and cache dependencies - restore_cache: keys: - v1-dependencies-{{ checksum "requirements.txt" }} # fallback to using the latest cache if no exact match is found - v1-dependencies- - run: name: install dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: paths: - ./venv key: v1-dependencies-{{ checksum "requirements.txt" }} # run tests! # this example uses Django's built-in test-runner # other common Python testing frameworks include pytest and nose # https://pytest.org # https://nose.readthedocs.io - run: name: run tests command: … -
Django auto populate author field in admin panel
In my django project i have a model.py with a class like this: class temp_main(models.Model): descr = models.CharField(max_length=200, verbose_name="Description") notes = models.TextField(null=True, blank=True, verbose_name="Note") dt = models.DateTimeField(auto_now=True) #Fields for API permissions owner = models.ForeignKey('auth.User', related_name='tmain_owner', on_delete=models.CASCADE, verbose_name="API Owner") class Meta: verbose_name = '1-Main Template' verbose_name_plural = '1-Main Templates' def __str__(self): return self.descr i would that in my admin panel the owner field was auto-populated with the current login user. In my admin.py i write: admin.site.register(temp_main, ) How can i set my owner field with logged in user? Thanks in advance -
Why am I unable to serialize my query via DRF?
class execution_details(APIView): def get(self): this_job_execution = JExecutionSerializer(this_job_execution) payload = [{ 'binaries': binaries, 'stage_logs': stage_logs, 'job_logs': job_logs, 'external_link': ext_links,}] return Response(this_job_execution.data + payload) error unsupported operand type(s) for +: 'ReturnDict' and 'list' I'm wondering if there is an issue because this_job_execution is a single record rather than a queryset with multiple records. I know I have done this in the past with a queryset, so that's why I suspect this is an issue. -
Django CMS:: Deserialization Error :: page has no field named 'path'
I have a Django application which is using Django CMS. I had built custom plugins, pages, users etc. in the application using CMS. I want to export the CMS data from my application to another instance of the same application which doesn't have any cms related data. I am using the following command: python manage.py dumpdata cms djangocms_column djangocms_file djangocms_googlemap djangocms_link djangocms_picture djangocms_style djangocms_text_ckeditor djangocms_video > cms_export.json --indent=2 I copied that file to the other app instance and tried to load it using the following command: python manage.py loaddata cms_export.json I got the following error: django.core.serializers.base.DeserializationError: Problem installing fixture '/cms_export.json': Page has no field named 'path' cms_export.json snippet: [{ "model": "cms.usersettings", "pk": 1, "fields": { "user": 2, "language": "en", "clipboard": 1 } }, { "model": "cms.usersettings", "pk": 2, "fields": { "user": 1, "language": "en", "clipboard": 7 } }, { "model": "cms.page", "pk": 4, "fields": { "path": "0004", "depth": 1, "numchild": 0, "created_by": "script", "changed_by": "xxxx", "parent": null, "creation_date": "2018-01-27T18:51:08.122Z", "changed_date": "2018-02-04T19:48:21.804Z", "publication_date": "2018-01-27T18:52:43.340Z", "publication_end_date": null, "in_navigation": true, "soft_root": false, "reverse_id": null, "navigation_extenders": null, "template": "base.html", "site": 1, "login_required": false, "limit_visibility_in_menu": null, "is_home": true, "application_urls": "", "application_namespace": null, "publisher_is_draft": true, "publisher_public": 5, "languages": "en", "revision_id": 0, "xframe_options": 0, "placeholders": [ 3, … -
Making a Django form appear on click
I have a Django form that is inside a div that I'm trying to get to appear when the user clicks on that div, but to no avail. Funnily enough though if I force the state of the element in the browser console it will work. Here's my code: {% if user.is_authenticated %} <div style="text-align:left;" class="content-editor"> <p class='body-font'>{{ post_detail.text|linebreaksbr }}</p> <!-- the form should only appear on click for the authenticated user --> <form method="POST" class="edit-prompt">{% csrf_token %} {{ form.text }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% endif %} CSS: .edit-prompt { visibility:hidden; } .edit-prompt:active { visibility: visible; } .content-editor { background-color: transparent; opacity: 1; border: none; width:inherit; height:inherit; } .content-editor:hover { border: 1px solid #ccc; border-radius: 5%; width: inherit; height: inherit; cursor: pointer; } -
Init django server with start-stop-daemon like a service
I'm trying to init a virtualenv and runserver command of django project on Ubuntu 16 Linux I create a file on /etc/init.d/initfile with the commands to start and stop service: do_start() { echo -n "Starting " $NAME " ..." if [ -f $PIDFILE ] then echo "\n-> Service " $NAME " is running." else start-stop-daemon --start --background --quiet --name $NAME --pidfile $PIDFILE --make-pidfile --exec $DAEMON echo "\n-> Service " $NAME " started..." fi } and the $DAEMON is a file with: VIRTUALENV_DIR=/home/user/python/DjangoProjects/newEnv1 SITE_DIR=/home/user/python/DjangoProjects/newEnv1/sampleSite source $VIRTUALENV_DIR/bin/activate python $SITE_DIR/manage.py runserver 0:8080 but when I check the process with ps -fu root is generated 3 pid id: 22875, 22878 and 22880 Image with multiple pid ids the problem is, when I execute the stop command only stopped the pid id that include in $PIDFILE but the other is running yet so the server still running. Can you help me please ? thanks -
Retrieve a script variable in all apps - Django
I've been searching and trying several solutions for a what it seems a simple problem for data retrieval of an externally executed script in Django. Now, I've figured out how to execute a script once through the Django's "AppConfig" (Execute code when Django starts ONCE only?), but I also need to retrieve at least once the data this script gathers across all Django's applications. Since it is a "sensorial" data, It shouldn't be included in a database or stored in any other way. What is the best way to do this? What am I missing? Thanks in advance for any heads up.