Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Toast with Django CreateView message How to show
I'm new in Django and I'm creating a CRUD. However I want to show a Success message in a Toast for successfully submit, but I don't know how to do it exactly. The view class once is inserted, redirect correctly to List, but no messages showed. This is my view class class AlmacenesCreateView(SuccessMessageMixin, CreateView): model = Almacen form_class = AlmacenesForm template_name = 'pages/create.html' success_url = reverse_lazy('almacenes') success_message = "Bien!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "New Almacen" return context And this is the script for the toast $(function () { let mensaje ="{{ messages.0 }}"; const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 }); if (mensaje != "") { Toast.fire({ icon: 'success', title: mensaje, }) } }); My doubt is how I can show the success message -
Display images one by one when user clicks next in Django
I have created a django app where user uploads multiple pdf files and it converts to png and displays the images. I am using ModelForms for this purpose. The upload and the convert part is working fine but how do I display the Images sequentially? What I want is to display one image and when the user clicks next, the next image should be displayed. Below is my app code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserUploadModel(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) file = models.FileField(upload_to = 'file_uploads/%d%m%Y') views.py from django.shortcuts import render, redirect from app1.forms import UserUploadForm from app1.models import UserUploadModel from app1.convert import convert_file from app1.transfer import move_dir import os from project1 import settings # Create your views here. def home(request): if request.method == 'POST': form = UserUploadForm(request.POST, request.FILES) if form.is_valid(): f = form.save() f.user = request.user f.save() ff = request.FILES.getlist('file') f_list = [] for i in ff: file_instance = UserUploadModel(file = i) file_instance.save() f_list.append(file_instance.file.path) [convert_file(j) for j in f_list] src_dir = os.getcwd() dest_dir = os.path.join(src_dir, 'media/converted_files') move_dir(src_dir, dest_dir, '*.png') return redirect('app1-display') else: form = UserUploadForm() return render(request, 'app1/home.html', {'form' : form}) def display(request): return render(request, … -
Django 3.2 how to fix AttributeError: 'itertools.chain' object has no attribute 'filter' error?
I have 3 querysets that I need to merge and use filter method when the user selects a checkbox. Ajax works fine but I am struggling with displaying filtered data because I am getting this error: AttributeError: 'itertools.chain' object has no attribute 'filter' When I am trying to iterate over 1 model like this favourite_list=Product.objects.all() everything works fine but in my case, I need to filter data from 3 different models. I tried to use list(chain(fa, fv, fp)) but it gives me list object has no attribute filter error. def filter_favourites(request): favourite_articles = request.GET.getlist('favourite_articles[]') favourite_video = request.GET.getlist('favourite_video[]') favourite_product = request.GET.getlist('favourite_product[]') fa = request.user.favourite_article.all().distinct() #list of favourites items from Article model fv = request.user.favourite_video.all().distinct() #list of favourites items from Video model fp = request.user.favourite_product.all().distinct() #list of favourites items from Product model favourite_list = chain(fa, fv, fp) if len(favourite_articles) > 0: favourite_list = favourite_list.filter(title__in=favourite_articles).distinct() if len(favourite_video) > 0: favourite_list = favourite_list.filter(title__in=favourite_video).distinct() if len(favourite_product) > 0: favourite_list = favourite_list.filter(title__in=favourite_product).distinct() context = { 'combined_queryset': favourite_list, } ajax_template = render_to_string('user/user_favourites_ajax.html', context) return JsonResponse({'data': ajax_template}) My question is how can I fix this error? How should I merge fa, fv, pd so they behave like normal querysets and I can use filter method on them. -
Can i validate filter params using django-filters with some exeption if params or filter-params are wrong?
I incapsulate some logic for inheritance to for drf views. If i am using wrong field-param or wrong fild-filter (for example param with filter is: ?title__contains=title, and on frontend we made some mistake), i just get Model.objects.all() query from self.filter_queryset without any exception, but i gues that django-filter validate params inside filter_queryset method. I will be very grateful for the hints in which direction I need to look. Hear i'm using django-filters: class SomeView(GenericAPIView): filter_backends = [DjangoFilterBackend] some = SomeDTO() def some_get(self, request: Request, serializer: serializers): model = serializer.Meta.model params = request.query_params if params: query = self.filter_queryset(model.objects.all()) # problem is hear! else: query = model.objects.all() self.some.collect(serializer(query, many=True).data, status.HTTP_200_OK) return self.uni Drf-views looks like: class CurrentView(SomeView): filterset_class = CustomerFilter def get(self, request: Request): some: SomeDTO = self.some_get(request, CurrentSerializerDepth) return Response(some.data, some.status) def post(self, request: Request): some: SomeDTO = self.some_create_or_update(request, CurrentSerializerFlat) return Response(some.data, some.status) -
Django server link is not running
I am facing an issue to run the Django server. "python manage.py runserver" is working but when I try to run the local host link, the link is not working and the page shows "Can't reach the page". Please help enter image description here -
Django display a variable in another template
I have a django project, where I have two templates: notification.html and base.html. Using get_context_data() method I display the number of answers at the notification.html. I tried to use the same variable in base.html, but it didn't work. I also created CBV that and used get_context_data() to pass the same logic and display it at the base.html, but it doesn't work. How do I display the variable in another template? I don't how to pass 'answers.count' to the base.html, if base.html doesn't have a view (I created this only now trying to display this variable). forum.views class NotificationView(ListView): model = Answer template_name = 'forum/notification.html' # If user visited the notification page - mark all answers as read def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) question = Question.objects.filter(user=user) answer_read = self.model.objects.filter(question__in=question) answer_read.update(is_read=True) return answer_read def get_context_data(self, **kwargs): context = super().get_context_data() user = get_object_or_404(User, username=self.kwargs.get('username')) question = Question.objects.filter(user=user) context['answers_all'] = Answer.objects.filter(question__in=question).order_by('-date_posted') context['answers'] = Answer.objects.filter(question__in=question, is_read=False) return context forum/notification.html {% block content %} <div class="container"> <b>УNotofocations: {{ answers.count }}</b> {% for answer in answers_all %} <div class="card mb-3 mt-2"> <div class="card-body"> <a href="{% url 'detail' answer.question.id %}" class="mb-2">Ответ на вопрос: {{ answer.question }}</a> <p>{{ answer.detail }}</p> <a href="{% url 'users_questions' answer.user.username %}">{{ answer.user.username }}</a> … -
Link choicefield to another within the same form django admin
I have a problem about the django admin panel. I am making a form (model) and I want there to be a selection field, and when selecting it, it shows new fields. This form will be used in the django panel, not by a template. Please look at the example image. see example image -
ImportError: attempted relative import beyond top-level package django
I'm writing a site on Django and faced the problem that when relative importing from a directory located in the same directory as the directory in which the import is carried out, the following error appears: ImportError: attempted relative import beyond top-level package here is my import,which is in the file online_book/shop-cart/cart.py from ..books.models import Book the Book model is in the file online-book/books/models.py help me find solution to this problem please -
how can categories a django queryset in defferent range based on column data
i want to write a django query which can count student obtaning marks in range [1,30][30,60][60,90][90,100] based on subject in defferent course result sumthing like -
Checking input password for user
Its work well, but i have problem with checking password, how control validation of input password with default saving? class MyAuthenticationForm(AuthenticationForm): # checking for username in DB: def clean_username(self): username = self.cleaned_data['username'] try: User.objects.get(username=username) except User.DoesNotExist: raise forms.ValidationError(f"The {username} is incorrect username.") return username -
Django- ValueError: source code string cannot contain null bytes
In the django project, everything was working fine, but when I created .env file and imported variables from .env to settings.py, it started to show this error. Traceback (most recent call last): File "F:\django\udemyProject\siddthoughts\manage.py", line 22, in <module> main() File "F:\django\udemyProject\siddthoughts\manage.py", line 18, in main execute_from_command_line(sys.argv) File "F:\django\udemyProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "F:\django\udemyProject\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute settings.INSTALLED_APPS File "F:\django\udemyProject\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "F:\django\udemyProject\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "F:\django\udemyProject\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "F:\django\udemyProject\siddthoughts\siddthoughts\settings.py", line 15, in <module> import environ File "F:\django\udemyProject\venv\lib\site-packages\environ\__init__.py", line 18, in <module> from .environ import * File "F:\django\udemyProject\venv\lib\site-packages\environ\environ.py", line 38, in <module> from .fileaware_mapping import FileAwareMapping ValueError: source code string cannot contain null bytes All files are showing UTF8 in vs code and I am in my same project's virtual environment and using python interpreter from it only. can somebody tell … -
How can we host django docker container to Linode server?
I wonder if it is possible to create a docker container for my django project and when the project is ready, how can we host the container to linode ? Like is there any special configuration to -
mostrar sólo algunos registros con changelist
Soy bastante inexperto en esto. Necesito corregir esto: def verpz(request,pk): myapplabel = Pozos._meta.app_label mymodelname = Pozos._meta.model_name infodata = myapplabel+'_'+mymodelname return HttpResponseRedirect(reverse("admin:%s_changelist" % infodata,args=(pk,))) El objetivo es que en el administrador se muestre la lista de cambios filtrada, no todos los registros, si no solamente los que cumplan con alguna condición cómo por ejemplo que tengan una id específica. Gracias por su colaboración. Hello. I'm pretty inexperienced at this. I need to correct this: def verpz(request,pk): myapplabel = Wells._meta.app_label mymodelname = Wells._meta.model_name infodata = myapplabel+'_'+mymodelname return HttpResponseRedirect(reverse("admin:%s_changelist" % infodata,args=(pk,))) The objective is that the filtered list of changes is shown in the administrator, not all the records, but only those that meet some condition, such as having a specific id. Thank you for your cooperation. -
Django Command Error - Celery + Webscraper
I am using this in core/management/commands/crawl.py: from django.core.management.base import BaseCommand from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings __file__ = "root/core/management/commands/crawl.py" class Command(BaseCommand): help = "Run all spiders" def handle(self, *args, **options): process = CrawlerProcess(get_project_settings()) process.crawl(__file__.CnbcSpider) process.start() When I tried it in this way: from django.core.management.base import BaseCommand from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from scraping.palmy.spiders import cnbc_spider class Command(BaseCommand): help = "Run all spiders" def handle(self, *args, **options): process = CrawlerProcess(get_project_settings()) process.crawl(cnbc_spider.CnbcSpider) process.start() I've received: ModuleNotFoundError: No module named 'scraping' So I tried to import the file crawl.py within file. Probably a wrong appraoch? The django app and scraping scripts are in two different dicts and django app is the source root. Probably anybody has an idea here for better import handling (I currently have 0 clue), just want my easy file imports with from folder import file back. Anyways when I currently run celery I get: django.core.management.base.CommandError: Unknown command: 'crawl' Her is my tasks.py file which should just call the BaseCommand @shared_task(bind=True) def crawl_websites(self): logger.info('Spiders are crawling') call_command('crawl') logger.info('Spiders just finished crawling') I am currently using this celery worker "setup": celery -A app.tasks worker --pool=eventlet -l info Can sb help me to fix the Unknown command … -
What is the difference between rendering full.html and partial.html with django and htmx, especially context variable
#views.py def full(request): form = ... number = 1 context = {"form": form, 'number': number} return render(request, full.html, context) def partial(request): form = ... number = 2 context = {"form": form, 'number': number} return render(request, partial.html, context) In full.html {{ number }} is 1. It works as expected. In full.html extended with partial.html {{ number }} stay 1, not updated too 2. Where is context from partial rendering? -
how to filter fk related objects on django
I want to query the books that an specific person has lend currently. I use this query Book.objects.filter(lends__person__username__iexact="Antony") but it's not working properly. what i want to get is: the books with their latest person username who lend. (not the persons whom lend before the latest) here is my models class Person(models.Model): username = models.CharField(max_length=32, unique=True) class Book(models.Model): name = models.CharField(max_length=50) author = models.CharField(max_length=50) class Lends(models.Model): book = models.ForeignKey( "Book", on_delete=models.CASCADE, related_name="lends" ) person = models.ForeignKey( "Person", on_delete=models.CASCADE, related_name="lends" ) -
How to modify builtin djoser status code response for login url?
I have created an authentication module in djoser using DRF for the user where user can log in and log out. The Authentication module is working fine. If the user enters wrong credentials it pops a builtin djoser error code of 400 Bad Request. Is there any way to change this error code from 400 Bad Request to 401 Unauthorized urls.py from django.urls import path, include from .views import * app_name='users' urlpatterns = [ path('api/auth/', include('djoser.urls')), path('api/auth/', include('djoser.urls.authtoken')), ] I have not written any views for the djoser as it is giving me automatic url /api/auth/token/login for GET and POST requests. Kindly if someone can guide me how i can modify the builtin djoser status code -
Django annotation multiply fields
When I try to annotate my model I face an issue that two fields multiply each other def get_queryset(self): return self.queryset.annotate( my_votes=Count("votes", filter=Q(votes=self.request.user), distinct=False) vote_count=Count("votes", distinct=False) comments_count=Count("comments", distinct=True) ) I know that there is an issue with multiple aggregations Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries django docomentation For example, if there are 3 comments on the post and I voted on the post 4 times and there are 7 votes total the count will return: my_votes=12 (4 my_votes * 3 comments) vote_count=21 (7 votes * 3 comments) comments_count=3 if I remove the comments count everything works as it should. if there are 0 comments it also counts properly There are ManyToMany relations between Post and Vote The is ForignKey between Comment and Post Is there another way to accomplish this? Thank you for your help. -
Should return hashed file path in Rest api?
There is a company model, calling GET /api/comps/12/ would return below json "comp_detail": { "id": 12, "name": "razin company", "brand": "razin", "logo": "/media/12/comp_p/3.png" }, For security reasons, should we use hashed file path (logo here) when returning the file path for a client or it's not necessary(above json is good)? and if necessary how should we do this(in django and drf)? thank you in advance -
django 3.0.2 get_cache_key returns different cache keys
I'm trying to invalidate a view following this Expire a view-cache in Django?. Here's a view function where I have disabled per-site caching and enabled per-view caching. This is the view, say, that I need to invalidate. @api_view(["GET"]) @never_cache @cache_page(60*60) def get_segment_list(request, appid: str, page: str) -> JsonResponse: try: ... I have already called get_segment_list once and that has cached the response header and page. 127.0.0.1:6379> keys * 1) ":1:views.decorators.cache.cache_page..GET.39679326f007515994e08d99042c26f7.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC" 2) ":1:views.decorators.cache.cache_header..39679326f007515994e08d99042c26f7.en-us.UTC". <<-- NOTE THIS Here's a expire-view function. def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None): """ This function allows you to invalidate any view-level cache. view_name: view function you wish to invalidate or it's named url pattern args: any arguments passed to the view function namepace: optional, if an application namespace is needed key prefix: for the @cache_page decorator for the function (if any) """ from django.urls import reverse from django.http import HttpRequest from django.utils.cache import get_cache_key from django.core.cache import cache # create a fake request object request = HttpRequest() # lookup the request path: if namespace: view_name = namespace + ":" + view_name request.META = { 'SERVER_NAME': '1.0.0.127.in-addr.arpa', 'SERVER_PORT': 8000, } request.LANGUAGE_CODE = 'en-us' request.path = reverse(view_name, kwargs=args) # get cache key, expire if the cached item exists: key = … -
I'm trying to install django in virtual environment but getting some error and I don't understand what is it about
> pip install django Collecting django Downloading Django-4.1-py3-none-any.whl (8.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.1/8.1 MB 24.2 MB/s eta 0:00:00 Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting backports.zoneinfo Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-arm64-cpython-38 creating build/lib.macosx-10.14-arm64-cpython-38/backports copying src/backports/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports creating build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' /private/var/folders/z_/gh45f3y971vg11kt0m32cl440000gn/T/pip-build-env-tklngwk1/overlay/lib/python3.8/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license … -
Duplicate Django model instance without modifying python object
I am trying to create a method to duplicate a model instance new_object = old_object.duplicate_in_db() According to Django 3.2 documentation model instance can be duplicated in database by setting entity pk and/or id to None : # Model method def duplicate_in_db(self): self.pk = None self._state.adding = True # Some other duplication steps happens here e.g. duplicating OneToOneFields attributes # ... self.save() However a side effect is that original object has its id changed (along other attributes...) old_object_pk = old_object.pk new_object = old_object.duplicate_in_db() print(old_object_pk == old_object.pk) # False What would be an effective duplicate method/function without any side effect? -
Cannot find module '@vue/cli-plugin-babel'
enter image description here enter image description here yarn run watch yarn run v1.22.18 $ vue-cli-service serve node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module '@vue/cli-plugin-babel' Require stack: C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\bin\vue-cli-service.js at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at idToPlugin (C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js:172:14) at C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js:211:20 at Array.map () at Service.resolvePlugins (C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js:198:10) at new Service (C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\lib\Service.js:35:25) at Object. (C:\Users\dpu_i\AppData\Roaming\npm\node_modules@vue\cli-service\bin\vue-cli-service.js:15:17) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\Users\dpu_i\AppData\Roaming\npm\node_modules\@vue\cli-service\lib\Service.js', 'C:\Users\dpu_i\AppData\Roaming\npm\node_modules\@vue\cli-service\bin\vue-cli-service.js' ] } error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. -
how to pass a csrf token between django and javascript
I know very little about javascript. I have a GeoDjango project, and am adding a map view of some of the data using Leaflet. There is a lot of data so I am using a Leaflet uGeoJSON Layer to display the data (this allows leaflet to post a bounding box so Django can filter results and only pass visible data). I am adding leaflet to a django view. I have this working with a function based view in django which I decorate with @csrf_exempt, but would like to pass the proper csrf headers so I can use the generic class based django views. The documentation for [Leaflet uGeoJSON Layer][1] suggests: var headers = {}; // CSRF headers var token = jQuery("meta[name='_csrf']").attr("content"); var header = jQuery("meta[name='_csrf_header']").attr("content"); if (header) { headers[header]= token; } var customers = new L.uGeoJSONLayer({ endpoint : "/layers/customers", headers: headers }).addTo(map); I added this to my javascript but token and header are always null. Here is my javascript. map.js var headers = {}; // CSRF headers var token = jQuery("meta[name='_csrf']").attr("content"); var header = jQuery("meta[name='_csrf_header']").attr("content"); if (header) { headers[header]= token; } // Point Styles var DmseJobStyle = { fillColor: "#FFFFE0", color: "#FFFF00", opacity: 1, fillOpacity: 0.8 } var ... DmseJobData … -
Validation for current user
How to realize checking 'name' for current user in forms.py in ValidationError('Same name already added, change name'). views.py @login_required def main_page(request): form = URL_listForm(request.POST) if request.method == "POST": if form.is_valid(): name = form.cleaned_data['name'] if URL_list.objects.filter(user=request.user, name=name).exists(): return HttpResponse('Same name already added, change name') new_post = form.save(commit=False) new_post.user = request.user new_post.save() return HttpResponse("Data added") return render(request, 'link/main.html', {'form': form})