Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix in django "Page not found (404)" error ("Django tried these URL patterns... The empty path didn't match any of these.")
As a newbie to Django, I encountered the same problem as many before me. I would appreciate if you didn't mark my question as a double immediately because I checked the fixes those old posts suggested but to no avail, unfofrtunately. When I start server I get: Page not found (404). Using the URLconf defined in shops_online.urls, Django tried these URL patterns, in this order: admin/ api/organizations/ [name='organizations-list'] api/organizations/<int:id>/shops_file/ [name='get-shops-file'] api/shops/<int:id>/ [name='shop-view'] api/v1/token/ [name='token_obtain_pair'] api/v1/token/refresh/ [name='token_refresh'] api/v1/token/verify/ [name='token_verify'] docs/ [name='schema-swagger-ui'] The empty path didn’t match any of these. Here`s my views.py: from django.shortcuts import render from rest_framework.views import APIView from .models import Shop, Organization from shop.serializers import OrganizationSerializer, ShopSerializer from rest_framework.response import Response from rest_framework import status import pandas as pd import logging from django.http import HttpResponse from django.core.mail import send_mail from background_task import background from background_task.models import Task from background_task.models import Task from .tasks import send_email_task from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) class OrganizationListView(APIView): def get (self, request): try: organizations = Organization.objects.filter(is_deleted=False) serializer = OrganizationSerializer(organizations, many=True) # logging logging.info('GET request was successful') return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: logging.error(f'An error occurred while executing the request: {e}') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['PUT']) … -
Automatically refresh Django admin panel
I'm wanting to automatically refresh/update a model in the admin page to show updated data. How can I modify the admin panel to do that? -
CommandError: Unable to serialize database: 'utf-8' after command makemigrations
I use Windows 11 Pro and Visual Studio Code. I created a new almost empty database in pgadmin 4 (PostgreSQL 16). I set the default settings in the project settings in django (settings.py): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5433', }, } After the python manage.py makemigrations command I get the following error in the terminal: Traceback (most recent call last): File "C:\Users\twitchtest\Myproject\project\manage.py", line 22, in <module> main() File "C:\Users\twitchtest\Myproject\project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\commands\makemigrations.py", line 156, in handle loader.check_consistent_history(connection) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\loader.py", line 313, in check_consistent_history applied = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\backends\base\base.py", line 330, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\backends\base\base.py", line 306, in _cursor self.ensure_connection() File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
get_form_kwargs being omitted
I have a simple admin form: class SomeForm(forms.ModelForm): class Meta: model = Process fields = ["start", "end", "result", "description", "user"] def __init__(self, user=None, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) self.fields["user"].initial = user The form is being instanciated by a normal ModelAdmin: class SomeAdmin(admin.ModelAdmin): form = SomeForm def get_form_kwargs(self, request): return {"user": request.user} def get_form(self, request, obj=None, change=False, **kwargs): form = super().get_form(request, obj, change, **kwargs, **self.get_form_kwargs(request)) return form The output of the print statement is never visible in the terminal. Why? I want to be able to access the "user" as an initial value in the form: Edit: Code updated according to @Willem Van Onsem's input (still not working: Error: TypeError saying modelform_factory() got an unexpected keyword argument 'user'.) -
Add extra field to serializer
I need to add an extra field to serializer. I have below django serialzer { "count": 2, "next": null, "previous": null, "results": [ { "id": 8363, "name": "test10", "description": "" }, { "id": 8360, "name": "check", "description": "edew" } ] } I need to add a field, for example, let us call it as new_field. How can we make this possible? The structure I am expecting is below. { "count": 2, "next": null, "previous": null, "results": [ { "id": 8363, "name": "test10", "description": "" }, { "id": 8360, "name": "check", "description": "edew" } ], "new_field": "New Field Value" } -
GeoDjango: Building route of MultiLineStrings between 2 railway stations
I'm using GeoDjango (django.contrib.gis). I have 2 models: class RailwayStation(models.Model): point = models.PointField('Point') class RailwayLine(models.Model): mls = models.MultiLineStringField('MultiLineString') In my DB I have railway stations and a lot of railway lines (note: in most cases those lines do not directly connect stations between each other, they can be very short up to 50 meters). My goal is to be able to find the train's route between 2 RailwayStations (in other words the shortest route) that must consist of chained RailwayLines from my database, that would represent train's route, basically MultiLineString of concatenated MultiLineStrings from my database. ChatGPT suggested "networkx" package, not really sure if it is the suitable approach, as I have geo-data. Attaching 2 examples of RailwayLine's model MultiLineString - as I said they can be very short, as well as that long so one can be directly connecting 2 stations (very rarely). -
Syntax Django Website Error in URL name defining
I'm building a Django website and have a Syntax Error in a weird place. In urlpatterns, defining a name to my url. I've tried this from django.urls import path, include from . import views urlpatterns = [ ("", views.home, name="home") ] And get this return File "C:\VsCodeProjects\my_project\home\urls.py", line 5 ("", views.home, name='home') ^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? -
No Watchlist matches the given query
Trying to add an item to my watchlist returns an suddenly started returning an error. Here is what my code looks like. models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, default=False) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) items = models.ManyToManyField(Listing, null=True, related_name="watchlist_item") views.py def add_to_watchlist(request, item_id): item = get_object_or_404(Listing, pk=item_id) user_watchlist = get_object_or_404(Watchlist, user=request.user) user_watchlist.items.add(item) return redirect("watchlist") urls.py path("add_to_watchlist/<int:item_id>", views.add_to_watchlist, name="add_to_watchlist"), template <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">remove from watchlist</button></a> {% else %} <a href="{% url 'add_to_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">add to watchlist</button></a> {% endif %} </div> -
Python django error occurs when trying to use daphne for realtime channels server and corsheaders middleware together
Im am trying to make an application supporting both http and websockets i used djangorestframework for making http api and also i used channels to incorporate websockets and, with this setup when i try to serve the http server with the development server i dont get any error or application break but when I use daphne to try and serve both http and websockets server the application breaks with an error that await expression cannot be used in httpresponse,and note that after debugging I came to realise this only occurs because of the corsheaders middleware removing the middleware handles the error but i still need the corsheaders for my react frontend to work with django without any errors -
Using Django, updating a model using REGEXP_REPLACE with multiple patterns to match
I've searched and found similar posts but not this specific. I am currently trying to update a models JSON field using REGEXP_REPLACE. I want to do it in one query so I want to match multiple patterns and replace them in one call. With my current setup, if I have just one pattern I want to match the code works fine eg. name1, but as soon as I try to match multiple using (name1|name2) it doesn't work. A small example: We have a JSON field information on a model Person. The information field is populated with the following: {"name": "first_name last_name", "description": "Test description", "address": "123 example street"} The code I currently am using to do REGEXP_REPLACE is: find_pattern = r'(name|description)": "(.*?)",' repl_pattern = r'\1": "filler",' Cast( Case( When( **{f'information__isnull': False}, then=Func( Cast(information, output_field=CharField()), Value(find_pattern), Value(repl_pattern), Value('g'), function='REGEXP_REPLACE', output_field=CharField(), ), ), default=None, ), output_field=JSONField(), ) However this does not work and I can't figure out why. I get the following error: django.db.utils.DataError: invalid input syntax for type json DETAIL: The input string ended unexpectedly. Any help/ideas would be greatly appreciated, thanks. -
Image does not load on my webpage in django template
i want to put an image in my webpage but it is not loading the settings.py is STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] and homepage.py is <html> <head><title>project</title> </head> <body> <div class="top"> {% load static %} <img src="{% static 'project1.jpg' %}"> <h1> FLIGHT</h1> </div> </body> </html> the virtual env is sem1 final and app is project and folder named static is in project which contains project1.jpeg i tried the django documentations but it did not work. -
How can I serialize multiple unrelated tables to get combined JSON output via django rest framework?
I am working on an order management. Here's the scenario: User can create multiple types of orders and these order types are unrelated, but user can view all types of order. I have created an individual table for each of order type in models.py class OrderType1(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype1_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType1") class OrderType2(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype2_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType2") class OrderType3(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype3_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType3") In serializers.py, I have created serializers accordingly class OrderType1Serializer(serializers.ModelSerializer): class Meta: model = OrderType1 fields="__all__" class OrderType2Serializer(serializers.ModelSerializer): class Meta: model = OrderType2 fields="__all__" class OrderType3Serializer(serializers.ModelSerializer): class Meta: model = OrderType3 fields="__all__" Then here's the key problem: I want to create a serializer of order to return all orders of mutilple types like class OrderSerializer(serializers.ModelSerializer): class Meta: model = [OrderType1, OrderType2, OrderType3] fields = "common info of all types of order" If the serializer accepts GET request, I want to return JSON output like this: { "OrderType1":[ { "id": 1, "create_time": "2018-01-01 12:00:00", "ordertype1_info": "Exclusive info for OrderType1" }, { "id": 2, "create_time": "2019-12-01 12:00:00", "ordertype1_info": "Exclusive info for OrderType1" } ], "OrderType2":[ { "id": 1, "create_time": "2020-01-01 … -
The message tag is being sent to html document but it's not visible
index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="{% static "css/signup.css" %}" type="text/css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <div id="container" class="container"> <!-- FORM SECTION --> <div class="row"> <!-- SIGN UP --> <div class="col align-items-center flex-col sign-up"> <div class="form-wrapper align-items-center"> <form class="form sign-up" id="signup-form"> {% csrf_token %} <input type="hidden" name="form_type" value="signup"> <div class="input-group"> <i class="bx bx-user"></i> <select name="role" class="form-control" required> {% for value, label in form.role.field.choices %} <option value="{{ value }}" {% if value == '' %}disabled="disabled" selected="selected"{% endif %}>{{ label }}</option> {% endfor %} </select> </div> <div class="input-group"> <i class="bx bxs-user"></i> {{ form.username }} </div> <div class="input-group"> <i class="bx bx-mail-send"></i> {{ form.email }} </div> <div class="input-group"> <i class="bx bxs-lock-alt"></i> {{ form.password }} </div> <div class="input-group"> <i class="bx bxs-lock-alt"></i> {{ form.confirm_password }} </div> <button type="submit">Sign up</button> <p> <span> Already have an account? </span> <b onclick="toggle()" class="pointer"> Sign in here </b> </p> </form> </div> </div> <!-- END SIGN UP --> <!-- SIGN IN --> <div class="col … -
Problem loading JS files in django project
I am currently working on a project which uses templet inheritance. and from other tamplet when i am trying to load two different javascript files having 2 windows.onload function it load only one which is on the top. i am attaching a image which show both the directory structure and code image with code and dir structure I am expecting that my all windows.onload fun run from diff JS files at once when document is loaded. -
The post in a django app shows the whole content how can I change that?
I am working on a django website and the post I write is a story with 300 words for example and it shows all those 300 words on the home page Is there a way I can make it show for example the first two lines of the story and then when people click on the details they can read the whole story how can I achieve that? (plus if you need to take a look at a specific part of my code please let me know cause I don´t know which part of it should I put here) -
Attribute Error while trying to access a MYSQL table : SQLAlchemy Django
I am getting the below attribute error while trying to access data from MySQL database using SQL Alchemy. qry = sa.select(ref_table.c.Trade_Date, ref_table.c.Open, ref_table.c.High, ref_table.c.Low, ref_table.c.Close ^^^^^^^^^^^^^^^^^^^^^^ File "E:\theparams\theparamsenv\Lib\site-packages\sqlalchemy\sql\base.py", line 1634, in __getattr__ raise AttributeError(key) from err AttributeError: Trade_Date The table has data for trade_date column and you can find the table description below. table_name = "core_historicaldata" engine = sa.create_engine('mysql+mysqlconnector://' + str(str(data_base.user) + ':' + str(data_base._password)) + '@'+ str(data_base._host) + ':' + str(data_base._port) + '/' + str(data_base.database), echo=False) ref_table = sa.Table(table_name, sa.MetaData(), autoload_with=engine) qry = sa.select(ref_table.c.Trade_Date, ref_table.c.Open, ref_table.c.High, ref_table.c.Low, ref_table.c.Close).where(ref_table.c.Symbol == stock) data = pd.read_sql_query(qry, engine) engine.dispose() I think this is something to do with primary key or index. Please advise -
¿It is possible to create a dynamic field in django admin?
The thing is I am creating a project on Django where my apps will work just on Django Admin View (so I dont want to create views or html templates). I am going to create two App: App One consist on showing just several models for example a Model named Client with client_id, name, country, etc. I can add data to my models, edit, delete, well the typical things you can do on Django Admin. Then App Two will be a model call Issue. On this model I want to register in database issues related to clients on a country. So, just with Django Admin I want to click on my model Issue then select a country and when I select the field country (that field will have a Foreign Key Obviously) on another field called country I want several checkbox for all the clientes of that country. The idea is to select with checkbox the clientes of that country that has reported an issue using just Models, Admin and maybe a Forms.py Thanks in advance I tried to overwrite admin.py with a personalized forms.py on this way: from django import forms from Dashboard.models import Country, Client class Issue (forms.ModelForm): … -
Celery Task Not Respecting Soft Time Limit in Django
In my Django project, I've encountered an issue with a Celery task that seems to ignore the soft time limit I've set for it. Here's the task definition: @shared_task(bind=True, soft_time_limit=18000) def my_task(self, args): # Actual task code here The problem is that this task continues processing for a much longer time, specifically 6 hours, even though I've set the soft_time_limit to 18000 seconds (5 hours). Why is this happening, and how can I ensure that the soft time limit is respected by the task? I appreciate any insights or suggestions on resolving this issue. Thank you! -
How to add multiple images to wagtail page programmatically?
How to add multiple images to a wagtail page programmatically, while creating it as a new page? -
Deploy django to digitalocean
I use django to deploy to digitalocean, but I have used the runtime file to modify the python version, but after deployment, the following message still appears. 2023-10-24T09:29:44.757072536Z [34m╭────────────[34m[30m[44m git repo clone [0m[0m[34m───────────╼[0m 2023-10-24T09:29:44.757101317Z [34m│[0m [34m › fetching app source code[0m 2023-10-24T09:29:44.757106815Z [34m│[0m => Selecting branch "main" 2023-10-24T09:29:47.813070835Z [34m│[0m => Checking out commit "8e73926565789603a85297bedda678f76a1c3c0b" 2023-10-24T09:29:47.894764681Z [34m│[0m 2023-10-24T09:29:47.907242184Z [34m│[0m [32m ✔ cloned repo to [35m/workspace[0m[0m 2023-10-24T09:29:47.985763173Z [34m╰────────────────────────────────────────╼[0m 2023-10-24T09:29:47.985784026Z 2023-10-24T09:29:48.241850731Z [34m › configuring build-time app environment variables:[0m 2023-10-24T09:29:48.241872928Z DEBUG DJANGO_ALLOWED_HOSTS DATABASE_URL 2023-10-24T09:29:48.241876096Z 2023-10-24T09:29:48.427492632Z [34m╭────────────[34m[30m[44m buildpack detection [0m[0m[34m───────────╼[0m 2023-10-24T09:29:48.473752383Z [34m│[0m [34m › using Ubuntu 22.04 stack[0m 2023-10-24T09:29:48.956739202Z [34m│[0m Detected the following buildpacks suitable to build your app: 2023-10-24T09:29:48.956762601Z [34m│[0m 2023-10-24T09:29:48.956766764Z [34m│[0m digitalocean/python-appdetect v0.0.3 2023-10-24T09:29:48.956769954Z [34m│[0m heroku/python v2.234.4 (Python) 2023-10-24T09:29:48.956772899Z [34m│[0m digitalocean/procfile v0.0.4 (Procfile) 2023-10-24T09:29:48.956775998Z [34m│[0m digitalocean/custom v0.1.2 (Custom Build Command) 2023-10-24T09:29:48.956778905Z [34m│[0m 2023-10-24T09:29:48.956782304Z [34m│[0m For documentation on the buildpacks used to build your app, please see: 2023-10-24T09:29:48.956785169Z [34m│[0m 2023-10-24T09:29:48.956787941Z [34m│[0m Python v2.234.4 https://do.co/apps-buildpack-python 2023-10-24T09:29:48.961924274Z [34m╰─────────────────────────────────────────────╼[0m 2023-10-24T09:29:48.961940790Z 2023-10-24T09:29:48.965795463Z [34m╭────────────[34m[30m[44m app build [0m[0m[34m───────────╼[0m 2023-10-24T09:29:49.159322638Z [34m│[0m -----> Using Python version specified in runtime.txt 2023-10-24T09:29:49.853946733Z [34m│[0m ! Requested runtime 'python-3.12.0' is not available for this stack (heroku-22). 2023-10-24T09:29:49.853971556Z [34m│[0m ! For supported versions, see: https://devcenter.heroku.com/articles/python-support 2023-10-24T09:29:49.856706598Z [34m│[0m [31;1mERROR: [0mfailed to build: exit status 1 2023-10-24T09:29:50.045411097Z [34m│[0m 2023-10-24T09:29:50.052507334Z … -
Ajax redirect broken when not uploading a file
I have a small bug where it would always redirect to a URL when I'm not uploading a file but when I upload a file it works perfectly and JS successfully captures the data for the user from Django. I tried changing up the function and redirects but unfortunately it's probably not that simple... Anyhow, here's the code I have written so far: type: 'POST', headers: { "X-CSRFToken": token }, url: window.location.href, data: examData, processData: false, contentType: false, success: function (data) { if (data.user_groups.includes('rasp') || data.user_groups.includes('canyon')) { window.location.href = "{% url 'red' %}"; } else { window.location.href = "{% url 'blue' %}"; } } The code above checks in the success Ajax function based on the given data to redirect to either red/ or blue/ depending on whether the user has those groups. As mentioned it works perfectly when the user hasn't uploaded a file. views.py for f in request.FILES.getlist('file'): handle_uploaded_file(request, f, task=db_item) messages.add_message(request, messages.SUCCESS, 'Success! Area added.') if request.user.groups.filter(name=rasp).exists() or request.user.groups.filter(name=canyon).exists(): user_groups = list(request.user.groups.values_list('name', flat=True)) data = {'user_groups': user_groups} return JsonResponse(data) else: if request.user.groups.filter(name=rasp).exists() or request.user.groups.filter(name=canyon.exists(): user_groups = list(request.user.groups.values_list('name', flat=True)) data = {'user_groups': user_groups} return HttpResponseRedirect(reverse('report')) This is the django function in views.py when a submit is clicked on … -
DRF CBV PUT Fetch internal server error 500
I have User model with list of friends, when I send PUT/POST request through GUI via link http://localhost:8000/api/users/2 everything works fine.. But when I try to do this by JS using fetch I got 500 internal server error There is my model: class User(AbstractUser): email = models.EmailField(unique=True) friends = models.ManyToManyField('self', symmetrical=True, blank=True) isPrivate = models.BooleanField(default=False) askBeforeStick = models.BooleanField(default=False) stickersOnBoard = models.ManyToManyField('Sticker', blank=True) first_name = models.CharField(("first name"), max_length=150, blank=False) last_name = models.CharField(("last name"), max_length=150, blank=False) def __str__(self): return 'Email: ' + self.email There is serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'email', 'friends','isPrivate', 'askBeforeStick', 'stickersOnBoard'] There is url: router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'stickers', StickerViewSet) urlpatterns = [ path('api/', include(router.urls)), view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer and js: function getCookie(name) { let cookieValue = null if (document.cookie && document.cookie !== ''){ let cookies = document.cookie.split(';') for(let i = 0; i< cookies.length; i++) { let cookie = cookies[i].trim() if(cookie.substring(0,name.length + 1)=== (name+'=')){ cookieValue=decodeURIComponent(cookie.substring(name.length+1)) break } } } return cookieValue } let csrfToken = getCookie('csrftoken'); let friendButton = document.querySelector('#friendButton') friendButton.addEventListener('click',()=>{ let friendID = document.querySelector('#friendID') friendID = friendID.innerHTML let friendUrl = `http://localhost:8000/api/users/${friendID}/` let userId = "{{user.id}}"; let url = `http://localhost:8000/api/users/${userId}` fetch(url) .then((resp)=>resp.json()) .then(function(data){ let list … -
User-invisible tags in "django-taggit"
I use to create tags - "django-taggit". But there are several tags (20-30 pieces) that have a service value and should not appear in the template. Is there an easy way to make them invisible to the user without messing with the database? There are two opinions on this matter: Add the "turn on-off" column to the database. Try to somehow delete the desired tags by their "id". Is there a ready-made solution? -
adding a button in django admin programmatically
I have a model called "Process" and I want to rename its button in the admin_changelist view. I want to limit the overwriting of templates where possible. I created a custom form called SingleForm and a form called MultipleForm and I want a button that leads to each form. So I tried the following: Template first: {% extends 'admin/change_list.html' %} {% block object-tools-items %} <li> <a href="/admin/app/process/add_set/" class="addlink"> Add multiple Processes </a> </li> {{ block.super }} {% endblock %} ModelAdmin: class ProcessAdmin(admin.ModelAdmin): ... def get_urls(self): urls = super().get_urls() my_urls = [path("add_set/", self.add_process_set),] return my_urls + urls def add_process_set(self, request): return MultipleForm But I only end up with Process with ID “add_set” doesn’t exist. Perhaps it was deleted? Bonus question: How can I ONLY show the the button for add_set and omit the normal add button (I'd prefer without overwriting the template)? -
Django Imagefield - display current value in ModelForm
My model contains a ImageField called cover_image. cover_image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) I have a working model form that allows users to upload book details including the cover_image from the front end. They also have the option to edit the book via the front end. In the model form the field is declared in the Meta with a FileInput widget and Bootstrap CSS class. 'cover_image': forms.FileInput(attrs={'class': "form-control"}), When edit is clicked, the form loads all the instance data except the cover image. The form can be updated and saved at this point without error. How can I access the current image path? The following both return nothing {{ form.cover_image.url }} {{ form.cover_image.path }} What's the appropriate way to deal with this? Am I expected to pass an instance of the object to the form?