Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Django images don't show up on the web-site
settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') template <img src="{{ group_avatar.avatar.url }}" style="width:30%" alt="Group Avatar" class="navbar-brand"> urls.py `urlpatterns = [ path('admin/', admin.site.urls), # Django admin route path("", include("apps.authentication.urls")), # Auth routes - login / register # ADD NEW Routes HERE # Leave `Home.Urls` as last the last line path("", include("apps.home.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` Instead of getting an image, I get an alt text... I've tried to fix it up for a long time, but nothing works... Django version 3.2.16, using settings 'core.settings' I suppose that the problem is in the project structure. It was done before I started working on the project and it would be difficult to change it... application is in the folder apps, which is in the root folder, and template which is needed is also there. But the folder 'media' is in the root directory. Although I'm not sure that the problem is in this. Interesting fact is that if I manually write the way to the image from static folder (static folder is also localed in apps directory) it will work. Would be glad for any help) Searching, reading documentation. I expect a hint how to fix it or where to search the … -
Django Paginator with bulk_update only updates odd pages
I have a two tables that have around 1M rows and in one of them, I've added a new migration that adds two new columns to one of them and that requires some computation to add their values. What I did was a command that fetches all rows in that table, and use Paginator with a chunk size of 1000, and after adding the new values, I perform the bulk_update. The problem is that only the odd pages are updated, the even ones stay with the null value. I start with 1000 pages to update, then I need to run again only to update 500 pages, and so on. I've also tested with chunks of 10, and the problem persists. Is there something wrong with this code? def add_values_to_columns(foo): foo.col1=... foo.col2=... class Command(BaseCommand): def handle(self, *args, **options): try: queryset = Foo.objects.all() \ .filter(col1__isnull=True, col2__isnull=True) \ .order_by("id") \ .select_related("bar") chunk_size = 1000 paginator = Paginator(queryset, chunk_size) pages = paginator.page_range number_pages = pages[-1] for page_number in pages: page = paginator.page(page_number) updated_rows = [] for foo in page.object_list: add_values_to_columns(foo) updated_rows.append(foo) Foo.objects.bulk_update(updated_rows, ["col1", "col2"]) except Exception as e: self.stdout.write(e) -
Django VS-Eextenstion is not colorizing syntax inside cotation
I am using Django extension to highlight my text. it works perfectly outside but fails to highlight inside citations. not working under cotations I expect if there is any solution to overcome this. I want it to highlight the code inside exactly as outside , what can i do to overcome this. -
List column data in Django template can not be iterated
Please read my code <p>{{request.POST}}</p> <p>langchi : {{request.POST.langchi.0}}/{{request.POST.langchi.1}}/{{request.POST.langchi.2}}/{{request.POST.langchi.3}}<p> <p>langeng : {{request.POST.langeng.0}}/{{request.POST.langeng.1}}/{{request.POST.langeng.2}}/{{request.POST.langeng.3}}</p> <p>langjpn : {{request.POST.langjpn.0}}/{{request.POST.langjpn.1}}/{{request.POST.langjpn.2}}/{{request.POST.langjpn.3}}</p> Output Screen We can tell in the request.Post, there are 3 list data langchi, langeng and langjpn. But when I try to read them by request.Post.langchi.0,request.Post.langchi.1... I can not get the actual value. Did I do something wrong? Appreciate for any help. Appreciate for any help. -
Django admin panel CSS files are denied to access to GC bucket
In my Django rest framework project, I have used the filter from django admin panel to filter users This is what I'm using : my codein admin.py based on their profile. This work fine in my local host localhost filtering users Now I'm hosting my project on GCP, once I push to live staging the screen display like this : the panel after pushing to staging . What I got in the console when I go to filter users is console when I use the filter the network tab in condole when I click over one of the error Thanks a lot of any suggestions https://github.com/jschneier/django-storages/issues/454 -
How to get User queryset from his Profile
Good afternoon. I am creating a referral system and at the last stage a question appeared. I need to get request.User and inviting.User querysets for Friends.create.objects(inviting=current_user, invited=inviting_query.user) How i get they? My models Post function -
artichels_pagination.get() missing 1 required positional argument: 'request'
class artichels_pagination(ListView): queryset =models.article.objects.all().order_by('-upload') template_name = 'blog.html' def get(self,request): page_artichel = Paginator(self.queryset, 2) page_number = request.GET.get('page') page_obj = page_artichel.get_page(page_number) render(request,self.template_name,context={'artichel':page_obj}) this is eror: artichels_pagination.get() missing 1 required positional argument: 'request'