Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
I'm getting this error when trying to run a django aplication: django.db.utils.OperationalError: unsupported file format
The program was quite running well a few minutes ago, after adding SlugField to my post URLs which I feel like it has nothing to do with the error, this is what I get when I run Python3 manage.py runserver in my terminal. System check identified some issues: WARNINGS: base.Post.tags: (fields.W340) null has no effect on ManyToManyField. System check identified 1 issue (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: unsupported file format The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/peace/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/peace/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/peace/.local/lib/python3.6/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) … -
Django, total price of not iterable object
Hello I have a question I have no idea how can i get total price of not iterable object in Django, I get this error: TypeError at /cart 'OrderItem' object is not iterable Here is my code, I would be pleased by any advise. views.py order_items = OrderItem.objects.filter(cart=cart) order_items = OrderItem.objects.annotate( sum=Sum(F('item__price') * F('quantity')) ).get(cart=cart) order_items.total_price = order_items.sum order_items.save(force_update=True) models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) total_price = models.IntegerField(default=1) -
Is there a way to implement a decorator to choose database for queries inside a function?
I have two databases; "default" and "replica". I know we can choose database explicitly by using ".using()". But I want something like this: @my_decorator(db_name = "replica") def my_fun(): """All queries in this function should perform operation on replica db""" Is there any way to do this? -
TinyMCE emoticon plugin doesn't load in Django
I am trying to set up tinyMCE for my Django website and I'm struggling with including plug-ins, in this case the emoticon one. Settings TINYMCE_DEFAULT_CONFIG = { # Plugins "plugins": "emoticons" # Toolbar "toolbar": "emoticons " [..] Formfield poller_text = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) Now on client side it throws the following error: tinymce.min.js:9 Failed to load plugin: emoticonssearchreplace from url plugins/emoticonssearchreplace/plugin.min.js What do I miss? -
"message": "Enum 'AccountsCandidateGenderChoices' cannot represent value: <EnumMeta instance>",
I am tring to create a candidate using graphene django. But is giving me error that cannot represent value . The choice is not saving in the database Enum 'AccountsCandidateGenderChoices' cannot represent value: **Django models** class Candidate(Model): class Gender(models.TextChoices): MALE = "Male" FEMALE = "Female" name = models.CharField(max_length=100) gender = models.CharField(max_length=100,choices=Gender.choices) > **ENUMS** > > class CandidateGender(graphene.Enum): > MALE = "Male" > FEMALE = "Female" > > **Mutations** class CreateCandidate(graphene.Mutation): > _candidate = graphene.Field(CandidateType) > > class Arguments: > input = CandidateInput(required=True) > > @classmethod > @candidate_required > def mutate(cls, root, info, input=None): > candidate = Candidate.objects.create(**input) > return CreateCandidate(_candidate=candidate) > > **Browser** > > mutation{ createCandidate(input: {name: "abc", gender: FEMALE}){ > Candidate{ > id, > gender > } } } -
Django form errors not showing when use id_<field-name>
I'm a beginner in Django, I try to use id_<field-name> method to create a signup form interface, but the default validation like "This field is required." or "This username already exists" is not showing. I don't want to use {{ form.as_p }} because I want to separate the field. The registration still working if i input the true the valid things. HTML <form method="POST" class="register-form" id="register-form" enctype="multipart/form-data" > {% csrf_token %} <div class="form-group"> <label for="id_username"><i class="zmdi zmdi-account material-icons-name"></i></label> <input type="text" name="username" id="username" placeholder="Username"/> </div> <div class="form-group"> <label for="id_email"><i class="zmdi zmdi-email"></i></label> <input type="email" name="email" id="email" placeholder="Your Email" /> </div> <div class="form-group"> <label for="id_password"><i class="zmdi zmdi-lock"></i></label> <input type="password" name="password" id="password" placeholder="Password"/> </div> <div class="form-group"> <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" /> <label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in <a href="#" class="term-service">Terms of service</a></label> </div> <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> views.py def register(request): registered = False if request.method == 'POST': # Get info from "both" forms # It appears as one form to the user on the .html page user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash … -
Is there anyway to create logging files for each user and date wise (Python)
I have an application where I need to create a folder for each user in which they will have their day-wise logs. I have added created custom middleware which will call my custom_logger file for creating logs file for each user. Below is my middleware auth_middleware.py from .custom_logger import LogClass log_obj=LogClass() def simple_middleware(get_response): def middleware(request): user_token=request.headers['userid'] user_name=request.headers['username'] page_name=request.headers['pagename'] log_obj.log_setting(str(user_name),str(page_name)) return response return middleware I am calling my custom_logger.py from middleware. class LogClass: def log_setting(self,user_name,page_name): current_date = datetime.date.today() #set variable which store current date log_path = './logs/' + user_name #log path of user folder if os.path.exists(log_path): #check user folder is already exist or not pass else: os.mkdir(log_path) #use to create user folder with username filename=str(current_date) +'.log' #set file name with current date logging.basicConfig(level=logging.DEBUG,filename=log_path+'/'+ filename,force=True, format='%(asctime)s : %(levelname)s : '+page_name+' : %(pathname)s : %(lineno)s: %(funcName)s : %(message)s') And after this, I import logging in every file and it works fine if one user work at a time for more than one user concurrently it's not working. If two users parallelly calls one API the first user will have initial logs then all the logs of the first user and the second user will come under the second user. Is there any way … -
How to get the URL requested in Django
So my URL which I am requesting in Django is 127.0.0.1:8000/ I want to get the id no. and URL separately in my views. I tried using: current_url = request.build_absolute_uri print(current_url) But it's giving error as: module 'django.http.request' has no attribute 'build_absolute_uri' Same goes with: current_url = request.resolver_match.url_name Not sure what I am doing wrong. -
How to flash ValidationError in Django template
I have a validator for limiting the upload size of a field ('track' & 'artwork') inside a form, I've added my validator function to 'validators.py' and set the validators setting to my model field. This seems to work as the app automatically reloads the form if file is too large , but my ValidationError is not visible, how can I flash this error message on screen ? also just to note, I'm using 'crispy forms' to display the upload form. validators.py from django.core.exceptions import ValidationError def file_size(value): filesize = value.size if filesize > 5242880: raise ValidationError("The maximum file size that can be uploaded is 5MB") else: return value models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio', validators=[file_size]) title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', validators=[file_size]) artist_name = models.TextField(max_length=50) artist = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) forms.py class MusicForm(forms.ModelForm): class Meta: model = Music fields = ['title', 'artist_name', 'track', 'artwork'] help_texts = { 'track': ('Max mp3 size: 5 MB'), 'artwork': ('Max image size: 5 MB'), } widgets = { 'title': forms.Textarea(attrs={'rows':1, 'cols':1}), 'artist_name': forms.Textarea(attrs={'rows':1, 'cols':1}), }