Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Locally Working Django fails during App Deployment to GAE
I have a simple local Django setup running on my Windows 10 PC in a Python virtual environment. I have two apps, one is a simple blog called "learning_logs" and the other one is an app called "users" to manage blog users. I migrated the DB from local SQLite to MySQL on GCP successfully. As the last step I wanted to deploy the local setup to the App Engine but it failed. There are too many log lines but I selected the lines with "errors" below. Maybe somebody could give me a hint: --- omitted --- Step #1 - "builder": 15 May 2020 13:29:56 INFO Arguments: ['--parser_script=/usr/local/bin/ftl.par', '--src=', '--entrypoint=', '--name=eu.gcr.io/able-engine-277215/app-engine-tmp/app/ttl-2h:66fee1cf-3401-4484-9ac2-26ac2cf7df98', '--directory=/workspace', '--destination=/srv', '--cache-repository=eu.gcr.io/able-engine-277215/app-engine-tmp/build-cache/ttl-7d', '--cache', '--builder-output-path=""', '--additional-directory=/.googleconfig', '--python-cmd=/opt/python3.7/bin/python3.7', '--pip-cmd=/env/bin/python3.7 -m pip', '--venv-cmd=/opt/python3.7/bin/python3.7 -m venv /env', '-v=DEBUG', '--base=eu.gcr.io/gae-runtimes/python37:python37_20200405_3_7_7_RC00'] Step #1 - "builder": 15 May 2020 13:29:56 INFO Unparsed arguments: ['--name=eu.gcr.io/able-engine-277215/app-engine-tmp/app/ttl-2h:66fee1cf-3401-4484-9ac2-26ac2cf7df98', '--directory=/workspace', '--destination=/srv', '--cache-repository=eu.gcr.io/able-engine-277215/app-engine-tmp/build-cache/ttl-7d', '--cache', '--builder-output-path=""', '--additional-directory=/.googleconfig', '--python-cmd=/opt/python3.7/bin/python3.7', '--pip-cmd=/env/bin/python3.7 -m pip', '--venv-cmd=/opt/python3.7/bin/python3.7 -m venv /env', '-v=DEBUG', '--base=eu.gcr.io/gae-runtimes/python37:python37_20200405_3_7_7_RC00'] Step #1 - "builder": /parse_workspace/build.py:145: DeprecationWarning: The 'warn' function is deprecated, use 'warning' instead Step #1 - "builder": logging.warn('Failed to parse requirements.txt to check gunicorn version') Step #1 - "builder": 15 May 2020 13:29:56 WARNING Failed to parse requirements.txt to check gunicorn version Step #1 - … -
passing Objects to serializer for nested serializer
I am trying to create a Model object through serializing json data. I have created a ReportSerializer: class ReportSerializer(serializers.ModelSerializer): agent_player = AgentPlayerSerializer() account = AccountSerializer() club = ClubSerializer() class Meta: model = Report exclude = ['created'] My reports model: class Report(models.Model): gross_winloss = models.DecimalField(max_digits=7, decimal_places=2) total_rake = models.DecimalField(max_digits=7, decimal_places=2) insurance = models.DecimalField(max_digits=7, decimal_places=2, blank=True) jackpot = models.DecimalField(max_digits=7, decimal_places=2, blank=True) hands = models.IntegerField(blank=True) created = models.DateField(auto_now_add=True) agent_player = models.ForeignKey( AgentPlayer, on_delete=models.SET_NULL, null=True, related_name="reports", blank=True) account = models.ForeignKey( Account, on_delete=models.SET_NULL, null=True, related_name="reports", blank=True) club = models.ForeignKey( Club, on_delete=models.SET_NULL, null=True, related_name="reports", blank=True) def __str__(self): return f"W/L: {self.gross_winloss} | RAKE: {self.total_rake} | RB: {self.rakeback_earnings} | NET: {self.net_winloss}" I have been running into a lot of problems with Djangos serializers. Maybe I am not understanding it correctly. When there are nested serialization, how does Django process it? Do we pass in objects? or if I pass in a PK? -
Saving json in django from javascript
I have an problem where I would like to store returned json from javascript on my django database. Currently I have a model as follows. class Plan(models.Model): slug = models.SlugField() title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) and I was in the process of writing a function starting like this. The data variable holds the relevant json that I would like to save to the db. function savePlan() { var data = plan.model.exportSerialized(); } How should I go about this? -
django.db.utils.OperationalError: FATAL: database "my_db" does not exist
I'm trying to deploy a Django/Postgres app using Docker but I get this weird message saying that my database does not exist after running docker-compose up This is the content of the most relevant files to this issue: settings.py . . ALLOWED_HOSTS = ["*"] . . DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_db', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } . . Dockerfile FROM python:3.7 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /leyton_reporter_api WORKDIR /leyton_reporter_api COPY requirements.txt /leyton_reporter_api/ RUN pip install -r requirements.txt COPY . /leyton_reporter_api/ docker-compose.yml version: '3.7' services: db: image: "postgres:11" environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_DB=my_db - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /leyton_reporter_api/manage.py runserver 0.0.0.0:8000 volumes: - .:/leyton_reporter_api ports: - 8000:8000 depends_on: - db volumes: postgres_data: -
Django saving file field file_name.tar.gz to file_name.tar_adfuh.gz?
In django if there are duplicate files in the folder then it appends random strings before the extension. But in this case random string should be appended before tar.gz not before gz. For example: file_name.tar.gz is already there in the upload_to folder. So the next time when the same file is uploaded then it should be named as file_name_sdfjh.tar.gz instead of file_name.tar_sdfjh.gz. -
NameError at /the/Url Path 1/ name 'variable' is not defined
I am trying to get the urls for the post detail views to display but instead it has a error. I tried searching but the results involved reformatting switching the operator from = to == which wasn't correct. its throwing an exception I am using Django 3 the code had worked in Django 2 before. I have been able to get code to work with a few minor changes here and there up till this error. Note: the category and subcategory apps are not added yet so just a simple default value as a placeholder value is being used. I was able to this the 1st with no issues. exc NameError("name 'newsname' is not defined") get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x0446CFE8>> request <WSGIRequest: POST '/panel/news/add/'> Using django 3 In visual code on the views.py I see a pylint error Undefined variable 'newsname' which is catname=newsname, which is catid=newsid, In this part of the code b = News(name=newstitle, short_txt=newstxtshort, body_txt=newstxt, date=2019, pic="-", writer="-", catname=newsname, catid=newsid, show=0) From this def news_add(request): if request.method == 'POST': newstitle = request.POST.get('newstitle') newscat = request.POST.get('newscat') newstxtshort = request.POST.get('newstxtshort') newstxt = request.POST.get('newstxt') if newstitle == "" or newstxtshort == "" or newstxt == "" … -
Using extra() for full text search in PostgreSQL
I'm trying to make a search function for multiple fields in PostgreSQL 12. It has two modes. First is just a regular search using Django ORM. Second is a search on partial words using extra() so i could call to_tsquery instead of plainto_tsquery. But for some reason second method returns 0 results. Where am i wrong? def dbsearch(queryset, query, config, *args): vector = SearchVector(*args, config='english') to_tsvector = "to_tsvector('english', coalesce({0}, '') | | ' ' | | \ coalesce({1}, ''))".format(args[0], args[1]) if config == "A": qs = queryset.annotate( search=vector, rank=SearchRank(vector, SearchQuery(query))).filter( search=query).order_by('-rank') if config == "B": query_terms = query.split() query_terms = ['{0}:*'.format(query_term) for query_term in query_terms] tsquery = " & ".join(query_terms) qs = queryset.extra( where=["%s @@ (to_tsquery(%s)) = true"], params=[to_tsvector, tsquery]) return qs -
Using the URLconf defined,Django tried these URL patterns
I'm doing tutorial "Movie rental" and i got error. Using the URLconf defined in vidly.urls, Django tried these URL patterns, in this order: Using the URLconf defined , Django tried these URL patterns, in this order: 1.admin/ 2.movies/ [name='movie_index'] 3.movies/ <int:movie_id [name='movie_detail'] The current path, movies/1, didn't match any of these. my code is(from main urls.py): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('movies/', include('movies.urls')) ] from mysite i.e movies(urls.py) from . import views from django.urls import path urlpatterns = [ path('', views.index, name='movie_index'), path('<int:movie_id', views.detail, name='movie_detail') ] from views.py from django.shortcuts import render from django.http import HttpResponse from .models import Movie def index(request): movies = Movie.objects.all() return render(request, 'movies/index.html', {'movies': movies}) def detail(request, movie_id): return HttpResponse(movie_id) What i'm doing wrong? -
How to get the next object?
here's what I have now: im = get_object_or_404(Images, uid=uid) next = get_object_or_404(Images, pk=im.pk+1) but if I deleted one instance always the next will be 404 because of the pk, so how can I get directly the next? -
Django self-referential Foreign Key won't map to proper field
I have a Django Model that looks something like this: class CompanyUser(models.Model): name = models.CharField(max_length=50, primary_key=True) manager = models.ForeignKey("CompanyUser",to_field="name",on_delete=models.PROTECT) ... class Meta: managed = False db_table = 'company_user' Using my own SQL, I have inserted this data from a company database to my local SQLite database. I have come to learn that I could use a data migration to do this instead of running my own SQL, but I'm not sure that is exactly my problem. Whenever I try to run "python manage.py makemigrations" I run into this error: django.db.utils.OperationalError: no such column: company_user.manager_id I have tried solutions such as using "to_field", and changing "CompanyUser" to "self", but these all produce the same results. I have not found a SO question that runs into this same error, as it appears that Django is trying to automatically create a "manager_id" field, which is not what I want. I have tried to run these migrations as an initial migration and an empty database to reset the migrations, but I have the same error. I have set managed to False to try to prevent this, but no dice. Thank you for any help you can provide. -
Djnago find in database
holiday.objects.filter(id > 2) - error how to use < or > in database queries in django. The task is to find entries with id>2 -
Deploying Django project on Centos 8, using Gunicorn, Nginx (Gunicorn.service problem)
I followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 Tried to deploy Django project on centos 8 Everything went fine and worked, except gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=facealatoo Group=nginx WorkingDirectory=/home/facealatoo/nadyr/promed ExecStart=/home/facealatoo/nadyr/promed/venv/bin/gunicorn \ --workers 3 \ --bind unix:/home/facealatoo/nadyr/promed/promed.sock \ configs.wsgi:application [Install] WantedBy=multi-user.target Folders destinations my project folder destination '/home/facealatoo/nadyr/promed' settings.py file 'home/facealatoo/nadyr/promed/configs/settings.py' server user name 'facealatoo' after running sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo systemctl status gunicorn.service Error message ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2020-05-15 18:37:22 +06; 13s ago Main PID: 32293 (code=exited, status=203/EXEC) May 15 18:37:22 facealatoo.net.kg systemd[1]: Started gunicorn daemon. May 15 18:37:22 facealatoo.net.kg systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC May 15 18:37:22 facealatoo.net.kg systemd[1]: gunicorn.service: Failed with result 'exit-code'. Please help me! ;) Thanks in advance )))) -
How to only create relevant model fields during a django test?
I am testing a method that requires me to create a fake record in my model. The model has over 40 fields. Is it possible to create a record with only the relevant model fields for the test so I don't have to populate the other fields? If so how would I apply it to this test case example. models.py class Contract(): company = models.CharField(max_length=255), commission_rate = models.DecimalField(max_digits=100, decimal_places=2) type = models.CharField(max_length=255) offer = models.ForeignKey('Offer', on_delete=models.PROTECT) notary = models.ForeignKey('Notary', on_delete=models.PROTECT) jurisdiction = models.ForeignKey('Jurisdiction', on_delete=models.PROTECT) active = models.BooleanField() ... test.py import pytest from app.models import Contract def calculate_commission(company, value): contract = Contract.objects.get(company='Apple') return value * contract.commission_rate @pytest.mark.django_db def test_calculate_commission(): #The only two model fields I need for the test Contract.objects.create(company='Apple', commission_rate=0.2) assert calculate_commission('Apple', 100) = 30 -
Access Django DB objects without shell?
I have a request - can you help me access and manage django DB objects without using shell ? I have created my models, but now (for example) i want to make a login system. I store users and passes(again, only an example), and i want to get the info from the DB, but i dont want to use shell. What can i do in this case, im quite new to Django ?! Best Regards -
Django oracle database connection
Im facing issue while connecting to oracle db in django project, Oracle connection details: ''' XXXX= (DESCRIPTION = (LOAD_BALANCE = YES) (FAILOVER = YES) (ADDRESS_LIST = (ADDRESS = (COMMUNITY = XXX.xxxx) (PROTOCOL = TCP) (Host = xxx-xx.xxx.com)(Port = 1521))) (CONNECT_DATA = (service_name = xxxx.xxxxx))) ''' i want to fit oracle details in below django database connection code, ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'a_user', 'PASSWORD': 'a_password', 'HOST': 'dbprod01ned.mycompany.com', 'PORT': '1540', } } ''' -
Placing two canvas elements on top of each other
I know this has been asked a few times already on SO (e.g.here), but I don't seem to be able to get this to work. I'm trying to: display images place a canvas on top of each of them get a user to draw on the top canvas based on the image underneath get the data off all canvases to be stored locally. I haven't been able to get the CSS to work so that the canvases are on top of each other and I've tried several ways of doing it. HTML: <div class="row"> <div class="pb-2 justify-content-center"> <h2><strong>Drawing test</strong></h2> <div class="justify-content-center"> <form enctype="multipart/form-data" method="post" action="">{% csrf_token %} <div class="wrapper"> <canvas id="dorsal" height="512" width="512"></canvas> <canvas id="dorsal-duplicate" height="512" width="512"></canvas> </div> </form> </div> </div> CSS canvas { position: absolute; top: 0; left: 0; } .wrapper { position: relative; width: 512px; height: 512px; } .wrapper canvas { position: absolute; top: 0; left: 0; } JS var canvas1 = document.getElementById("dorsal"), ctx1 = canvas1.getContext("2d"); var canvas2 = document.getElementById("dorsal-duplicate"), ctx2 = canvas2.getContext("2d"); var background1 = new Image(); var to_draw_on = new Image(); background1.src = "{% static aspects.Dorsal.0 %}"; /* image from Django static folder */ background1.onload = function(){ctx1.drawImage(background1,0,0);} to_draw_on.onload = function(){ctx2.drawImage(to_draw_on,0,0);} /* code to draw on the … -
Loop for recent post on home page in django project
I want to show 6 recent blog posts on home page in django project Nd 2nd doubt is that i want that like after 8-9posts on blog page its will automatically create new page like in so many websites having option next page page 1 as in pictureenter image description here -
How to apply migrations in django, pytest, postgres
How to auto-apply migrations to test database? Error django.db.utils.ProgrammingError: relation "users" does not exist E LINE 1: ...ers"."phone_confirmed", "users"."last_login" FROM "users" WH... pytest.ini [pytest] DJANGO_SETTINGS_MODULE = ma_saas.settings addopts = --migrations database_fixture.py import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.yield_fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'test_db' run_sql('DROP DATABASE IF EXISTS test_db') run_sql('CREATE DATABASE test_db') yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE test_db') I think it is better to create a database and apply its migrations in the database_fixture better. -
Django Summernote in Admin Prints Out Code View in HTML Page
I have installed Django-summernote by following the guide from GitHub and have successfully added it to my admin page. However, when I try to edit the text using summernote and view it on the HTML page, it shows the code view instead of text only. I can't seem to find any solutions to this on the internet. I'm not sure what I'm missing here. Here is my admin page where summernote is applied Here is my html page where the above would be viewed Here is my admin.py from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import Post class postAdmin(SummernoteModelAdmin): summernote_fields = ('body',) admin.site.register(Post, postAdmin) Here is my models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) category = models.CharField(max_length=32, default='Random') image = models.ImageField(default='placeholder.jpg') author = models.ForeignKey(User, on_delete=models.CASCADE) # also deletes user post if user if deleted summary = models.TextField(max_length=255, default='') body = models.TextField() def __str__(self): return self.title -
Trying to restrict location and radius on an address field using Django
I am stumped... I'm trying to use location biasing on a simple address search in a charField Django form. I'm using this example from Google and have set the ID of the form so I can use it in my script for the address autocomplete. I can also restrict the results to a particular country (because it is an attr) autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete'), {types: ['geocode'], componentRestrictions: {country: "UK"}}); ...according to some docs: Location biasing You may bias results to a specified circle by passing a location and a radius parameter. This instructs the Place Autocomplete service to prefer showing results within that circle. Results outside of the defined area may still be displayed. You can use the components parameter to filter results to show only those places within a specified country. ^^ I've tried this to no avail.. however in Google's example they use this function: // Bias the autocomplete object to the user's geographical location, // as supplied by the browser's 'navigator.geolocation' object. function geolocate() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var geolocation = { lat: position.coords.latitude, lng: position.coords.longitude }; var circle = new google.maps.Circle( {center: geolocation, radius: position.coords.accuracy}); autocomplete.setBounds(circle.getBounds()); }); } } and the HTML <div … -
Getting 502 Bad gateway - Nginx & Gunicorn
I am trying to setup Nginx with Gunicorn and Django but getting 502 bad gateway error. Below are my files. gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/apio/apio/ ExecStart=/root/sweetapi_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ apio.wsgi:application [Install] WantedBy=multi-user.target My nginx.conf file server { listen 80; server_name MY_IP_ADDRESS; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } My Folder structure apio apio db.sqlite3 manage.py static apio settings.py wsgi.py urls.py __init__.py On hitting my IP Address I am getting below in /var/log/nginx/error.log 2020/05/15 12:08:15 [error] 31068#31068: *1 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 117.203.***.***, server: ***.**.**.**, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/" My gunicorn.socket test is also failing gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: failed (Result: service-start-limit-hit) since Fri 2020-05-15 11:58:41 UTC; 12min ago Listen: /run/gunicorn.sock (Stream) Please provide some pointers. How can I debug this? -
Store keywords in queryset that give search hits with Q objects in the resultant queryset along with the search results
record_list is a python list containing a list of keywords to be searched. Following is my django views where I am searching the mysql database using these keywords. The code searches in columns product_name and description and returns the entire record where keywords give search hits. q_object = Q(product_name__icontains=record_list[0]) | Q(description__icontains=record_list[0]) for item in record_list: q_object.add(Q(product_name__icontains=item) & (Q(description__icontains=item)), q_object.connector) queryset = Products.objects.filter(q_object).values().distinct() for query in queryset: Filtered.objects.create(**query) The search result is successfully saved in the 'queryset' and I am able to save the queryset in database table. But I also want to save the keywords that gave search hits in the 'queryset' along with the respective search results. Is there a way to do so using django Q objects? -
Type object 'Gallery' has no attribute '_default_manager'
Using Django I create a model for uploading images for the portfolio page. I am using generic views. The ListView is working and I see all the images like thumbnails. DetailView is giving me an error: type object 'Gallery' has no attribute '_default_manager'. models.py from django.db import models class Gallery(models.Model): name = models.CharField(max_length=250) new_image = models.ImageField(upload_to='gallery_folder') day_publish = models.DateField() def __str__(self): return self.name views.py from django.shortcuts import render from .models import Gallery from django.views.generic import ListView, DetailView class Gallery(ListView): model = Gallery order_by = ['-day_publish'] class Pic(DetailView): model = Gallery urls.py from django.urls import path from .views import Gallery, Pic from . import views urlpatterns = [ path('portfolio/', Gallery.as_view(), name="portfolio"), path('detail/<int:pk>/', Pic.as_view(), name="pic_info"), ] -
docker: command not found Django channels
I have just started with Django channels, and stuck at this error... MacBook :chat $ docker run -p 6379:6379 -d redis:5 -bash: docker: command not found -
Django two foreign keys based on each other
These are my models: class Place(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE) street = models.ForeignKey(Street, on_delete=models.CASCADEdefault) class District(models.Model): name = models.CharField(max_length=255) class Street(models.Model): name = models.CharField(max_length=255) district = models.ForeignKey(District, on_delete=models.CASCADE) Every District has some Streets. In the Admin Create Form (for Place), I need to filter Streets based on the selected District. Any solutions?