Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I connect my Django Admin panel to Angular
I want help in integrating my Django Admin Panel to my Custom Angular Admin panel, I want to migrate all the functionalities of Django admin in Angular (Front-End). Would appreciate if anyone will share the walkthrough to deal with this problem. If with REST API than how please guide. -
Django : display the content of a PDF or Image on a template
I want to display a pdf/image file on a template. I download the content of the file from a azure blob storage but I do not know how to display it in a template without using the HttpResponse method from Django. Here is my code : function def download_from_blob(file): blob_client = create_blob_client(file) if not blob_client.exists(): return blob_content = blob_client.download_blob() return blob_content views.py def displayFILE(request, file_id): file = UploadFilesAAD.objects.get(pk=file_id) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) if blob_content : response = HttpResponse(blob_content.readall(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response This code works but only for pdf and takes the whole page for it. I would like to take this content and insert it in a html tag without using a django method. Because after I want to custom the page to diplay the content in half a page. My idea was to encode the content in 64 bits and then display it in the html code but it does not work. Here is the code : def displayFILE(request, file_id): context = initialize_context(request) file = UploadFilesAAD.objects.get(pk=file_id) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) encoded_string = … -
i face Problem while installing swagger in Django
I try to install swager for my Django rest framework project. when I was put this below commend then facing then error. I try too many times. but not success. I follow this below documentation site is. https://drf-yasg.readthedocs.io/en/stable/index.html pip install drf-yasg Collecting drf-yasg Using cached drf_yasg-1.20.0-py2.py3-none-any.whl (1.6 MB) Collecting uritemplate>=3.0.0 Using cached uritemplate-4.1.1-py2.py3-none-any.whl (10 kB) Collecting coreapi>=2.3.3 Using cached coreapi-2.3.3-py2.py3-none-any.whl (25 kB) Collecting inflection>=0.3.1 Using cached inflection-0.5.1-py2.py3-none-any.whl (9.5 kB) Requirement already satisfied: djangorestframework>=3.10.3 in g:\partshouse\venv\lib\site-packages (from drf-yasg) (3.12.4) Collecting ruamel.yaml>=0.15.34 Using cached ruamel.yaml-0.17.21-py3-none-any.whl (109 kB) Requirement already satisfied: Django>=2.2.16 in g:\partshouse\venv\lib\site-packages (from drf-yasg) (3.0.8) Collecting coreschema>=0.0.4 Using cached coreschema-0.0.4.tar.gz (10 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "<string>", line 36, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\Sony\AppData\Local\Temp\pip-install-zogxxnl5\coreschema_14f317f16044494cb26e7e1e63f7852c\setup.py", line 75, in <module> 'Topic :: Internet :: WWW/HTTP', File "g:\partshouse\venv\lib\site-packages\setuptools\__init__.py", line 87, in setup return distutils.core.setup(**attrs) File "g:\partshouse\venv\lib\site-packages\setuptools\_distutils\core.py", line 109, in setup _setup_distribution = dist = klass(attrs) File "g:\partshouse\venv\lib\site-packages\setuptools\dist.py", line 466, in __init__ for k, v in attrs.items() File "g:\partshouse\venv\lib\site-packages\setuptools\_distutils\dist.py", line 293, in __init__ self.finalize_options() File "g:\partshouse\venv\lib\site-packages\setuptools\dist.py", line 885, in finalize_options for ep in sorted(loaded, … -
Updating field in admin change list
I have a model of products, and want to display the list on the admin site with the possibility of changing the order. class Product(models.Model): name = models.CharField(max_length=500) is_active = models.BooleanField(default=True) category = models.ForeignKey( "categories.Category", on_delete=models.CASCADE, related_name="products" ) description = models.TextField(null=True, blank=True) ingredient = models.TextField(null=True, blank=True) order = models.PositiveIntegerField(default=0) rank = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) objects = ProductManager() class Meta: verbose_name_plural = _("Products") verbose_name = _("Product") ordering = ["order"] def __str__(self) -> typing.Text: return self.name I decided to order the model by the field order which can't be editable in admin page, so I want to copy it's value to the field rank which I want to make editable in admin page, and when I will save the changes I made to rank I want to override the order values with the new value from rank. This is how I register the model: class ProductAdmin(SortableAdminMixin, TranslationAdmin): inlines = [ImagesInline, NutritionsInline] search_fields = ["name", "description"] autocomplete_fields = ["category", "brand", "manufacturer"] fieldsets = ( ( _("Details"), { "fields": ( "is_active", "name", "price", "category", "description", ), }, ), ( _("Product Info"), { "fields": ("ingredient",), }, ), ) list_display = ("order", "rank", "name", "category") list_editable = ["rank"] I tried to override the … -
Django: Dealing with Username Changes
This might be a silly question, but I thought I'd ask before I continue doing anything. Assume I have two models: the first, some User model, and the second an ImgUpload model which captures the username automatically as the form is submitted and stores it in the database. If I end up updating a username (let's say User1 -> User2) or any other field from the User model, will the ImgUpload model automatically capture this change or do I need some sort of way to handle this? -
Are the names of files uploaded to an HTML multi-file upload input guaranteed to be unique?
Let's say I have a form with a multi-file upload input like this: <form method="POST" enctype="multipart/form-data"> <label for="files">Select files:</label> <input type="file" id="docs" name="docs" multiple><br><br> <input type="submit"> </form> I have a Django backend that is parsing this upload: def view(request): files = request.FILES.getlist("docs") file_names = [f.name for f in files] if len(file_names) != len(set(file_names)): raise Exception("Duplicate file names") Assuming the files are actually uploaded in a mainstream browser (Chrome, Firefox, IE, Edge, Safari, Opera), are the names for the files uploaded in this input guaranteed to be unique? I.e. is there any way for the exception in the backend to get raised? -
CSS files not found when trying to import third party NPM CSS file in django
I am running a django app and I want to import a third-party stylesheet from my node_modules. But my django app is looking in the wrong directory and throws a 404 and I don't understand why. My structure of the static files: static ├── src │ | │ │ │ ├── outputs │ │ ├── example.css │ │ ├── .. │ │ ├── .. │ │ ├── .. │ │ └── .. In my example.css I do the following: @import "~leaflet/dist/leaflet.css"; This should import my leaflet CSS - the ~ represents the path to the node modules- which is in my node_modules directory in my root directory (I also tried the absolute path to node_modules and the same error occurs). I added the node_nodules to the STATIC_DIRS in the django config and my static file settings look like so: STATIC_URL = "/static" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "myproject/static"), os.path.join(BASE_DIR, "node_modules"), ] STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) With this setting django should look into node_modules for the static files too. Now, with the above settings, when I include my example.css into the head of my template I get the following error: GET http://localhost:8000/static/src/outputs/~leaflet/dist/leaflet.css net::ERR_ABORTED 404 (Not Found) So obviously my app … -
Delete user model
How can I delete the user model? what will be the views? urls.py: path('account_delete/<int:user_delete>', views.account_delete, name="account_delete") views.py: from django.contrib.auth.models import User def account_delete(request,user_delete): return redirect("/") Templates: <a href="{ url 'account_delete' user_delete=user_delete }" class="delete_btn btn"> <i class="far fa-trash-alt"></i> </a> -
can't align list correctly
as you can see my list aligns some kind randomly and i dnot know why. Any ideas? html: {% if shop_name %} <ol> {% for library in shop_name %} <li>Video Library Info</li> <ul> <li>Name : {{library.shop_name}}</li> <li>Adress : {{library.adress}}</li> {% comment %} <button id="btn_goto" onclick="">Select</button> {% endcomment %} </ul> {% endfor %} </ol> {% else %} <p>ERROR</p> {% endif %} css code: body { text-align: center; color: #FFA000; background-color: #911E42; } ol { display: table; text-align: left; margin: 0 auto; margin-bottom: 20px; } ul { display: table; margin: 0 auto; vertical-align: baseline; text-align: left; } so at css i typed that text in list should be aligned on left side but still it does'nt help and it aligns randomly as i think. The thing i need to perfom is to align every li from ul on left side -
In Django, how do I collect the users input from html, use the input with python, and display the console output back to HTML?
I am a student. I am trying to make a simple online ping tester website with Django where the user can type in the IP address on the website, and the backend gives the result of the ping command which can show on the HTML page. Right now I have a problem with correctly collecting the information and getting results back. Views.py from django.http import HttpResponse from django.shortcuts import render import os import cgi import cgitb # Create your views here. def home_view(request, *args, **kwargs): cgitb.enable() form = cgi.FieldStorage() ip_to_check = form.getvalue('ip') result = os.system('ping {}'.format((ip_to_check))) print(result) print(request.user) return render(request, "home.html", {}) def contact_view(request, *args, **kwargs): return render(request, "contact.html", {}) Home.html <html> <head> <title>Ping</title> <meta name="description" content="Ping"> <meta name="keywords" content="Ping"> </head> <body> <h1>ping</h1> <form method="post">{% csrf_token %} <label for="ip">Ip adress:</label><br> <input type="text" id="ip" name="ip" placeholder="8.8.8.8"><br> <input type="submit" name="submit_cmd" value="run"> </form> <h2>Result</h2> <body></body> </body> </html> -
Django retrieve data from multiple tables on 2 levels
enter image description here I have this condition where for each value of table A, I need to recover the values of all connected tables, first (blue tables) and second level (green tables). As far as possible, I would like to adopt a simple solution, which follows Django's directives and doing well, which I obviously have not found. As from suggestions found online, for each foreign key I also set a 'Related Name', even if I am not sure it is useful for the purpose. Python: 3.7 Django: 3.12 -
error while configuring whitenoise with django for eks migration
we are migrating existing django application to kubernetes to load staticfiles we are using whitenoise we have configured all in setting.py file according whitenoise documention but we get 500 error while hitting the /admin page and below are container logs File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/usr/local/lib/python3.8/site-packages/django/templatetags/static.py", line 106, in render url = self.url(context) File "/usr/local/lib/python3.8/site-packages/django/templatetags/static.py", line 103, in url return self.handle_simple(path) File "/usr/local/lib/python3.8/site-packages/django/templatetags/static.py", line 118, in handle_simple return staticfiles_storage.url(path) File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 147, in url return self._url(self.stored_name, name, force) File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 126, in _url hashed_name = hashed_name_func(*args) File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 417, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'admin/css/base.css' Running python manage.py collectstatic inside the container we get below error File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File … -
How do you set the disabled value for a particular select option in a django form without a model?
I have a Django form that I am using without any model backing. Part of the form is a dropdown select list, which has various options. I want to set a particular choice as default, but also have it disabled so that it can't be submitted as an option. I know how to do this by setting the 'disabled' option to the particular option that I want to disable. I attempted setting disabled after setting the initial value for the select field: subject_choices = (('One', 'One'),('Two', 'Two'),('Three', 'Three'),('Four', 'Four'),('Five', 'Five'),) subject = forms.ChoiceField(widget = forms.Select(), choices=subject_choices, initial='One', disabled="true") I know this is incorrect because I am setting disabled for the entire select field and not the individual option, but I am unsure how to do that. How would I pass 'disabled' to one of the values I define in 'subject_choices'? -
Django Views.py: kwargs and serializer w/o explicit reference in class definition
I'm following along with a Django Rest Framework tutorial (source code here) and I have a few questions about the below code snippet: class ReviewCreate(generics.CreateAPIView): serializer_class = ReviewSerializer permission_classes = [IsAuthenticated] throttle_classes = [ReviewCreateThrottle] def get_queryset(self): return Review.objects.all() def perform_create(self, serializer): pk = self.kwargs.get('pk') watchlist = WatchList.objects.get(pk=pk) review_user = self.request.user review_queryset = Review.objects.filter(watchlist=watchlist, review_user=review_user) if review_queryset.exists(): raise ValidationError("You have already reviewed this movie!") if watchlist.number_rating == 0: watchlist.avg_rating = serializer.validated_data['rating'] else: watchlist.avg_rating = (watchlist.avg_rating + serializer.validated_data['rating'])/2 watchlist.number_rating = watchlist.number_rating + 1 watchlist.save() serializer.save(watchlist=watchlist, review_user=review_user) In the class definition, the variable serializer_class is declared; however in the perform_create method, serializer is an argument. Given the differences in naming, how are these two related? In the method perform_create, self.kwargs is referenced. However, I don't see a kwargs argument passed to any __init__ method or else attached to the class object. How/where is kwargs passed to the class? In both cases, I can only assume that the inherited class (generics.CreateAPIView) has an __init__ method that assigns a serializer_class variable to serializer. How it "listens" for a child class definition of serializer_class, I have no idea. And as for kwargs, I'm at a loss for how this is passed to the child class w/o … -
How can I connect my Django Admin panel to Angular
I want help in integrating my Django Admin Panel to my Custom Angular Admin panel, I want to migrate all the functionalities of Django admin in Angular (Front-End). Would appreciate if anyone will share the walkthrough to deal with this problem. -
restricted url access Django
I built myself the auth system of the website, and I created later on a Django app 'homepage' that can only be accessed when the user is logged so I have to create a way to restrict users from typing the app name into the url I searched on google and found the login_required function but I think this applies only If I used django auth system, and if that's not the case, how django can know if a user is logged in based on my auth system that I created it -
Django: is it possible to set DateInput widget limits for maximum and minimum dates?
my Date widget in forms.py looks like this: class DateInput(DateInput): input_type = 'date' class TaskCreateForm(ModelForm): class Meta: model = TaskModel fields = '__all__' exclude = ('task_project',) widgets = { 'task_baseline_start': DateInput(), 'task_baseline_finish': DateInput(), 'task_scheduled_start': DateInput(), 'task_scheduled_finish': DateInput(), 'task_real_start': DateInput(), 'task_real_finish': DateInput(), } The problem is whenever someone introduces a date too far into the future/past, some other parts of the application get all messed up (like graphs and other stuff). I've tried the following: class DateInput(DateInput): input_type = 'date' attrs = {'min': '2020-01-01'} But the widget keeps accepting dates before 2020-01-01. Am I missing something here? Thanks a lot! -
How to install a golang package in a docker file?
I'm new in docker and I want to setting-up a docker-compose for my django app. in the backend of my app, I have golang packages too and run that in djang with subprocess library. But, when I want to install a package using go install github.com/x/y@latest and then copy its binary to the project directory, it gives me the error: package github.com/x/y@latest: cannot use path@version syntax in GOPATH mode I searched a lot in the internet but didn't find a solution to solve my problem. Could you please tell me where I'm wrong?\ here is my Dockerfile: FROM python:3.8.11-bullseye # set work directory WORKDIR /usr/src/toolkit/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install packages RUN apt-get update \ && apt-get -y install --no-install-recommends software-properties-common libpq5 python3-dev musl-dev git netcat-traditional golang openvpn freerdp2-x11 tigervnc-viewer apt-utils \ && rm -rf /var/lib/apt/lists/* RUN go install github.com/x/y@latest && cp pacakge /usr/src/toolkit/toolkit/scripts/webapp/ # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/toolkit/entrypoint.sh RUN chmod +x /usr/src/toolkit/entrypoint.sh # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/toolkit/entrypoint.sh"] -
Django Queryset filtering based on each entry
Given the Django model below of a car traveling along a certain road with the start and end times: class Travel(models.Model): car = models.CharField() road = models.CharField() start = models.DateTimeField() end = models.DateTimeField() I want to identify the set of cars X that had been in the same road as the target car x for at least m minutes. How should I obtain the required set of cars X? My attempt: So let's say I use filtering to obtain the set of travels T that x had been in. T <-- Travel.objects.filter(car=x) I then brute force with: for t in T: possible_travels <-- filter Travel.objects with car=/=x, road=r.road, start < r.end, end > r.start confirmed_travels <-- further filter possible_travels with the overlapping region being at least m minutes long confirmed_cars <-- confirmed_travels.values('cars').distinct() However, the problem is that it may involve many DB hits by querying in a loop. Also, confirmed_cars gives a QuerySet object. So it seems I need to somehow append these QuerySet objects together. I saw other posts doing things like converting to list then appending and finally converting back to QuerySet but some people say it is not a good way, should I be doing something like … -
Creating a Django Model for a recipe #2
This is a follow-up question to Creating a Django Model for a recipe. I am able to select multiple ingredients for a single recipe, but my code only allows for one general quantity selection that associates with all ingredients selected. For example: (BLT recipe) I can select Bacon, Lettuce, and Tomato, but I am not able to have different quantities for each (i.e. Bacon(1), Lettuce(1), Tomato(2). class Recipe(models.Model): '''A recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredient = models.ManyToManyField(Ingredient) quantity = models.CharField(max_length=1) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) def __str__(self): return self.recipe class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' ingredient = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient -
Data isn't displayed in my ag-grid (vuejs) for some reason
I've been tasked to do some modifications on an old django + vuejs & ag-grid project. It is quite hard to do it, because the docs are a bit scarcer for the frameworks versions used for this project. (for example, django is 1.9, python is 2.7. We will migrate those later) I need some help understanding why my ag-grid (on vuejs) doesnt display anything. I've just started working on this project so I'm not sure if every function in here is needed (I took the code from another file). Please start reading columnDefs, gridOptions and the document.addEventListener (in those I added code) My table is blank: Here's the JS code which does the requests: const DOUBLE_KEY_INTERVAL = 400; const columnDefs = [ { field: 'Book number', pinned: 'left', }, // { field: 'Dossier', pinned: 'left', }, // { field: 'Dossier type', pinned: 'left', }, // { field: 'Date', pinned: 'left', }, // { field: 'Present to client', pinned: 'left', }, // { field: 'Client list', pinned: 'left', }, ] const gridOptions = { onSortChanged: saveState, onFilterChanged: saveState, onColumnVisible: saveState, onColumnPinned: saveState, onColumnResized: saveState, onColumnMoved: saveState, onColumnRowGroupChanged: saveState, onColumnValueChanged: saveState, onColumnPivotChanged: saveState, onColumnGroupOpened: saveState, onNewColumnsLoaded: saveState, onGridColumnsChanged: saveState, onDisplayedColumnsChanged: saveState, onVirtualColumnsChanged: … -
How to change django model.py PhoneNumberField format?
I would like to change the django PhoneNumberField() to take the following format 0712345678 instead of +14151234567 models.py contact_number = PhoneNumberField() -
How to retrieve 1 table objects that is related to 2 ForeignKey?
I would like to show in my template in each cell the name ("nombre") of the client ("cliente") with his payment {{pago.cantidad_pagada}} , the problem is that as I am doing it {{presupuesto.cliente.nombre}}, I show all the names that I have in my table and they are repeated in each of the cells, I imagine that it is due to the use of "for", but I don't know of another way to display the data. presupuestos.html <tbody> {% for pago in pagos %} <tr> <td> {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} </td> <td> {{pago.cantidad_pagada}} </td> </tr> {% endfor%} </tbody> pagos/models.py class Pagos(models.Model): numero_transaccion=models.IntegerField() estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.numero_transaccion}' presupuestos/models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente}' clientes/models.py class Clientes(models.Model): nombre = models.CharField(max_length=200, blank=True) def __str__(self): return f'{self.nombre}' views.py def presupuestosIndex(request): presupuestos = Presupuestos.objects.all() pagos=Pagos.objects.all() return render(request, "Presupuestos/presupuestos.html", {'presupuestos':presupuestos,'pagos':pagos}) -
cursor "_django_curs_1696_sync_2" does not exist
I accidentally deleted my migrations. I later makemigrations and migrate but when I access certain parts of the app that have ForeignKey references, I get cursor "_django_curs_1696_sync_2" does not exist. How on earth would I go about getting this corrected. This is happening in development and so I fear pushing to production because the same error will arise.? I tried looking at similar questions but couldn't get one to help solve my problem. -
How to access the profiles of a custom type of users in Django?
I'm a newbie to Django. In my project I have created a custom user (ArtHubUser) model with proxy types of users. I am trying to create a ListView that displays all the profiles (UserProfile) of the one type of users (type Artist). So far, my view looks like that: class DashboardArtistsView(views.ListView): model = Artist template_name = 'art/dashboard_artists.html' context_object_name = 'artists_objects' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) artists = Artist.objects.all() context['artists'] = artists return context However, this only gives me access to the info stored in the custom user database, and not to the fields belonging to the user's profile. How do I define context so I can load info from the profiles of all the users belonging to the Artists user group in the template?