Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build c90ad64e-2c2f-4ad0-a250-160de6f315df status: FAILURE
I am trying to deploy my Django application to gcloud and I keep getting this error, any ideas what this means? File upload done. Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build c90ad64e-2c2f-4ad0-a250-160de6f315df status: FAILURE Error ID: c84b3231 Error type: UNKNOWN -
How to retrieve a json without the use of database?
I want to scrape a website using python and send as json the information that I got to my flutter application without saving it to the database. I don't want to use the Django Restframework database. I want to send a string to the backend and trigger a function that scrapes a certain website and sends back a json to the client. Without using the database. -
Django pagination - NoReverseMatch
I'm running in to an issue where I have some context in a template that I am attempting to send back to another view, but Django seems to think that it does not exist. NoReverseMatch at /results/wrench/2/ Reverse for 'recent_page' with keyword arguments '{'search': 'wrench', 'page': ''}' not found. 1 pattern(s) tried: ['results/(?P<search>[^/]+)/(?P<page>[^/]+)/$'] So it looks like 'page' is empty up there, but if I print it out on the page with {{ notes.next_page_number }} it seems to print out just fine, so I know it exists in the context of the page. Here is the template code: {% if notes.has_next %} <a href="{% url 'dashboard:recent_page' search=search_term page=notes.next_page_number %}">{{ notes.next_page_number }}</a> {% endif %} And my url is here: path("results/<search>/<page>/", views.recent_search, name="recent_page"), Which leads to my view.. @require_GET def recent_search(request, search=None, page=1): """ Display search results with Postgres FTS. """ if search is not None: search_term = search query = SearchQuery(search_term, config='english') else: # New search! search_term = request.GET.get('search') query = SearchQuery(request.GET.get('search'), config='english') relevant_notes = Note.objects.annotate(rank=SearchRank(F('vector_column'), query))\ .filter(vector_column=query).order_by('-rank') paginator = Paginator(relevant_notes, 20) selected_page = paginator.get_page(page) context = { 'notes': selected_page, 'tags': Tag.objects.all(), 'search_term': search_term, } return render(request, 'dashboard/recent.html', context) This one view handles new searches that are submitted with a … -
Django Rest Framework + React rest hooks CORS error
I am trying to integrate both React frontend and Django & DRF backend. I am using rest-hooks to fetch the data. I get CORS errors only when defining urlRoot = 'api/somemodel' in the resource. But I get the data from the API whenever I define urlRoot = 'api/somemodel.json' (adding .json to the resource urlRoot). CategoryResource.ts import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class CategoryResource extends Resource { readonly id: number | undefined = undefined; readonly name: string = ''; readonly description: string = ''; pk() { return this.id?.toString(); } static urlRoot = API_URL + 'categories.json'; } The above code works only for useResource(CategoryResource.list(), {}), but, whenever I fetch one category with useResource(CategoryResource.detail(), { id }) it returns some network error due to the URL format: http://localhost:8000/api/categories.json/1. But it should be categories/1.json. So, I thought, if I am able to use Postman to fetch all the categories in JSON format when sending request to http://localhost:8000/api/categories I should use that, but then I get CORS error. My Django configuration is allowing all origins from settings.py: CORS_ALLOW_ALL_ORIGINS = True. And again, it does work with the first approach. Any clues? -
Cyclic dependency in graph error during migration when using existing MSSQL Database
I have connected Django to MS SQL server 2017. But i am getting the following error during migration django.utils.topological_sort.CyclicDependencyError: Cyclic dependency in graph: I am seeing that this model which was generated after running python manage.py inspectdb is the one causing this. What could be wrong. Kindly assist class Djangomodel(models.Model): id = models.OneToOneField('self', on_delete=models.DO_NOTHING, db_column='Id', primary_key=True) # Field name made lowercase. -
How to add progress bar to file uploads in Django 3 served with NGINX reverse proxy?
There are similar questions, but they are years old and address Django 1 or 2. I found some information about it and setups like the progressbarupload or this post. But it all seems to be outdated. Is there an app that works with Django 3? -
Why it doen't set DEBUG = True?
I'm working in a Django project with a venv. My problem is the next one: I've configure DEBUG = TRUE in my code below, but it seems that setting is not loaded when django is starting and it launch this error: You must set settings.ALLOWED_HOSTS if DEBUG is False. I think DEBUG is changed in the virtual environment because I debug my code and I found that DEBUG is false before starting the server import django_heroku import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DEBUG = True ALLOWED_HOSTS = [] DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] PRIORITY_THIRD_PARTY_PASS = [ 'django_admin_env_notice', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'django_filters', 'django_otp', 'django_otp.plugins.otp_totp', 'drf_yasg', ] LOCAL_APPS = [ 'finalusers', 'reports', ] INSTALLED_APPS = PRIORITY_THIRD_PARTY_PASS + DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS AUTH_USER_MODEL = 'users.CustomUser' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } 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', 'django_otp.middleware.OTPMiddleware', ] ROOT_URLCONF = 'circulo.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', 'django_admin_env_notice.context_processors.from_settings', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'circulo.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
sync_cassandra command giving error in Django
I am a complete newbie in Django & Cassandra. I am trying to connect my Django app with the Cassandra database which is running as a Docker container on port 9042 using django_cassandra_engine. This is my database settings: DATABASES = { 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'test_ks', 'HOST': 'localhost:9042', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 3 } } } } But when I run sync_cassandra command it is giving me this error: PS C:\py\pytest> python manage.py sync_cassandra Traceback (most recent call last): File "C:\Users\patil\AppData\Local\Programs\Python\Python39\lib\site-packages\django_cassandra_engine\connection.py", line 78, in register connection.get_connection(name=self.alias) File "C:\Users\patil\AppData\Local\Programs\Python\Python39\lib\site-packages\cassandra\cqlengine\connection.py", line 247, in get_connection raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name)) cassandra.cqlengine.CQLEngineException: Connection name 'default' doesn't exist in the registry. As I am completely new to Django and Cassandra I am not able to get this error. Please help me to understand and resolve this error. Thanks in advance. -
How do I set up django alongside gitlab?
Gitlab is installed on the server, it hangs on the git.domain.com subdomain, I need the site to hang on domain.com, when I try to go to this domain, the browser swears at the lack of ssl, I tried googling, I got this config # the upstream component nginx needs to connect to upstream django { server unix:///home/web/project/uwsgi_nginx.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8001; listen 444 ssl http2 default_server; listen [::]:444 ssl http2 default_server; server_name domain.com; ssl_certificate /etc/gitlab/ssl/domain.com.crt; ssl_certificate_key /etc/gitlab/ssl/domain.com.key; # the domain name it will serve for server_name domain.com www.domain.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/web/project/media; # your Django project's media files - amend as required } location /static { alias /home/web/project/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/web/project/deployment/uwsgi_params; # the uwsgi_params file you installed } … -
Filter pk that before url_path in ListApiView. Django
I have urlpatterns += [path('collection/<int:pk>/video/', CollectionVideoViewSet.as_view(),name='collection-videos')]. And ListAPIView: class CollectionVideoViewSet(ListAPIView): """ViewSet for operation with videos in collection""" permission_classes = (IsAuthenticated,) queryset = Video.objects.all() serializer_class = CollectionVideoSerializer Can i filter queryset in this view by pk? -
Django and ajax problem cannot show results from query in template
I'm developing a website in django and at the moment i'm trying to implement search by using ajax. Currently i'm getting results in console but i cannot show results in the template. views.py def search_products(request): if request.method == 'POST': search_str = json.loads(request.body).get('searchText') products = Product.objects.filter(Q(price__istartswith=search_str) | Q(name__icontains=search_str) | Q(description__icontains=search_str)) data = products.values() return JsonResponse(list(data), safe=False) urls.py path('search-products/', csrf_exempt(views.search_products), name="search_products"), searchProducts.js const appTable = document.querySelector(".app-table"); tableOutput.style.display = "none"; searchField.addEventListener("keyup", (e) => { const searchValue = e.target.value; if (searchValue.trim().length > 0) { fetch("/search-products/", { body: JSON.stringify({ searchText: searchValue }), method: "POST", }) .then((res) => res.json()) .then((data) => { console.log("data", data); appTable.style.display = "none"; tableOutput.style.display = "block"; if (data.length === 0) { tableOutput.innerHTML = 'No Results Found'; } }); }else { tableOutput.style.display = "none"; appTable.style.display = "block"; } }); template <div class="container-3 w-container"> <div class="search-block w-form"> <form id="email-form-2" name="email-form-2" data-name="Email Form 2" class="search-field"> <label for="name-3" class="search-label-2">Search:</label> <input type="text" class="searchfield w-input" name="name-2" data-name="Name 2" placeholder="" id="searchField"> </form> </div> </div> <div class="w-layout-grid grid-8 table-output"> <div id="w-node-_16f775a1-c8df-749b-d74e-d96c0e9465bf-488447d3" class="search-product-result"> <a href="#" class="w-inline-block"><img src="images/search-results.jpeg" loading="lazy" height="" width="237" sizes="100vw" alt=""></a> <div class="div-block-33"> <a href="#" class="link-2-product-price search">Product Title</a> <a href="#" class="link-2-product-price search">€ 500</a> </div> </div> </div> How can i show results in template by using image, product title and price … -
Why django debug toolbar is hidden?
I install django debug toolbar and it did not appear in the browser, when I looked at the code, I saw that it was hidden. How can I fix this? -
How to solve django PostCreateView is missing a QuerySet in django
here we go screen shot of the above mentioned problem enter image description here -
Testing absolute url for models in django
in my model for userprofile. def get_absolute_url(self): return reverse('user_detail', kwargs={'pk': self.pk}) in my test.py def test_get_absolute_url(self): user = UserProfile.objects.get(id=1) self.assertEqual(user.get_absolute_url(), '/writecloud/user/1') well i wanna know if what i wrote in assertEqual() is correct to test this. im not sure how to use kwargs -
Use raspberry pi as server with custom domain for django project
I found a way to set up my raspberry pi for custom domain. Than he takes the /var/www/index.html as html file. But I want it to go to my django project. I set u an apache server, but i don't realy know how to link all those. It works separate, but not togheter. Any video or post how to set this up? -
How to Solve This Problem Which Picture is given below
This error found in django oscar. when i edit basket.html -
How to make a "create-only" non-editable field in django admin
im looking for some solution about make a "create-only" field on django admin using models. I saw some questions before, but no one can answer the core question: the field should appear when the user are creating on admin panel, but i dont want to be able to edit. models.py class Fonte(Always): source_slug = models.CharField(max_length=255) admin.py @admin.register(Fonte) class FonteAdmin(admin.ModelAdmin): readonly_fields = ['source_slug'] the "readonly_fields" solves the problem in the matter of editing in the future, but ends up forbidding when creating. Problem: Im using this field to make a hash and i dont wanna this change evermore.. I thought about using a second field that would generate a hash on top of the editable one field in the creation, after that the field would be "dead", but that seems to me to be contrary to the 2 way of normalization. Is there any more elegant way? -
NoReverseMatch at / 'customer' is not a registered namespace
This is a follow-on question from my answer to Django-oscar : how to change the URL from root APP?. Working through the Frobshop tutorial, I encountered an error when I attempted to subclass a template. The message was: NoReverseMatch at / 'customer' is not a registered namespace. The Problem Essentially, there is a problematic path() or repath() invocation, and to resolve the issue a namespace parameter needs to be provided to the invocation in urls.py: path(pattern, include([app_urls]), <i>... or ...</i> re_path(pattern, include([app_urls]), High-Level Solution I believe there is a conceptually simple solution, however the details are tricky. The solution has two key points: This part is easy. The offending path or re_path method require namespace and app_name parameters. To do this a 2-tuple need to be provided as the first argument for include(). Conceptually, the 2-tuple looks like ([app_urls], app_name), where the first item in the tuple is an app's array of URLs, and the second item in the tuple is the name of the app. Now for the tricky part. When one django-oscar path is redefined, some other app paths must also be redefined. You can see all of the registered apps by setting a breakpoint in get_app_config() in … -
How to add, retrieve and update fields which are not implemented in models using djongo?
I am using mongoDB as my primary database in a django project. I am using djongo engine for accessing and manipulating mongoDB. For testing I wrote a simple student model class StudentModel(models.Model): name = model.CharField(max_length=250) age = model.IntegerField() and insereted data to this model using from app.models import StudentModel StudentModel(name="John" age=10).save() Because mongoDB is schemaless database I want to try and add fields which are not implemented in StudentModel, I have tried to insert a new student with additional email address field. StudentModel(name="Steve" age=9, email="steve@email.com").save() But it gives this type error TypeError: StudentModel() got an unexpected keyword argument 'email' This is my database setup in settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'testdb', 'ENFORCE_SCHEMA': 'False', } } How do we add, retrieve and update fields which are not implemented in models using djongo? -
Invalid template library specified. No module named 'crispy_forms.compatibility'
Every time I try to run my django application locally on localhost using python3 manage.py runserver, ge thte following error and i dont understand why. I have the latest version of crispy forms installed (1.11.2) and i have it on my requirements.txt, and installed on my venv. Can someone help me? Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/Users/bermed28/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/bermed28/Desktop/semester-project-stack-overflowers/venv/lib/python3.7/site-packages/crispy_forms/templatetags/crispy_forms_filters 2.py", line 9, in <module> from crispy_forms.compatibility import lru_cache ModuleNotFoundError: No module named 'crispy_forms.compatibility' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/bermed28/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/bermed28/opt/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File … -
How do I copy existing formset data to prepopulate a CreateView in Django?
In one of my views, I use a class based CreateView to prepopulate my form with various fields from a different model. I do so like shown below: def get_initial(self): initial = super(Author, self).get_initial() book = Book.objects.get(pk=self.request.GET.get("dropdown")) initial = Book.__dict__.copy() initial.update({ "pages": book.pages, return initial Works brilliantly. Now I'm trying to grab data from some related formsets for this model as well, but because they are formsets, I'm a bit stumped on how to go about doing the prepopulation in as close to an identical fashion as possible. They are inline formsets. I've spent the last day looking and can't find anything that is helping me think this through. Thanks in advance for any thoughts on this. -
How to bypass WSGI error in django filter
from django.db import models from django.contrib.auth.models import User class Transfer(models.Model): id = models.AutoField(primary_key=True) amount = models.DecimalField(max_digits=10, decimal_places=2) name=models.CharField(max_length=55) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) Is it possible to make a request like this without WSGI error? result = Transfer.objects.filter(name=request.name) -
OperationalError at / no such table: blog_post
I'm making a Blog in Django. But when I run my program it gives me this error: OperationalError at / no such table: blog_post. I tried deleting migrations and db.sqlite3 table and ran the migrations command but it didn't work. Here is my code: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='Published') class Post(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) title = models.CharField(max_length=255) body = models.TextField(null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=255, unique_for_date='publish') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='Draft') tags = TaggableManager() objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) def __str__(self): return self.title class Meta: ordering = ('-publish',) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.CharField(max_length=255) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f"Comment by {self.name} on {self.post}" class Meta: ordering = ('-created',) views.py from django.shortcuts import redirect, render, get_object_or_404 from django.core.mail import send_mail from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from taggit.models import Tag from django.db.models import Count from django.contrib.auth.decorators … -
forms in django dose not retrive data and save it
i'm trying to create an appointment app with multiple condition in theory i find a way to make it happend but it dose not save the data an give me an error message the first part of the code work perfectly the 2nd part dose not save any data i try a lot of things but nothing work this is my code mybe some one see where the error is and give a hint to fix this this is my views.py @login_required def create_appointement(request): user = User() ######################################################"this part work perfectly if request.user.is_patient(): form_appointement = AppointmentForm(request.POST or None) if request.method=='POST': form_appointement = AppointmentForm(request.POST or None) if form_appointement.is_valid(): form_app = form_appointement.save(commit=False) form_app.user_ho_add = request.user form_app.patient = request.user # form_app.end_time = (form_app.start_time)+(timezone.timedelta(minutes=30)) # end_time_time = datetime.combine(form_app.start_time, time()) + timedelta(minutes=30) # form_app.end_time = end_time_time.time() start_time = form_app.start_time future_time = dt.datetime(1970, 1, 1, start_time.hour, start_time.minute, start_time.second, start_time.microsecond) + timedelta(minutes=30) form_app.end_time = dt.time(future_time.hour, future_time.minute, future_time.second, future_time.microsecond) form_app.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement1.html',{'form':form_appointement}) ###################################### this the part that give me always the error message and dont save any data else: if request.method=='POST' and request.POST.get("type") == "register patient": form_appointment_2 = AppointmentForm_2(request.POST or None) user = User() user2 = get_user_model() patients = user2.objects.filter(type_of_user=TypeOfUser.PATIENT) if form_appointment_2.is_valid(): … -
Django "Join" and "count" - Easy in psql, not so trivial in Django
user id 8a0615d2-b123-4714-b76e-a9607a518979 has many entries in mylog table. each with an ip_id field. I'd like to see a weighted list of these ip_id fields. in sql i use: select distinct(ip_id), count(ip_id) from mylog where user_id = '8a0615d2-b123-4714-b76e-a9607a518979' group by ip_id this gets me: ip_id count --------------------------------------+-------- 84285515-0855-41f4-91fb-bcae6bf840a2 | 187 fc212052-71e3-4489-86ff-eb71b73c54d9 | 102 687ab635-1ec9-4c0a-acf1-3a20d0550b7f | 84 26d76a90-df12-4fb7-8f9e-a5f9af933706 | 18 389a4ae4-1822-40d2-a4cb-ab4880df6444 | 10 b5438f47-0f3a-428b-acc4-1eb9eae13c9e | 3 Now I am trying to get to the same result in django. It's surprisingly elusive. Getting the user: u = User.objects.get(id='8a0615d2-b123-4714-b76e-a9607a518979') #this works fine. I tried: logs = MyLog.objects.filter(Q(user=u) & Q(ip__isnull=False)).value('ip').annotate(total=Count('ip', distinct=True)) I am getting 6 rows in logs which is fine, but the count is always 6, not the weight of the unique ip as it is in the SQL response above. What am I doing wrong?