Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are my ValidationErrors not rendering anymore?
I have a form that has to check a few things before submission to make sure the data is valid. Before I did a few changes (went from class based views to function based) everything worked fine, but when I went back to test everything I noticed that a very important part was not working properly, which is the number validation. What used to happen before was that, if a number that was not in the DB was entered, the user would be shown an error at the top. If they entered a number that was in the DB, but it was not the right "team" then it would show an error. I was handling this in forms.py, and completely forgot about this since it was working before, and all the things I started working with were in views.py. Now, while it will not actually submit the form (so it is still going through the logic) it will not display any errors. It will just re-render the page but empty, and not submit anything unless the data entered is right. The logic that would handle this was clean_employee_number. I'm not sure If I deleted something from my html without noticing, … -
Inline display many to many admin django
Simplified example of my code would be: in models.py: from django.db import models class A(models.Model): ... class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): a_fields = models.ManyToManyField(A) then in admin.py @admin.register(A) class AAdmin(admin.ModelAdmin): pass class CInline(admin.TabularInline): model = C extra = 0 @admin.register(B) class BAdmin(admin.ModelAdmin): inlines = (CInline,) It won't show fields of A inline when I open the add new form for B entity. It actually shows a drop box with pre-existing entries and allows me to click on '+' to add new A, which is not desired behavior plus the same happens without using inline in the first place. Thanks in advance! -
Added additional model to models.py, but I get `OperationalError: no such table`
My webapp webapp has two tables already registered in models.py. Let's call them Model1 and Model2. They're built, they work, they're both registered in my webapp's admin.py and the entire webapp is running. I can go to the admin console (/admin) and see that both the tables are there, and I can look through them. I wanted to add a third table, Model3. I wrote out the code in models.py - it looks very similar to the other two models, with slightly different fields. I modified admin.py to include it, like the other two. I then deleted the migrations folder and I did the following Django commands: $ python manage.py makemigrations webapp Migrations for 'webapp': webapp/migrations/0001_initial.py - Create model Model1 - Create model Model3 - Create model Model2 $ python manage.py migrate webapp Operations to perform: Apply all migrations: admin, webapp, auth, contenttypes, sessions Running migrations: Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK I'm not sure what those migrations are that are actually getting run (I haven't changed Model1 and Model2 recently). When I run the webapp and enter the admin console, Model3 appears along with Model1 and Model2, but clicking on it yields the following error: Internal Server Error: /admin/webapp/model3/ … -
It is safe to use Django urls to run code?
I'm worried about the security of my web app, I'm using Django and sometimes I use AJAX to call a Django url that will execute code and then return an HttpResponse with a message according the result, the user never notice this as it's happening in background. However, if the url I'm calling with AJAX is, for example, "runcode/", and the user somehow track this and try to send a request to my domain with that url (something like "www.example.com/runcode/"), it will actually run the code and I feel like it is a security hole. Should I use Django urls to run code with AJAX?, if this is ok how I can avoid the users to notice that the URL exists? -
Social-Auth-App-Django vs. Django-Allauth
I need to add (optional) social authentication to a Django project with multiple user types and groups. After searching, I came across the libraries Social-Auth-App-Django, and Django-Allauth for handling social login. Which of these libraries should we choose in 2019? Security is the top priority for me. Thanks in advance, -
Checking if input from a form is in table django
The goal is to take in input from a user and see if that input matches information in a table in a database. If there is a match, delete that information from the table. If there isn't a match, clear out the form and say that there isn't a match. Here is the views file. from django.shortcuts import render, redirect from django.contrib import messages from .forms import CheckoutForm, CheckoutRegForm from .models import Checkout from books.models import Addbook def checkout(request): if request.method == 'POST': form = CheckoutForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'The book has been checked out.') return redirect('front-page') else: form = CheckoutForm() return render(request, 'checkout/checkout.html', {'form': form}) def checkin(request): if request.method == 'POST': form = CheckoutRegForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] member_id = form.cleaned_data['member_id'] if title in Checkout.objects.all(): Checkout.objects.filter(title = title).delete() messages.success(request, f'The book has been checked in.') return redirect('front-page') else: messages.error(request, f'Error: This book is not in the Checkout table.') return redirect('checkin') else: form = CheckoutRegForm() return render(request, 'checkout/checkin.html', {'form': form}) From my understanding, forms in Django collect user information and store it in a dictionary 'form.cleaned_data'. I tired multiple ways to set up that if statement to see if there is a match with the input from the … -
How to install libpq-fe.h?
I cannot figure this out for the life of me. When I pip install django-tenant-schemas it tries to install the dependency psycopg2 which requires the Python headers and gcc. I have all this installed and still keep getting this error! ./psycopg/psycopg.h:35:10: fatal error: libpq-fe.h: No such file or directory So to install libpq-fe-h I need to sudo apt-get install libpq-dev.. ..which returns.. libpq-dev is already the newest version (10.10-0ubuntu0.18.04.1). Then when I sudo find / libpq-fe.h it doesn't seem to be in my OS. I am lost at this point. If anyone can help I would highly appreciate it. -
What seems to be the problem with template tags?
Why doesn't this template tag work when I run server and on the browser doesnt show me anything when I add in the url static/images/django.jpg ? Hello I am a newbie here, on the path to full-stack development. While learning about Django-Static Files through python and django fullstack web development and after creating templates and template tags, I was not able to inject an image to an html file because as indicated in VS Code in red color the text and quotaition marks. images/Django.jpg" %} " As I see it must be a problem with code formater/code runner or that settings in VS code about single/double quotation marks, but still this is the first problem I encountered and I think I would have encountered it before if it was extension problem ? Here are images: problem 1 -
How to create xml sitemap of all the Django project detail page urls
I'm trying to get all the urls for specific Django project detail pages for instance: path('/mysite/speical/<pk>',views.DetalView.as_view(),name='detail') /mysite/special/1390u20 /mysite/special/930nfdn /mysite/special/29093nn How do I print all these urls into an xml file in the shell? I'm not sure where to even start. -
AttributeError at /pre_pred/
I've installed all the requirements and successful in running the local server but when I tried to run the prediction part of this 4th_umpire(The cricket match predictor using Random Forest algo project I'm getting the following error:- Here I'm presenting the error part of the code as mentioned in the error image. def _transform(self, X, handle_unknown='error'): X_list, n_samples, n_features = self._check_X(X) X_int = np.zeros((n_samples, n_features), dtype=np.int) X_mask = np.ones((n_samples, n_features), dtype=np.bool) if n_features != len(self.categories_): raise ValueError( "The number of features in X is different to the number of " "features of the fitted data. The fitted data had {} features " "and the X has {} features." .format(len(self.categories_,), n_features) ) The exception line is if n_features != len(self.categories_): although I've checked that OneHotEncoder part and it seems ok to me. -
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 …