Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sort by letter in Django
On my website, there are different listings arranged as (a-e), (e-j), (j-o), (o-t), and all. When a user clicks on any of these listings, I want the website to retrieve data from the database starting with titles that fall within the selected letter range. However, I'm not very familiar with how to implement this functionality. Can anyone help me with this? index.html <div class="widget-content"> <h4>Sort by letter</h4> <ul class="widget-links"> {% for letter_range in letter_ranges %} {% if selected_range == letter_range %} <li><strong>{{ letter_range }}</strong></li> {% else %} <li><a href="?range={{ letter_range }}">{{letter_range}}</a></li> {% endif %} {% endfor %} </ul> views.py def index(request): letter_ranges = ['All', 'a-e', 'e-j', 'j-o', 'o-t', 't-z'] selected_range = request.GET.get('range', 'All') if selected_range == 'All': queryset = tabir.objects.filter(is_active=True) else: start_letter, end_letter = selected_range.split('-') queryset = tabir.objects.filter(title__istartswith__range=(start_letter, end_letter), is_active=True) context = { "tabirs": queryset, "current_date": datetime.now(), "selected_range": selected_range, "letter_ranges": letter_ranges, } return render(request, "ruya/index.html", context) models.py class tabir(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=200) description = RichTextField() is_active = models.BooleanField(default=False) is_home = models.BooleanField(default=False) release_date = models.DateTimeField(null=False,blank=True) #default=datetime.date.today create_date = models.DateTimeField(editable = False, auto_now_add=True)#default=datetime.date.today slug = models.SlugField(null= False, blank=True,unique=True, db_index=True, editable=False) -
HTML Django conditional statement dependent on radio button choices
I am working on an attendance system where teachers can mark a student as Present, Absent, or Late, but they can only enter a comment if a student is marked Absent or Late. I would like to make the Comment text input disabled when Present is selected. I tried different if statements with <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100">, but none seemed to work. Below is my code and a screenshot of the page. <form action="{% url 'attendance:submitAttendance' %}" method="post" name="fullForm"> {% csrf_token %} <table> <tr> <th>Student Name</th> <th>P/A/L</th> <th>Comment</th> </tr> {% for student in list_of_students %} <tr> <td>{{student}}</td> <td> <div class="radio-button"> {% for attendanceType in list_of_attendanceTypes %} {% if attendanceType.attendancetype == "Present" %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}} checked="checked"> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% else %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}}> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% endif %} {% endfor %} </div> </td> <td> <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100"> </td> </tr> {% endfor %} </table> <input type = "submit" value = "Save Attendance"/> </form>[![enter image description here][1]][1] Please note that I am not using Django forms. Any help will be appreciated. -
how do I access a previously created from a page on a different page
I am trying to open a modal i created that shows a team member's info. I want this same modal to be linked to the team members' names on a differnt page so that the same info pops up when the name is clicked. the modal works fine in the team page, but I just can't seem to figure out how to have the same modal pop up on the other page. I asked ChatGPT, and it gave me a bunch of code which did not work and I think I messed up even my previously written code. PLS HELP (sidenote: this is my first time building a website so I am very new at this). I am using django to build the website. team.html (original modal) {% extends 'base.html' %} {% block title %}Green Team - Our Team{% endblock %} {% block heading %}Our Team{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> {% for team_member in team_members %} <div class="col-md-4"> <div class="team-member-card team-card-center" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id }}"> <div class="profile-picture profile-picture center"> <img src="{{ team_member.image.url }}" alt="{{ team_member.name }}"> </div> <div class="team-member-info"> <h3 class="name"> {% if team_member.id in team_member_pks %} <a href="#" class="author-link" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id … -
how can i customize google signup template in django
before i finish signup this template apper and i want to customize it urls.py path('accounts/', include('allauth.urls')), path('users/', include('users.urls', namespace='users')), setting.py INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'grappelli', 'captcha', 'users', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google',] SOCIALACCOUNT_LOGIN_ON_GET=True SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS':{'access_type':'online'} } } LOGIN_REDIRECT_URL = 'home:home' LOGIN_URL = 'users:login' AUTHENTICATION_BACKEND=( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) i make templates>account>sinup.html but it did not work -
Handle UploadedFile in csv.reader
I am trying to read an uploaded file without saving it: def import_file(request): if request.method != 'POST': form = UploadForm() else: form = UploadForm(request.POST, request.FILES) if form.is_valid(): rdr = csv.reader(request.FILES["file"], delimiter=',') for row in rdr: print(row) ... But I get iterator should return strings, not bytes (the file should be opened in text mode) If i was reading a file with open function, I could have opened it with 'rt'. But in this case I am dealing with InMemoryUploadedFile class if I'm not mistaken. So I can't re-open it. What is the correct aproach here? Based on simpilar topics I've tried using read() and decode("UTF-8") and decode("ISO-8859-1") on the InMemoryUploadedFile, but so far nothing worked. -
Django run raw sql on existing queryset
I'm using Django 3.2 and Django Rest Framework 3.12.2. We have some custom OrderingFilters that override OrderingFilter and manipulate the received queryset. We override the get_ordering() function of the OrderingFilter: def get_ordering(self, request, queryset, view): So far we used some of the django queryset abilities. Now, I want to run a raw sql as part of the ordering process. As far as I know, we can do something like - MyModel.objects.raw("select * from my_model.....") The problem is that as I see, we can only select from the whole table (my_model in that case) and not from the already prepared queryset. What I would like to be able to do is something like - query_set = MyModel.objects.filter(created_at='2023.03.07') raw_query_set = query_set.raw("select * from query_set ...") Is it possible in some way? -
Unresolved reference 'showaddress' in pycharm
in pycharm this happen when i create class show this in admin .py this error pops up immediately how to solve this error everytime it shows this error in the console that it is reflecting this error give me step by step solution for this error -
Comments On How JoeFlow Package Works
I've just started working with JoeFlow package and need some help on it. I've installed it successfully and created an application based on joeflow tutorial. But why workflows stop in second node i.e. 'has_user' with status 'scheduled' How can I make workflows to proceed? Any advice is appreciated. Thank you -
Django why function can't be stopped with redirect to a specific URL
In a function (create_mapping) I call another function (GetCsvHeadersAndSamples) that calls another function (get_csv) that tries to get a CSV file. I want to check in this last function if the file is present before displaying a form or return a request message saying the file was not found. I also use the get_csv function in a bunch of other places create_mapping() def create_mapping(request, pk): flow = Flow.objects.get(pk=pk) if flow.fl_file_name == "": messages.error( request, 'Aucun fichier n\'a été enregistré pour ce flux. Veuillez le télécharger et mettre à jour le flux.') return redirect('flows:flow-update', pk=pk) fl_fiche_header_flow = fetch_fiche_headers(pk) headers_samples = GetCsvHeadersAndSamples(request, pk) # <------ call #2 func. HERE headers_json = make_headers_json(headers_samples['headers']) form = MappingForm(request.POST or None, headers_samples=headers_samples, fl_fiche_header_flow=fl_fiche_header_flow) context = { 'form': form, 'flow': flow, # 'mappings': mappings, 'headers_json': headers_json, 'title': 'Création Mapping Field', } if request.method == 'POST': [...] GetCsvHeadersAndSamples() def GetCsvHeadersAndSamples(request, flow_id): # returns tuple (file, separator, encoding) get_file_and_attribs = get_csv(request, flow_id). # <------ call #3 func. HERE file = get_file_and_attribs[0] separator = get_file_and_attribs[1] encoding = get_file_and_attribs[2] with open(file, newline='', encoding=encoding) as f: reader = csv.reader(f, delimiter=separator) headers = next(reader) samples = next(itertools.islice(csv.reader(f), 1, None)) headersAndSamples = {'headers': headers, 'samples': samples} return headersAndSamples get_csv() def get_csv(request, flow_id): flow = … -
Iframe responsive
I have a website where I cant make the iframe responsive. The map looks properly in computer however the map is invisible in mobile phone. I am currently using bootstrap <div class="container d-none d-sm-block mb-5 pb-4"> <div class="wrapper" id="map" style="height: 480px; position: relative; overflow: hidden;"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5994.821337674272!2d69.25345364107476!3d41.29992894681807!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38ae8ae3e16117eb%3A0xe38bf57767a5d5a9!2z0KjQutC-0LvQsCDihJY5MQ!5e0!3m2!1sru!2s!4v1689872593583!5m2!1sru!2s" width="1100" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </div> Maybe the problem is with bootstrap style so below are links and scripts: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link rel="shortcut icon" type="image/x-icon" href="img/favicon.png"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link rel="stylesheet" href="{% static 'blog/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/themify-icons.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/nice-select.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/gijgo.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/animate.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/slicknav.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/style.css' %}"> <script src="{% static 'blog/js/vendor/modernizr-3.5.0.min.js' %}"></script> <script src="{% static 'blog/js/vendor/jquery-1.12.4.min.js' %}"></script> <script src="{% static 'blog/js/popper.min.js' %}"></script> <script src="{% static 'blog/js/bootstrap.min.js' %}"></script> <script src="{% static 'blog/js/owl.carousel.min.js' %}"></script> <script src="{% static 'blog/js/isotope.pkgd.min.js' %}"></script> <script src="{% static 'blog/js/ajax-form.js' %}"></script> <script src="{% static 'blog/js/waypoints.min.js' %}"></script> <script src="{% static 'blog/js/jquery.counterup.min.js' %}"></script> … -
Django Multiple User type and extra fields
I have a project. My project has multiple user types and every type has different fields. For example user types are admin, teacher,student, admin area does not need any changes, teacher fields-> branch (mathematics, physics teacher), mentor, mentor student(relationship) student fields->school name, score, school number .... I want use admin panel and for example i want to create student in one page How should i design my model? if its impossible , what could be the alternatives Thank you for your assistance i tried abstractuser and proxy -
WebSocket connection to 'ws://localhost:8000/ws/Python/' failed: in django
I'm trying to get a WebSocket running for a Django project I'm working on, but I can't get the WebSocket to connect, which is strange since I copied the example chat application. HTML part {% block scripts %} {{ room.slug|json_script:"json-roomname" }} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e){ console.log('onmessage') } chatSocket.onclose = function(e){ console.log('onclose') } </script> {% endblock %} routing.py from django.urls import path from .import consumers websoscket_urlpatterns =[ path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WeChat.settings') application = ProtocolTypeRouter({ "http" : get_asgi_application(), "websocket" : AuthMiddlewareStack( URLRouter( room.routing.websoscket_urlpatterns ) ) }) consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) First time I'm using the WebSocket. I run the Python file and inspect the browser but I got an unexpected error like Python:64 WebSocket connection to 'ws://localhost:8000/ws/Python/' failed: (anonymous) @ Python:64 it shows the redline under the ( new WebSocket) const … -
My django server does not save my model object but if I use python shell it does
I'm still learning django, I tried to save an object from my app models on the django server but it does not work, and it shows OperationalError at/admin but if I try to use python shell to save it, it saves I need help please. -
I want to add multiple foreign key at single field in Django Model? Is it possible?
I am building an Online Attendance Application in Django. In which the teacher initiates attendance and students give their responses. Everything is great, but the problem occurs when one practical class is taken by more than one teacher at a time. I don't know how to reference multiple teacher full_name from Teacher model on a single teacher field in Attendance model. The models are: class Teacher(models.Model): full_name = models.CharField(max_length=100, unique=True) class Attendance(models.Model): std_session = models.CharField(max_length=10, default="2023-24") att_date = models.DateField(default=date.today) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) subject_name = models.CharField(max_length=50) std_class = models.CharField(max_length=50) unique_code = models.IntegerField(default=0) total_students = models.IntegerField(default=0) is_active = models.BooleanField(default=True) The view to save attendance data has a simple form.save() method. -
Getting error: from django.core.urlresolvers import reverse
I am working on django app. I am getting error when calling module. from django.core.urlresolvers import reverse "urlresolvers" here is underlined red. Which package am I missing? -
how to create user using admin token
i was trying to create user using admin token but the console show me unauthorized when i try to create the user the back-end is Django the front-end is react.js .... only admin can create the user const handleSubmit = async (values) => { try { console.log("here",values) // Make a POST request to the backend API endpoint // Get the admin token from localStorage const adminToken = localStorage.getItem('token'); console.log(adminToken) // Check if the admin token exists if (!adminToken) { console.log("Admin token not found."); // Optionally, you can show an error message or handle the absence of the token return; } // Include the admin token in the request headers const config = { headers: { Authorization: `Bearer ${adminToken}`, }, }; const response = await axios.post("http://128.140.431.171:21000/users/", values,config); // Check if the request was successful if (response.status === 200) { console.log("Driver registration successful!"); // Optionally, you can show a success message or redirect the user to another page } else { console.log("Driver registration failed."); // Optionally, you can show an error message or handle the error in another way } } catch (error) { console.log("An error occurred while registering the driver:", error); // Optionally, you can show an error message or handle … -
Django authenticate function return None although the User isn't None
I am try to make login with custom User which using email instead of username, but authenticate(email=email, password=password) returns None although the user is exist class CustomUserManager(UserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=254, unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() # use the custom manager def __str__(self): return self.email Views.py: class LoginView(FormView): template_name = 'login.html' form_class = LoginForm def form_valid(self, form): email = form.cleaned_data['email'] password = make_password(form.cleaned_data['password']) print(email, password) # for debugging purposes user = authenticate(email=email, password=password) print(user) # for debugging purposes if user is not None: login(self.request, user) return redirect('home') else: messages.info(self.request, 'invalid username or password') return redirect('login') backends.py: from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailBackend(ModelBackend): def authenticate(self, request, password=None, email=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None settings.py AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailBackend', ] I want to know why the value of user is None. I am sure the email and … -
Django, sorted fields type many-to-many in admins pages
Good day! It is necessary to display when editing the structure of the field (belonging to the parent) and sort by belonging to the parent object, which is displayed in the admin panel. I am creating a page for publishing documents in 3 categories, each category has a model (also the page itself). The following content models.py class Pages(models.Model): slug = models.CharField(default="", max_length=64, verbose_name="Slug", help_text="Фигурирует в URL, как id для ссылки на страницу") title = models.CharField(default="", max_length=255, verbose_name="Краткий заголовок", help_text="Заголовок, отображаемый в меню, блоках и прочее") description = models.CharField(default="", max_length=255, verbose_name="Описание", help_text="Описание подробное страницы, обычно используется в поисковых системах, как параметр description") public_name = models.CharField(default="", max_length=255, verbose_name="Отображаемый заголовок", help_text="Заголовок в шапке страницы") date_pub = models.DateField(default=datetime.date.today, editable=False, verbose_name="Отображаемый заголовок", help_text="Заголовок в шапке страницы") fullmenu = models.BooleanField(default=False, verbose_name="Раскрытое меню на странице", help_text="Отображать на десктопах постоянно открытое меню сайта") class Meta: ordering = ['-date_pub'] verbose_name = 'Страницы сайта' verbose_name_plural = 'Страницы сайта' def __str__(self): return self.title def get_containers(self): return Containers.objects.filter(page_member=self) #Files module #Tags menu class TagsMenu(models.Model): titlemenu = models.CharField(default="", blank=True, max_length=80, verbose_name="Название критерия файла", help_text="Название критерия файла по которому идёт выборка") order = models.IntegerField(default=0, verbose_name="Приоритет", help_text="Чем меньше число, тем выше приоритет, как порядковый номер") class Meta: ordering = ['order'] verbose_name = 'Меню тегов' … -
How to get user id or specified user only using js
Iam currently using django for a project.In my news page i need to put a delete button under the news which is if uploaded by the logged in user only,not for everyone.Question maybe stupid but expecting a way to do this using js News page looks somewhat like this -
TypeError: Object of type LinkPreview is not JSON serializable
I'm using the following link preview python package in my django 3.2 api. https://github.com/meyt/linkpreview When I post a link from my frontend flutter app and attempt to preview it, I get the error as stated. TypeError: Object of type LinkPreview is not JSON serializable Here are the views.py my flutter app hits : class PreviewLink(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) throttle_scope = 'link_preview' def post(self, request): serializer = PreviewLinkSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data link = data.get('link') user = request.user link_preview = user.preview_link(link) return Response(link_preview, status=status.HTTP_200_OK) class LinkIsPreviewable(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) throttle_scope = 'link_preview' def post(self, request): serializer = PreviewLinkSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) data = serializer.validated_data link = data.get('link') try: is_previewable = link_preview(url=link) except Exception as e: is_previewable = False return Response({ 'is_previewable': is_previewable }, status=status.HTTP_200_OK) The PreviewLinkSerializer class ---> class PreviewLinkSerializer(serializers.Serializer): link = serializers.CharField(max_length=255, required=True, allow_blank=False) The link_preview function: def link_preview(url: str = None,content: str = None,parser: str = "html.parser"): """ Get link preview """ if content is None: try: grabber = LinkGrabber() content, url = grabber.get_content(url) except InvalidMimeTypeError: content = "" link = Link(url, content) return LinkPreview(link, parser=parser) I have only pasted the relevant code above. The complete code is available in the link I shared. -
Django Multiple Database - Duplicate tables in default
I have a Django Application with two database. Even with routers, subapp tables are written in default DB. SubApp DB has only its own table. In core.models Im not define the appl_label In subapp models.py for every class, I define the app_label SubApp models.py class MyModel ... ... class Meta: app_label = 'subapp_name' db_table = 'my_model' In default settings I have defined the routing: DATABASE_ROUTERS = ["core.routers.DefaultRouter" , "subapp.routers.SubAppRouter"] In subapp router in allow_migrate, I have this: def allow_migrate(self, db, app_label, model_name = None, **hints): if app_label == 'subapp_name' and db == 'subapp_name': return True return None This works well. In SubApp Database I only have MyModel table and a DjangoMigration table (this one has all migrations rows, even from default modules). This is the allow_migrate in DefaultRouter: def allow_migrate(self, db, app_label, model_name = None, **hints): route_app_labels = { "admin", "auth", "contenttypes", "core", "sessions" } if app_label in self.route_app_labels: return db == "default" return None Unfortunally, subapp MyModel is create in default database too but subapp is not inside route_app_labels. Why is this happening? -
Is there any settings to use Django timezone other than TIME_ZONE?
I am using django and postgres. I set this in settings.py TIME_ZONE = 'Asia/Tokyo' USE_TZ = True in my models.py there is models which uses DateTimeField. class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass then check admin console http://localhosg:8000/admin, but time zone is not applied. Still UTC is used in created_at and updated_at Is there any other things I need to check? -
Django Admin Dashboard ImageField Problem
In my django admin dashboard i made a model for an ImageField, problem is that i will use that for a carousel but for that i need to upload more than one image, django limits to only uploading 1 image at a time, and i tried looking around for about 3 hours and i couldnt find any solutions for it, everytime i find something either it doesnt work anymore or its not what im looking. So overall i just want a solution for the Choose Files button when i click it i can choose more than one file/img i tried looking for solutions for more than 3 hours and couldnt find anything that would work -
Customize Django Admin, Order and place of model
I have a Django project in this project i have app a with model A and app b with model B. # a/models.py class A(models.Model): pass # b.models.py class B(models.Model): pass So i see Model A under section of app a and same for Model B. But I want to change this placement because from the first of project I was bad in layout. notice: I've tried putting BModelAdmin(admin.ModelAdmin) in admin file of app a and it has not worked. please tell me an absolute answer. -
django admin panel data
Hi Team i have a written code in admin.py. At this time i am getting urls and other feilds . what i want as url can be duplicate for ex i have google url but each url consist if different crud operations . what i want is grouping . Please advise how we can do that. class UrlAccessAdmin(admin.ModelAdmin): list_display = ('method', 'clickable_url', 'has_access', 'get_roles', 'description') list_filter = ('method',) search_fields = ['url', ] list_per_page= 15 def get_roles(self, obj): return obj.role_list if obj.role_list != 'ALL' else 'All Roles' def clickable_url(self, obj): url_length = 50 if len(obj.url) > url_length: truncated_url = f'{obj.url[:url_length]}...' else: truncated_url = obj.url return mark_safe(f'<a href="{obj.url}" target="_blank">{truncated_url}</a>') clickable_url.short_description = 'URL' admin.site.register(UrlAccess, UrlAccessAdmin)