Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view not redirecting properly
I've been trying to get this working all day and finally now asking for help, sometimes this runs and sometimes is doesn't yet putting a stop in the debugger it never hits it. There is obviously something seriously wrong with this, but I can' see it for the life of me. class ProjectDelayedView(RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get("slug") print(slug) obj = get_object_or_404(Project, slug=slug) if obj.delayed is False: obj.delayed = True else: obj.delayed = False obj.save() return redirect('www.google.com') Ideally I want it to redirect back to the page I was at previously, but at this point just directing to anything at all would help, hence the return redirect to google on a RedirectView. All I know is that if I paste the url into the address bar, it goes to a blank page and looks to be in constant search, as the refresh icon in firefox stays as X. Stopping the page and then refreshing it again does the action in the database, but I can't get the redirect to work at all, it should go back to the same page I was on preferably. -
pipenv shell fails to create virtual environment
I am trying to run a Django project using pipenv shell. But when I enter the command pipenv shell, it fails. ❯ pipenv shell Creating a virtualenv for this project… Pipfile: /Users/juyeong/Desktop/django_workspace/Pipfile Using /usr/local/bin/python3 (3.7.3) to create virtualenv… ⠸ Creating virtual environment...Already using interpreter /usr/local/bin/python3 Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7' Running virtualenv with interpreter /usr/local/bin/python3 ✘ Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 390, in shell [pipenv.exceptions.VirtualenvCreationException]: pypi_mirror=state.pypi_mirror, [pipenv.exceptions.VirtualenvCreationException]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 2156, in do_shell [pipenv.exceptions.VirtualenvCreationException]: three=three, python=python, validate=False, pypi_mirror=pypi_mirror, [pipenv.exceptions.VirtualenvCreationException]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 574, in ensure_project [pipenv.exceptions.VirtualenvCreationException]: pypi_mirror=pypi_mirror, [pipenv.exceptions.VirtualenvCreationException]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 506, in ensure_virtualenv [pipenv.exceptions.VirtualenvCreationException]: python=python, site_packages=site_packages, pypi_mirror=pypi_mirror [pipenv.exceptions.VirtualenvCreationException]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 935, in do_create_virtualenv [pipenv.exceptions.VirtualenvCreationException]: extra=[crayons.blue("{0}".format(c.err)),] [pipenv.exceptions.VirtualenvCreationException]: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 417, in copyfile os.symlink(os.path.realpath(src), dest) FileExistsError: [Errno 17] File exists: '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/config-3.7m-darwin' -> '/Users/juyeong/.local/share/virtualenvs/django_workspace-CfQ2tbWB/lib/python3.7/config-3.7m-darwin' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 2611, in <module> main() File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 862, in main symlink=options.symlink, File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 1137, in create_environment install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear, symlink=symlink) File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 1421, in install_python copy_required_files(stdlib_dir, lib_dir, symlink) File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 1331, in copy_required_files copyfile(join(src_dir, fn), join(lib_dir, fn), symlink) File "/usr/local/lib/python3.7/site-packages/virtualenv.py", line 420, in copyfile copy_file_or_folder(src, dest, … -
Hide a specifc field in update but not in create
I want to show the password field only in create form, but not in the update form. If I remove the password from UserSerializer, it won't appear in both forms. class UserSerializer(serializers.ModelSerializer): subscriptions = SubscriptionSerializer(many=True, read_only=True) password = serializers.CharField( style={'input_type': 'password'}, write_only=True ) class Meta: model = User fields = '__all__' def create(self, validated_data): user = User.objects.create(**validated_data) user.set_password(validated_data["password"]) user.save() return user -
How to trigger infinite scroll from within a lightbox gallery - Django / FancyBox / Waypoints.js
The objective : I'm trying to build a photo gallery app using Django with justified layout, infinite scroll and a lightbox. I have followed the following tutorial for the infinite scroll using django pagination and waypoint.js, the justified layout is using Justified Gallery and I try to use Fancybox for the lightbox (any lightbox could do the trick, but I like the clean look of this one). At this point, each of these is working fine when taken individually. The issue(s): My photo gallery contains 100 images. When loading the page on desktop, 36 are loaded. If I scroll down, next pages/images are correctly loaded. But if I use the lightbox before scrolling, I'll be stuck with these 36 images. So at the moment, I am mostly looking for a way to trigger the lazyloading of the page from within the lightbox gallery, without having to exit the lightbox and scroll down. I found many stackoverflow posts about including the new images to the lightbox (which will probably be my next challenge, tbh), but not much information about how to call next pages/images from within a lightbox. Being some kind of js/jQuery noob, any help is welcome as i'm not … -
Remove special characters and replace spaces with "-"
I'm trying to make a directory that is okay to appear in a URL. I want to ensure that it doesn't contain any special characters and replace any spaces with hyphens. from os.path import join as osjoin def image_dir(self, filename): categorydir = ''.join(e for e in str(self.title.lower()) if e.isalnum()) return "category/" + osjoin(categorydir, filename) It's removing special characters however I'd like use .replace(" ", "-") to swap out spaces with hyphens -
Gunicorn reload not detecting changes in application code
I have seen that gunicorn reload uses inotify (when installed, which I have). I have verified that the reloader is working, and that some file changes are detected (mainly, changes to gunicorn itself) But my application code is not included in the list of files being supervised by inotify. What can I do for gunicorn to supervise my application code? My application is a django app, with the following wsgi.py: """ WSGI config for my project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys from django.core.wsgi import get_wsgi_application # This allows easy placement of apps within the interior # core directory. app_path = os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, 'core')) # We defer to a DJANGO_SETTINGS_MODULE … -
Kill side effects of aborted requests in django
Let's say I have a request that runs a lengthy SQL query server side. The client gives up waiting and closes the browser. Will that query continue to run? Can I somehow detect such situationa and handle it or does django handle it for me? -
Django.db.utils.ProgrammingError: relation does not exist in Postgresql
I did this code to import a shapefile in Django and my PostgreSQL database. import os from django.contrib.gis.utils import LayerMapping from .models import Adm3_names adm3_name_mapping = { 'gid': 'gid', 'adm1_code': 'adm1_code', 'adm1_name': 'adm1_name', 'adm2_code': 'adm2_code', 'adm2_name': 'adm2_name', 'adm3_code': 'adm3_code', 'adm3_name': 'adm3_name', 'adm3_statu': 'adm3_statu', 'pop': 'pop', 'pop_0to14': 'pop_0to14', 'pop_65plus': 'pop_65plus', 'hh': 'hh', 'shape_leng': 'shape_leng', 'shape_area': 'shape_area', 'geom': 'MULTIPOLYGON', } adm3_name_shp = os.path. abspath(os.path.join(os.path.dirname(__file__),'data/vnm_polbn_adm3_2014_pdc.shp')) def run(verbose=True): lm = LayerMapping(Adm3_names, adm3_name_shp, adm3_name_mapping, transform= False, encoding='iso-8859-1') lm.save(strict=True,verbose=verbose) When I run the first time it works and imports the data into my database. By mistake, I drop the data table in Postgresql... When I run the same code again, it nows telling me: django.db.utils.ProgrammingError: relation "testdjango_adm3_names" does not exist LINE 1: INSERT INTO "testdjango_adm3_names" ("gid", "adm1_code", "ad... How I can fix that? -
Django display a pdf in an iframe
Currently I am Working on a workflow where on the left side are input fields and on the right half is a scalable pdf. But actually I am not able to show a PDF in an iframe. I am using django 2.1.1(python 3.7.2) on windows. Is there any solution to display a pdf in an iframe? I hope you have some ideas..i looked up many sides an tried different solution but actually the pdf document is not shown.. Hope to hear from you soon! Kind regards -
how to exclude product of all the variables based on condition in python
import numpy as np x_1 = getval1 x_2 = getval2 x_3 = getval3 x_4 = getval4 y_1 = getx(x_1) y_2 = getx(x_2) y_3 = getx(x_3) y_4 = getx(x_4) z_1 = gety(x_1, y_1) z_2 = gety(x_2, y_2) z_3 = gety(x_3, y_3) z_4 = gety(x_4, y_4) val = np.prod( list({float(z_1), float(z_2), float(z_3), float(z_4)})) I have the code as above and im trying to find if y_1 value is 20 and i get z_1 value from it and assign it to 'val' variable and not to include other variables like z_2, z_3,z_4 in np.prod(). similarly if y_2 value is 20 i dont want other variables like z_1,z_3,z_4 to include in 'val' variable. it applies for y_3 and y_4 as well for eg: if y_1 == '20' then val = float(z_1) if then statement is not available in python.is there any other way to check this for y_1, y_2, y_3, y_4 variables? -
Iterating Through a Database Django
I have a model in my database called Item. This is the model class Item(models.Model): item_title = models.CharField("Item title: ", max_length=50) item_description = models.CharField("Item description: ", max_length=200) starting_price = models.FloatField( default = 0) picture = models.ImageField(upload_to = 'gallery') finishTime = models.DateTimeField("Finish time: ") ownerID = models.ForeignKey(User, on_delete = models.CASCADE) higestBid = models.FloatField() highestBidderID = models.IntegerField(blank=True, default=-1) active = models.BooleanField(default = True) I want to create a function in views.py , which will check the 'active' field of each item in the database. How can I do that? I have tried to do this: items = list(Item.object.values()) for i in range(items): print(item[i].active) However it does not work. Any help is appreciated -
CORS headers missing when addressing the backend by computer name, but not when using IP
The system architecture is roughly this (at least the components related to the issue at hand): A JavaScript GUI as a client (webapp) hosted using Nginx as a webserver, a Django-based backend proxied by said Nginx instance and both are hosted on the same machine. I'm accessing the network they're both in using a VPN.The issue is that it all works like a charm when addressing the host machine by its IP (https://10.11.12.113/#!/). When using the computer name (https://computer-name/#!/) instead of the IP, I cannot get past the login screen and the browser console lists CORS headers missing as the reason.When inspecting any response received from the backend when using IP, they have the required headers, most importantly Access-Control-Allow-Origin: '*' (asterisk for debugging purposes). These headers are theoretically added to the request twice: by django-cors-headers as middleware and by Nginx by a global directive found in the nginx.config file. The IP and the server name are correctly associated as can be verified by pinging the machine by its IP where computer name is mentioned in the ping command output. The host OS is Windows Server 2012 R2 by the way.So what could be the reason of this strange behavior?Note: I'm … -
itrerate over a python object in django html
I'm trying to generate the HTML code form my web app automatically despite the change the data in the backend {% for object in objects %} <tr> <td>{{ object.attr1 }}</td> <td>{{ object.attr2 }}</td> <td>{{ object.attr3 }}</td> </tr> {% endfor %} instead of hardcoding each attribute I want to iterate over the objects and generate the code inside automatically Thanks -
How I can escape from using sessions in Django?
What I'm trying to do? I want to display 2 registration forms separately of each other on the same page. The forms are: built-in User model and my self created UserProfile. To track, on what form user is now, I use sessions. It some sort of flags for me at the moment. Why I don't want to use sessions? I discovered a 'bug', at least for me, that I don't know how to fix. Bug appears if user passed first registration form, and close browser/tab. Next time user opens registration page, it will show second registration form, instead of first, as expected. Where bug happens, but now with code. When user opens register page first time, built-in UserCreationForm will be show, because there is no session called username yet. def get(self, request): if request.session.get("username", None): self.context["form"] = RegisterProfile() else: self.context["form"] = UserCreationForm() I'm using CBV, so it's OK that function called get and first argument is self. Also I created context dictionary as instance variable, so I can just add new field form to it. Next, if user fill in given form (note, that first form is built-in User's form) built-in User instance will be created and it's username will … -
Python module not found in docker container
I'm trying to run a django-cookiecutter project, but I'm getting a ModuleNotFoundError: No module named 'iprestrict' error in some of the containers. I checked out our repository that my colleagues can successfully build and run using both Docker for Windows and Docker for Linux. I've been debugging this for a while, but now I'm at a loss and asking for your help. This is my setup: $ uname -r 5.0.0-36-generic $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 19.04 Release: 19.04 Codename: disco $ docker -v Docker version 19.03.3, build a872fc2f86 $ docker-compose -v docker-compose version 1.25.0, build 0a186604 $ service docker status ● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2019-11-20 13:02:07 CET; 1h 59min ago Docs: https://docs.docker.com Main PID: 9382 (dockerd) Tasks: 41 Memory: 518.6M CGroup: /system.slice/docker.service ├─ 9382 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock ├─14817 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 5432 -container-ip 172.30.0.2 -container-port 5432 └─14829 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8025 -container-ip 172.30.0.3 -container-port 8025 To get a clean start I ran the following commands in my project directory: $ docker-compose down --volumes $ docker-compose build --no-cache The project is … -
django detail() got an unexpected keyword argument 'pk'
url.py path('detail/<int:pk>', movie.views.detail, name='detail') views.py def detail(request, primary_key): moviedetail = get_object_or_404(movieinfo, pk=primary_key) return render(request, 'movie/detail.html', { 'moviedetail':moviedetail }) moviehome.html <a href="{% url 'detail' movieinfos.movie_id%}"> detail() got an unexpected keyword argument 'pk' Could you please help me?? How do i have to fix it?? -
Django contains on a many to many field
I am trying to get a user that has the skills needed for a shift. This means the user needs to have the exact skills or more. I tried this. But this does not work for relation fields User.objects.filter(skills__contains=skills) The in operator also does not work because I need a user that has all the skills and not a user which has a subset of the skills required. Is there a way to retrieve the user where the asked about skills are a subset of the user skills? -
Setting up and serving static files for Django
I am on the verge of deploying my website but I have to firstly solve the issuer$ of serving static files via a web server for django. I have the following layout that is modifiable but is what I am working with so far website |-> PWEB | |-> exchange | | |-> migrations | | |-> static | | | |-> exchange | | |-> templates | |-> PWEB | |-> static-server | |-> static | | |-> exchange Both static folders right now contain exactly the same files but as I need to know exactly (I have tried various methods before) what to specify and where on how to access the static files. Here is the static definition in the settings.py file: STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) and here is an example of how the files are accessed within a html code: {% load static %} <!DOCTYPE HTML> <!-- Massively by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <style> {% block style %} {% endblock style %} </style> <head> {% block head%} {% endblock head %} <meta charset="utf-8" /> … -
'index_together' refers to field 'three' which is not local to model 'Entry'
Why am I getting this error? If remove index_together from the Post class, then everything works, but you can’t do this for certain reasons. class Post(models.Model): one = .. two = .. three = .. class Meta: abstract = True index_together = [ ['one'], ['one', 'two','three'] ] class Comment(Post): pass zinnia.Entry: (models.E016) 'index_together' refers to field 'three' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'two' which is not local to model 'Entry'. HINT: This issue may be caused by multi-table inheritance. zinnia.Entry: (models.E016) 'index_together' refers to field 'one' which is not local to model 'Entry'. I do not quite understand, where does Entry. but here is what is class Entry(load_model_class(ENTRY_BASE_MODEL)): """ The final Entry model based on inheritence. """ def load_model_class(model_path): """ Load by import a class by a string path like: 'module.models.MyModel'. This mechanism allows extension and customization of the Entry model class. """ dot = model_path.rindex('.') module_name = model_path[:dot] class_name = model_path[dot + 1:] try: _class = getattr(import_module(module_name), class_name) return _class except (ImportError, AttributeError): raise ImproperlyConfigured('%s cannot be imported' % model_path) ENTRY_BASE_MODEL = getattr(settings, 'ZINNIA_ENTRY_BASE_MODEL', 'zinnia.models_bases.entry.AbstractEntry') ZINNIA_ENTRY_BASE_MODEL = 'apps.blogextra.models.Post' -
Django-crispy-forms with bootstrap4 not showing selected result in browse file field
Attempting to use bootstrap4 with django for forms. Installed crispy forms and and everything seems to work as I expected except for the browse file button selection functionality. When a file selection window comes up and file is choose from expolorer it does not show as selected it the field. However when the form is submitted everything works as expected and the file is uploaded. Am I missing a helper class setting? I could not find one that looked like it addresses this. Any help is appreciated, details below. rendered html Environment: Windows 10 bootstrap4 Python 3.7.4 Django 2.2.5 Django crispy forms 1.8.0 Models.py from django.db import models # Create your models here. class Csvfile_model(models.Model): name = models.CharField(max_length=50) csv_file_name = models.FileField(upload_to='csv_file/') forms.py from django import forms from crispy_forms.helper import FormHelper from .models import * class CsvForm(forms.ModelForm): helper = FormHelper() class Meta: model = Csvfile_model fields = ['name', 'csv_file_name'] views.py def csv_upload(request): if request.method == "POST": form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sucess') else: form = CsvForm() return render(request, 'csv_upload.html', {'form' : form}) def sucess(request): return HttpResponse('sucessfully uploaded') csv_upload.html <!-- templates/home.html --> {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form form.helper %} {% block title %}Home{% … -
Trying to read a text file in django
Im unable to read the contents of a file from view.py Below is my code: def home_view (request, *args, **kwargs): ksh_test_result=AutomationTestResult.objects.values('tatr2tafmc__jobcommand', 'ksh_completion','ftp_log_abs_path','aftp_log_abs_path').distinct() ksh_drilldown_data=AutomationTestResult.objects.all() for ksh in ksh_test_result: ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() aftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.aftp_log_abs_path, 'r').read() print(ftp_log_file) print(aftp_log_file) context={ "ksh_list" : ksh_test_result, "ksh_drilldown" : ksh_drilldown_data, "ftp_log" : ftp_log_file, "aftp_log" : aftp_log_file } return render(request, "home.html", context) I'm reading the path of the file from a database. When I run this code i get the following error code Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/nmehta/Projects/GATI/src/KTA/dashboard/views.py", line 11, in home_view ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read() AttributeError: 'dict' object has no attribute 'ftp_log_abs_path' [20/Nov/2019 14:31:27] "GET / HTTP/1.1" 500 65923 -
How to go from one page to another in django
I'm new to Django and python (infact my first language which I've only been learning for 3 months) I'm creating this website using Django and I'm not able to go from one page to another using the href tag. it throws at me a 404 error saying "current path didn't match any of these" This is my code views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import off # Create your views here. def homepage(request): return render(request=request, template_name='main/home.html', context={'toll' : off.objects.all}) def secondpage(request): return render(request = request, template_name = 'main/next.html') main/urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('',views.homepage,name='homepage'), path('',views.secondpage,name='secondpage') ] templates/mains/home.html <div class="topnav"> <a href="{% url 'next' %}">Link </a> <a href="#">Link </a> <a href="#">Link </a> </div> I also request the helper to simply it for me as I wouldn't be able to handle complex and advanced python terminology Thanks In Advance From a Friend Arvind -
Why get error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet (Django 2.1.5)?
Tell me why I get this error and how to fix it? Tried to write django.setup() at the top of the file, but got a RuntimeError error: populate() isn't reentrant Code of mu model and traceback -
how make a filter or autocomplete in a field in django from html page
I newbie in django, I make a django form and show this in a html, in this form I have a field products, when a user going to select a product in this field shows all products, but to find a product not is easy because the products not can be filter when the user write, then the user have search from all the products in this field How I can make to filter when a user write for the product name -
Django management command with arg.parser and confirm
I' writing a small django management command where I parse user input: class Command(BaseCommand): help = 'Management command to transfer User Data from one user to the other' def add_arguments(self, parser): parser.add_argument( '-o', '--old', dest='old', default='', help="ID of Username from whom data is removed", required=True) parser.add_argument( '-n', '--new', dest='new', default=1086, help="ID of Username of receives data", required=False) ... Later I force a confirm to the user confirm = input('You are about to transfer data from {} to {}. Proceed? (Y/n)').format( old_user.username, new_user.username ) while True: if confirm not in ('Y', 'n', 'yes', 'no'): confirm = input('Please enter either "yes" or "no": ') continue if confirm in ('Y', 'yes'): break else: return Unfortunately this fails with NameError: name 'y' is not defined I think what is happening is that arg.parser tries to parse the value. How can I stop it in my confirm loop?