Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What options need to be specified in the CACHES variable of Django's settings.py file to connect with an azure vm
My goal is to use a Linux (ubuntu 20.04) azure vm to run a caching service for django. I am running memcached on a Linux (ubuntu 20.04) azure vm. I am using django-pymemcache which extends the pymemcache library and is a wrapper around memcached. settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '53.171.42.209', 'OPTIONS': {} } } I've tested it while running the memcached service locally and specifying a location of (127.0.0.1:11211) and it works as expected. I know that the memcached service is listening on port 11211 of the azure vm. I've opened up inbound rules on azure to allow connection. But it refuses my connection, I assume because I haven't specified any sort of credentials to connect to it. I can't figure out how to do that piece, and if it's the only thing that I'm missing. -
Django/Javascript - How to generate link for a protected resource?
I would like to know if it's possible to generate the content of .href=... after the user has clicked the button and not in advance. If I look at my page source code I can see the full link :( <a type="button" class="btn btn-outline-primary" target="_blank" onclick="location.href='{% url 'stream' pk=track.file.pk|safe|cypher_link_stream %}'"><i class="fad fa-play-circle"></i></a> Thanks. -
request.POST.getlist returns a list of strings - how to get integers instead
I have some form fields, say: <input name="item" value="2"> <input name="item" value="3"> <input name="item" value="4"> When I obtain these in my Django view by using getlist, I obtain the following: items = request.POST.getlist("item") # items = ['2', '3', '4'] Is there a way to get these as integers and not strings? Or should I convert these to integers manually (eg through list comprehension)? -
Django or Flask synchronous one-time run and return to subprocess or system call in python and or vim
That's a mouthful of a title and i had a really hard time searching for what I'm trying to do pulling up tons of false hits. Let me explain. Say I am in a python script that requires some input values in real-time. Normally you use input for simple cases. But in my case, I want to synchronously fire up a django (or flask) app view route in a real browser that allows me to create the values I need in real-time on a real live page. These values don't exist so this can NOT be implemented using an API otherwise it would be easy! I want the original python program to block / wait until i fire "submit" on the live django (or flask) page. Then somehow I need the values that were submitted to be routed back to the calling python program that is still blocking / waiting for the values. Obviously I'm trying to make http which is asynchronous somehow act as synchronous. I'm not sure this can even be done but my thought was that if I could: have subprocess block by starting the run of the django dev server itself + open the desired page … -
AttributeError: 'str' object has no attribute 'ValidationError' Django
I am trying to create Views.py method where I check if the email already exists in the database. It worked for username but it is not working for emails or tokens. What would be the way to make that possible? Thank you! @api_view(['POST']) def send_user_details(request): if request.method == "POST": serializer = SignUpDetailsForm(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] username = serializer.validated_data['username'] password = serializer.validated_data['password'] if User.objects.filter(email=email).exists(): raise email.ValidationError("Este Email ya está en uso") if User.objects.filter(username=username).exists(): raise username.ValidationError("Este Usuario ya está en uso") It generates AttributeError: 'str' object has no attribute 'ValidationError' -
Return keyword arguments with None values to the views in django 3.2
As per Django 3 change logs (https://docs.djangoproject.com/en/3.2/releases/3.0/#miscellaneous): RegexPattern, used by re_path(), no longer returns keyword arguments with None values to be passed to the view for the optional named groups that are missing. Recently upgraded from django 2.2 to 3.2 after which I'm facing an issue for which I suspect the above mentioned changelog. Issue is I get KeyError while accessing the URL parameters as keyword arguments in the view (using get_context_data(...)) when accessing URLpatterns that are defined using re_path(). FYI, just to verify I rolled back to django 2.2 and checked on the context data from the view and could see that the required Key in the self.kwargs dict was set to None Is there any way to return keyword arguments with None values to the views in django 3.2? -
summation of multiple rows to check if value is less than referenced model in django
I tried to implement this SQL query using Django, where multiple payments under the same fee in possible and I have to get the payments that are lower than the fee amount. I have managed to get total payments under same fee id using Fee.objects.get(pk=self.pk).payment_set.aggregate(Sum('amount')) but cant find a way to compare it with payment_fee.amount SQL I tried to implement: SELECT payment_fee.id, payment_fee.amount , SUM(payment_payment.amount) as `su` FROM payment_payment inner join payment_fee on fee_id = payment_fee.id GROUP By fee_id HAVING (su)<payment_fee.amount django models: class Fee(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) class Payment(models.Model): fee = models.ForeignKey(Fee, on_delete=models.CASCADE, related_name='fee_payment') amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) -
Django process files uploaded by user
I am working on an app where the user uploads a text file which is further processed. All works well on my local environment but on Heroku, the app is unable to find the file in the specified location. User uploads file through form & I save it to a folder in the media root: # views.py myfile = request.FILES['myfile'] fs = FileSystemStorage(location=os.path.join(settings.BASE_DIR, 'media/raw')) filename = fs.save(myfile.name, myfile) I try to open the file and perform some operations on it # another file class Text: def __init__(self, filename): self.filename = filename self.raw_path = os.path.join(settings.MEDIA_ROOT, f'raw/{self.filename}') ... with open(self.raw_path) as file: ... On production, I get an error saying No such file or directory: '/app/media/raw/filename.txt' I know that Django is handling media files a bit differently in production but I haven't been figure out how to solve this issue. In my settings.py I have: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Thanks for any help! -
Using regular expression for a field name in a Django
I have a model in Django that has the fields photo_1, photo_2, photo_3 and many other fields that does not contains the "photo" string on their names. Also, the photo fields can be blank, so I can find some rows with empty photo fields. For the html template, is there a way to go through the fields named "^photo_[0-9]*$" and selecting only those that are not empty ? Here is what I mean: # views.py file def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request,"listings/listing.html", context) # listsing.html file <div class="col-md-2"> <a href="{{listing.photo_n.url}}" data-lightbox="home-images"> <img src="{{listing.photo_n.url}}" alt="" class="img-fluid"> </a> </div> I would like to go through the "listing" QuerySet, searching for the fields named "^photo_[0-9]*$" and, if the the value for that field is not empty, pass it to ref="{{}}" and src="{{}}" tks -
Django application not working because of packages in aws
I have tried to install packages into aws but when I connected it to apache. it was producing error then on further checking I discorvered that the packages I installed were not installed into proper directory where it was supposed to be located in so apache was producing error 500. How can I install packages into the directory where apache would be able to use it? -
How to move an django application from Heroku to aws Elastic Beanstalk
I am using Heroku for my django web app, but I don't want to use it anymore, but now I am afraid if I switch my service I will lose my db data and I can't afford data so if there is anyway to migrate the app from Heroku existing app with its data to AWS elastic bean I would love to hear that please explain. And please don't devote question if wrote anything in wrong way, suggest me I will do the changes. Thank You. For your precious time -
Django/Wagtail : django-debug-toolbar gives 404 error when cicking on panel
the toolbar shows nice and clean, but when i click on a panel to see if it really works, it gives me a 404: Not Found error. I have checked lots of answers and etc but they were from really old versions and i'm afraid i missed some important changelog. my urls.py import debug_toolbar from django.conf import settings from django.urls import include, path from django.contrib import admin from django.urls import path from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('search/', search_views.search, name='search'), ] urlpatterns = urlpatterns + [ path("", include(wagtail_urls)), path('__debug__/', include(debug_toolbar.urls)), ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my dev.py from .base import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'hidden' # SECURITY WARNING: define the correct hosts in production! ALLOWED_HOSTS = ['*'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = INSTALLED_APPS + [ 'debug_toolbar' ] MIDDLEWARE = MIDDLEWARE + [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INTERNAL_IPS … -
Fail to load API definition Swagger - Django rest Framework
I am completely new to DRF and Python need your help here getting "Fail to load API definition" Swagger ERROR, while loading the Swagger page using drf-yasg package below are my configurations note: app is the name of my Django Project and repertoire is the Django app app\urls.py schema_view = get_schema_view( openapi.Info( title="BMAT API", default_version="v1", description="BMAT API v1", terms_of_service="", contact=openapi.Contact(email="sivaperumal2000@gmail.com"), ), public=True, urlconf="app.urls", ) urlpatterns = [ path( "", schema_view.with_ui("swagger", cache_timeout=0), name="v1-schema-swagger-ui", ), path("repertoire/", include("repertoire.urls")) ] Error MSG Internal Server Error: / Traceback (most recent call last): File "D:\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Django\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Django\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\Django\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "D:\Django\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\Django\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\Django\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\Django\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\Django\venv\lib\site-packages\drf_yasg\views.py", line 94, in get schema = generator.get_schema(request, self.public) File "D:\Django\venv\lib\site-packages\drf_yasg\generators.py", line 242, in get_schema endpoints = self.get_endpoints(request) File "D:\Django\venv\lib\site-packages\drf_yasg\generators.py", line 311, in get_endpoints enumerator = self.endpoint_enumerator_class(self._gen.patterns, self._gen.urlconf, … -
Django: URL Reverse custom parameter to match?
I'm trying to figure out if I can build a url which would match objects in my model with other field instead of pk. I have a model which has many fields, and I was happy while using simple <int:id> while building url paths, so in this case: path("<int:pk>/", ProductDetailView.as_view(), name="product_detail") But things changed, and we decided to use our old url regex, so instead this we changed to: path("<slug:url>/", ProductDetailView.as_view(), name="product_detail"), Our model have this field: url = models.TextField(null=True) and I can easily filter out by url, like this: model.filter(url='/nesiojami-kompiuteriai/nesiojami-kompiuteriai.html') for example. I have a problem while trying to reverse and url for the model instance: prod = Product.objects.filter(is_deleted=False, category_id=64, url__isnull=False).first() return reverse("product:product_detail", kwargs={"url": prod.url}) NoReverseMatch at /nesiojami-kompiuteriai/nesiojami-kompiuteriai/ Reverse for 'product_detail' with keyword arguments '{'url': '/nesiojami-kompiuteriai/nesiojami-kompiuteriai/nesiojamas-kompiuteris-acer-sf314-14-i5-8265-8256gb--9618707.html'}' not found. 1 pattern(s) tried: ['product/(?P<url>[-a-zA-Z0-9_]+)/$'] -
Is there any altenative package in django testing framework in chrome getting refused connection
from django.test import TestCase from selenium import webdriver class FunctionlTestCase(TestCase): def setUp(self): self.browser = webdriver.Chrome("C:\Developement\chromedriver.exe") def test_there_home_page(self): self.browser.get('http://localhost:8000') self.assertIn('install', self.browser.page_source) def tearDown(self): self.browser.quit() OUTPUT ERROR: line 4, in <module> browser.get('http://localhost:8000') selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED (Session info: chrome=93.0.4577.82) NOTE: I am running very complex python-selenium tests on non-public webpages. In most cases these tests run fine, but sometimes one of these tests fail during the initialization of the Webdriver itself. Trying to do Django testing frame work. Install everything and set Django, selenium but getting error showing connection is refused. Is there any error in functions in code? All my network connection is good. I'm not able to find error and how to solve ? -
Does mysql database not support intersect operation in django project [duplicate]
Does mysql database not support intersect operation in django project -
pagination is not working in django restFarmwork
view.py 'class tutorials_list(generics.ListAPIView): queryset = Tutorial.objects.all() serializer_class = TutorialSerializer pagination_class = LargeResultsSetPagination' urls.py ' urlpatterns = [ url(r'^api/tutorials$', views.tutorials_list.as_view()), url(r'^api/tutorials/(?P<pk>[0-9]+)$', views.tutorial_detail), url(r'^api/tutorials/published$', views.tutorial_list_published) ' model.py: ' class Tutorial(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) ' i run this api than iget a error of this type: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'tutorials.models.Tutorial'> QuerySet. paginator = self.django_paginator_class(queryset, page_size) i try both class-based view and function-based view error screen -
Django authentication login page modification
I created a django project with many applications inside that projects, All of the applications make use of the same login page. How can I get the login page to read data from a particular application's view so that the database can provide data which would be viewed inside the login page. So I can do something like this. datadict = {'datafromdatabase': dataFromDatabase} response = render(request,'loginapplication/login_page.html', datadict) return response -
Cannot install module page_types using pip
I need to run django/mezzanine project with python 2.7. When I try to start my server using command python mange.py runserver I get the error: No module named page_types. When I try to install it I get: pip install page_types ERROR: Could not find a version that satisfies the requirement page_types (from versions: none) ERROR: No matching distribution found for page_types WARNING: You are using pip version 20.1.1; however, version 20.3.4 is available. You should consider upgrading. Can you help ? I get the same error with python 3.6. -
Django CSRF verification failed. Request aborted. error
i'm try to make image upload using dropzone.js that not using login or register and i got CSRF verification failed. Request aborted. error so pls help... javascript is: <script type="text/javascript"> Dropzone.options.fileDropzone = { url: '/media/', init: function () { this.on("error", function (file, message) { alert(message); this.removeFile(file); }); var submitBtn = document.querySelector("#submitBtn"); var myDropzone = this; submitBtn.addEventListener("click", function () { console.log("upload"); myDropzone.processQueue(); }) }, autoprocessQueue: true, clickable: true, thumbnailHeight: 90, thumbnailWidth: 115, maxFiles: 1, maxFilesize: 10, parallelUploads: 1, addRemoveLinks: true, dictRemoveFile: 'delete', uploadMultiple: false, } </script> and html is: <form class="imageUploaderForm" method="post" id="upload" enctype="multipart/form-data"> {% csrf_token %} <div class="form-title">Upload your Image</div> <div class="upload-type">File should be Jpeg, Png, Gif</div> <div class="dropzone" tabindex="0" class="drop-zone" style="border-style: dotted;" id="fileDropzone"> <input accept="image/jpeg, image/png, image/gif" multiple="" type="file" autocomplete="off" tabindex="-1" name="myFile" class="drop-zone-input" style="display: none;"> <div class="placeholder"> <img class="hide" width="115" height="90" src="#" id="preview"> </div> </div> <span style="color: rgb(169, 169, 169);">or</span> </form> and i used var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); and headers: { 'x-csrf-token': CSRF_TOKEN, }, this two codes but it's still have same error -
Redirect user to index after raising restriction
I have two groups of users Administrators and Clients and I'm trying to redirect user from Clients group to index page in case they try to access detail view of calculations that is not theirs. I still want to allow Administrators to view everyone's calculation details. I'm using Django's built in User model and Administrators group is characterized by is_staff flag. The mechanism itself works but I get 404 Page not found instead of Index page. Any idea on how to fix it? views.py class CalculationDetailView(LoginRequiredMixin, generic.DetailView): model = Calculation def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) try: if not self.request.user.is_staff: qs = qs.filter(pk=self.request.user.pk) return qs except: redirect('index') -
The value of 'list_filter[0]' refers to 'people__type', which does not refer to a Field
First time asking a question here so sorry if I'm not doing this perfectly. Context : Project in django, trying to have a filtering option in my admin panel. I have this Charfield in my model.py file that I am trying to use as a filter in admin.py, however python tells me that it doesn't refer to a field which is very confusing. Here are my codes : models.py class People(models.Model): OWNER = 'owner' TENANT = 'tenant' TYPES = ((OWNER, 'Owner'), (TENANT, 'Tenant')) type = models.CharField(max_length=20, choices=TYPES) people_name = models.CharField(max_length=200) people_surname = models.CharField(max_length=200) people_phone_number = models.CharField(max_length=200) people_email = models.EmailField(max_length=254) people_occupation = models.CharField(max_length=200) people_revenue = models.IntegerField() people_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.people_name admin.py from django.contrib import admin from django.db import models from .models import * from tinymce.widgets import TinyMCE #Register your models here. class PeopleAdmin(admin.ModelAdmin): fieldsets = [ ("Type", {"fields": ["type"]}), ("Information", {"fields": ["people_name", "people_surname", "people_phone_number", "people_email", "people_occupation", "people_revenue"]}), ("URL", {"fields": ["people_slug"]}), ] list_filter = ('people__type',) admin.site.register(People, PeopleAdmin) -
How to sink this error in Django? Invalid HTTP_HOST header
We keep getting this error with Django: Invalid HTTP_HOST header: u'/home/scheduler/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. I believe this happens because a "disallowed" host is establishing connection with our Django app. And we are aware we are letting this happen: ALLOWED_HOSTS = ['.mysite.org', '*'] Before you faint, we do this because we reject hosts using custom middleware DomainNameMiddleware. Our site supports clients pointing their own domains to ours and registering those domain names through a controlled process from our side. So yeah, those alien hosts will get rejected, just with extra steps. However it's really annoying to get this "Invalid HTTP_HOST header" error constantly. I'm not sure at what point in the stack this happens, but is there any way we could sink it and ignore it? -
Why is Python XLSWRITER Cell formula does not work programmatically?
I have these simple codes that get the SUM of A1, A2 and A3. workbook = xlsxwriter.Workbook(path) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 5, None) worksheet.write(1, 0, 3, None) worksheet.write(2, 0, 9, None) worksheet.write(3, 0, '=SUM(A1:A3)', None) workbook.close() Theoretically it should work. But it's not. (See image below) But if I manually change one of the 3 numbers then it will work. Manually changing its numbers are no good bc the excel is a generated file via python program, I cannot just say to the client to manually change a 1 number of their choice and change it back when the sum formula works. Send help senior Programmers. -
django-cities-light ValueError: invalid literal for int() with base 10: ''
I am getting error when I run python manage.py cities_light here is the complete error Assuming local download is up to date for http://download.geonames.org/export/dump/countryInfo.txt Traceback (most recent call last): File "manage.py", line 30, in execute_from_command_line(sys.argv) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 215, in handle self.country_import(items) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 308, in country_import country = Country.objects.get(geoname_id=items[ICountry.geonameid]) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 399, in get clone = self.filter(*args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1315, in _add_q child_clause, needed_inner = self.build_filter( File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 20, in init self.rhs = self.get_prep_lookup() File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/fields/init.py", line …