Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no space between images in inline display images (xhtml2pdf)
I am using xhtml2pdf to generate PDF file from my DetailView in Django. I have a loop in my html template file where I am displaying all images in 1 line. What I am struggling with is adding some space between images and either padding, padding-left, padding-right, margin, margin-left, margin-right don't work in inline display. They only work if I put images in seperate lines. I do the same on my website and the padding works fine but not in my pdf. I've read in the documentation and there is information that there is no way to use images within paragraphs so images are always rendered in seperate paragraphs (link for reference is here). Question: Is there any way in xhtml2pdf to add space between images if I want to keep them in 1 line? I am looking for some tips, hacks, or any solution to this problem. my loop in HTML file <div> {% for client in product.client.all %} <img src="{% thumbnail client.client_logo 125x100 upscale %}" alt="{{client.title}}" class="client-logos"> {% endfor %} </div> utils.py def export_to_pdf(request, slug): product = get_object_or_404(Product, slug=slug, status=1) template_path = 'card_pdf_template.html' teams = Team.objects.filter(product__slug=slug) context = {'product': product, 'teams': teams} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename={product}.pdf'.format(product=product) … -
how to solve such question: The view didn't return an HttpResponse object. It returned an unawaited coroutine instead
` @csrf_exempt async def predict_images(request): if request.method == 'POST': data = json.loads(request.body) user_id = data['user_id'] task_id = data['task_id'] surgical = data["surgical_intervention"] years = data["years"] flag = check_userID_taskID(user_id, task_id) image_list, filepath = lookup_database(user_id, task_id) func = sync_to_async(func) await func(image_list, filepath, surgical, years) async def func(image_list, filepath, surgical, years): "some deal function" return ` I want to call func Asynchronous. The predict_images function is a async view function. I want such situation that the view function response immediately and func executes in the background. But I get error as shown in title. I have tried many solutions but all failed. Could you give me solution andd explain why? And func is a computationally intensive task. Thank you. The detail as above . -
in django is it possible to have a two part form with some repeating fields?
I would like to have a form with a few fields that will repeat themselves Django a django form with a few fields that have multiple entries -
Django subquery pass extra workaround distinct since mysql
I am trying to prepare subnet=adress/netmask for presentation, and start_ip and end_ip for filtering purpose under lifs qs. then I want to use subquery to cut of single interface as vserver may have multiple. Problem is that I can't pass extra field generated in lifs queryset. lifs = (NetworkLif.objects.filter(vserverid=OuterRef('pk')) .annotate(network=Concat('address', Value('/'), 'netmasklength', output_field=CharField())) .extra(select={'start_ip': "INET_NTOA(INET_ATON(address) & 0xffffffff ^ ((0x1 << ( 32 - netmasklength) ) -1 ))"}) .extra(select={'end_ip': "INET_NTOA(INET_ATON(address) | ((0x100000000 >> netmasklength ) -1 ))"}) .order_by('network') ) queryset = (Vserver.objects.filter(type='DATA') .exclude(name__endswith='-mc') .annotate(subnet=Subquery(lifs.values('network' )[:1]), #.annotate(start_ip_address=Subquery(lifs.values('start_ip')[:1])) #.annotate(end_ip_address=Subquery(lifs.values('end_ip')[:1])) .values('id', 'clusterid__name', 'name', 'state', 'nfsenabled', 'cifsenabled', 'ldapclientenabled', 'dnsenabled', 'subnet', )#'start_ip_address')#, 'end_ip_address' ) .order_by('id') ) getting this error, I guess this is becuase evaulation logic raise FieldError("Cannot resolve expression type, unknown output_field") django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field is there any workaround? I know in postgresql distinct('name') would fix my problem. unfortunetelly ActiveIQ is running on mysql. -
PostDetail.post() got multiple values for argument 'slug'
I am trying to submit comments on my blog posts but I get faced with this traceback every time. When it succeeds the comment will then be subjected to moderation before showing on the website. If I could get any help it would be greatly appriciated! Here is the traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/cubs/post/should-be-the-final-test-lmao/ Django Version: 4.1.2 Python Version: 3.10.6 Installed Applications: ['beavers.apps.BeaversConfig', 'cubs.apps.CubsConfig', 'scouts.apps.ScoutsConfig', 'accounts.apps.AccountsConfig', 'executive.apps.ExecutiveConfig', 'main_website.apps.MainWebsiteConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django_summernote', 'crispy_bootstrap5', 'taggit_helpers', 'taggit_labels', 'debug_toolbar', 'admin_reorder', 'crispy_forms', 'storages', 'taggit'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'admin_reorder.middleware.ModelAdminReorder') Traceback (most recent call last): File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) Exception Type: TypeError at /blog/cubs/post/should-be-the-final-test-lmao/ Exception Value: PostDetail.post() got multiple values for argument 'slug' PostDetail (views.py) class PostDetail(LoginRequiredMixin, DetailView): model = Post form_class = CommentForm template_name = "cubs/post_detail.html" def get_form(self): form = self.form_class(instance=self.object) return form def post(self, slug, *args, **kwargs): new_comment = None pk … -
Python: Need guidance with a dropdown list
I took over a web app from a user who left the company and I don't know what I'm doing. Basically I have a site table that has 2 columns I need, site and name. I want the name to display in the dropdown menu and site to be the value of the dropdown. This what it looks like now: In the views template def getWarehouseList(): warehouse_list = ['Warehouse'] + pd.DataFrame.from_records(Site.objects.filter(active=True).values('site')).sort_values('site')['site'].tolist() return tuple([(choice, choice) for choice in warehouse_list]) In the html/view: <select id="warehouse\_drop" name = "warehouse"> {% for warehouse in warehouse\_list %} <option value ="{{warehouse}}">{{ warehouse }}</option> {% endfor %} </select> How can I change the option value to be "name" instead of "site" (warehouse). Thank you. -
Django 'utf-8' codec can't decode byte 0x99 in position 5289: invalid start byte
I work on a website with python, before I change my database from sqlite to mysql I saves it as a json file python manage.py dumpdata > datadump.json after I changed my settings.py to the mysql database and migrate is I wanted to move data to mysql db by: python manage.py loaddata datadump.json but it cause this error: File "C:\Users\M.Hawa\Desktop\My_Django_Stuff\firstproject\deneme\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 5289: invalid start byte Not: I tried to change stream_or_string = stream_or_string.decode() to: stream_or_string = stream_or_string.decode("UTF-16") but it did not work I looking for solutions -
how to user django rest framework serializer outside of django in python console
I am using a DRF serializer in my project as below # my_serrializers.py from rest_framework import serializers class TssUpdateExtraVarsSerializer(serializers.Serializer): cluster_name = serializers.CharField(required=True) class TssUpdateSerializer(serializers.Serializer): extra_vars = TssUpdateExtraVarsSerializer(required=True) It works fine when I send a request and it handles the job. But if I open a python console (the one in my project's venv) as below: #python console from my_serializers import TssUpdateSerializer s = TssUpdateExtraVarsSerializer(data={"a": 1}) s.is_valid() I get this error django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. what is the reason for it and how to fix it. I want to be able to play with it outside of django. is it possible? how? -
I'm excluding the objects with None value, but all of them are being returned, why?
I'm using a function to get the URL and avoid the link if the foreign key (cve) is none. def get_absolute_url(self): try: return reverse('detail', args=[self.cve, self.id) except NoReverseMatch: pass But, where I'm using these URLs, I'm also FILTERING to exclude when the fk is None. class VSitemap(Sitemap): def items(self): return Vuln.objects.exclude(cve__in=[]).exclude(cve=None) Thus, I'm getting this: <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> Everything I'm getting Is None even if I filter too much. -
How can I get the cards to appear next to each other in a row to fill up the grid before starting a new row?
I have data from a table and the cards are being created from that data and rendered onto the screen. However, they appear beneath each other on the left side rather than filling up a row first before starting a new row: (https://i.stack.imgur.com/dDgvB.png) My code is: <div class="container"> {% for class in all_classes %} </br> <div class="row-sm-3"> <div class="col-sm-4"> <div class="card-deck"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title">{{ class.class_name}}</h5> <p class="card-text">{{class.teacher_id.username }}</p> <a href="#" class="btn btn-primary">Go To</a> </div> </div> </div> </div> {% endfor %} </div> How can I fix this? -
How can I analyze Django ORM query performance on a server with DRF Endpoints only?
Previous Django apps I've worked on have used HTML template rendering, and django-debug-toolbar has proven to be a valuable way to analyze ORM SQL queries and find places to optimize. The current app I'm working on uses Django for django-rest-framework REST endpoints only, and has no HTML views. Is there a way I can analyze queries in a similar way? I looked into django-debug-toolbar + django-debug-panel (with a Chrome extension), but it's quite a bit out of date, requiring Django 2.1 or earlier. -
Error Unable to lock the administration directory (/var/lib/dpkg/) are you root?
I am in my distant server ovhCloud whose python is version 3.5.3 and I would like to update it to 3.10 I have this error (Unable to lock the administration directory (/var/lib/dpkg/) are you root ?) and even the sudo command is not recognized `bele@cloudweb-ssh:˜ $ sudo apt update bash:sudo:command not found` How to solve this? I tried also su root I get permission denied -
My site is not displayed in the Google search list
I just uploaded a site with Django on pythonanywhere and it was indexed by Google and it is displayed in the English search list, but it is not displayed in the Persian search list. This is my website link: https://peshgaman.pythonanywhere.com/ I registered my site in google search console and also created a sitemap for my site -
Django throw empty validation error on admin field when using filter_horizontal. is it normal?
I have ThesisExamSchedule model that I registered in admin using ModelAdmin. class ThesisExamSchedule(models.Model): participant=models.ForeignKey(User,on_delete=models.CASCADE,related_name="thesis_participant") room=models.TextField() date=models.DateField() start_time=models.TimeField() end_time=models.TimeField() thesis_title=models.TextField() examiner=models.ManyToManyField(User) def __str__(self) -> str: return self.participant.first_name class ThesisExamScheduleAdmin(admin.ModelAdmin): list_display=['participant','date','start_time','end_time','thesis_title'] filter_horizontal=['examiner'] autocomplete_fields=['participant'] admin.site.register(ThesisExamSchedule,ThesisExamScheduleAdmin) After I choose multiple users to fill examiner field then hit save. Django admin throw empty validation error and the examiner field emptied. Scenario 1 validation error throwed: choose users from left box. chosen user show on the right box. validation error throwed. Scenario 2 Success: choose users from left box. chosen user show on the right box. select user (highlight the user). submit success. Is it normal? My expectation is there will be no error when using scenario 1 -
use python to estimate probability
Use python to estimate the probability. There are three Urns (A, B and C), which each contains the following balls: A: 1 white, 2 black and 3 red balls B: 2 white, 1 black and 1 red balls C: 4 white, 5 black and 3 red balls One urn is chosen at random and two balls are drawn which are white and red. What is the probability that they came from urn B or C? # It is easy to use Bayes' theorem to calculate the exact probability(the answer is 85/118), but when using "random" to estimate the probability in python, it is rather difficult. Can you help me? Thanks! -
Is there a solution to load html without asking me to store them in static folder?
My index is loading well on browser, but when I click home page, there is nothing 404 error, is responding static/index.html, (when I click home page or any other such as contact, it is searching for html in static) why is it asking for index.html in static files and how can I rectify that?[ I stored my html files on templates folder thinking that when i clicked my dropdown, they were going to apper on my web. -
Using Cache in UserViewSet in djoser in django / djangorestframework
i am currently using cache_page from decorators in django rest framework to cache the api. For authentication I am using djoser with django rest framework, but i dont understand how i can add cache_page decorator in djoser urls. This is my one of the viewset for cache class TagViewSet(viewsets.ModelViewSet): queryset=Tags.objects.all() serializer_class=TagSerializer permission_classes=[permissions.IsAuthenticated] authentication_classes= [authentication.TokenAuthentication] #Cache @method_decorator(cache_page(30)) def dispatch(self, *args, **kwargs): return super(TagViewSet, self).dispatch(*args, **kwargs) i want exactly the same with djoser urls but i dont have the userviewset and i dont know how to access it. views.py (user) empty Please guide me how i can add cache_page for djoser urls -
Group every objects by year
I had 3 objects [{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', u'id': 2, u'tipo': u'NIP', u'slug': u'copa-06'}, {u'criados' : u'16/5/2020 21:25', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/test.pdf', u'id' : 3, u'tipo: u'NIP', u'slug': u'test-02'}] this objects has different year and i want to display in html something like this: 2022 - Object 1 - Object 2 2020 - Object 3 please help me -
how to serve a media file in Django?
I have a Django project where I'm trying to create a card with an image that was uploaded by the user. I keep getting a certain error but I have already done every solution and its still coming up. any help would be appreciated. the {{image}} variable isn't working html page <div class="p-5 mx-4 bg-white border-2 border-gray-300 grow"> <button><img src="{{image}}" alt=""></button> <h3>{{title}}</h3> <span>{{currentBid}}</span> <span>{{sellor}}</span> </div> settings MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\ urls urlpatterns = [ path("", views.activeListings, name="activeListings"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("createListing", views.createListing, name="createListing"), path("listingPage/<str:title>", views.listingPage, name="listingPage"), path("wishlist", views.wishlist, name="wishlist"), path("catagory", views.catagory, name="catagory"), path("catagoryListing/<str:catagory>", views.catagoryListingsPage, name='catagoryActiveListingsPage'), path("catagoryListing/listingPage/<str:title>", views.listingPage, name="catagorylistingPage"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also have the media url pattern line in the urls for my whole project error 04 4334 Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-09-19_at_2.39.14_PM.png Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-19_at_2.38.33_PM.png HTTP/1.1" 404 4355 WARNING:django.request:Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /temperature-anomaly_wlbvLbQ.png WARNING:django.request:Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-09-19_at_2.39.14_PM.png HTTP/1.1" 404 4334 WARNING:django.request:Not Found: /temperature-anomaly_wlbvLbQ.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-10-10_at_5.42.19_PM.png HTTP/1.1" 404 4334 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /temperature-anomaly_wlbvLbQ.png HTTP/1.1" 404 4307 debug is … -
Slug in Djnago URL
I want to create a directory like mysite.com/user after user get logged In. i.e mysite.com/john Here is the corresponding views and urlpatterns. But after authorization I only left with http://127.0.0.1:8000/authorization instead of http://127.0.0.1:8000/user ? models.py user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) project/urls.py urlpatterns = [ path('authorization/', include('authorization.urls')), ] authorization/app/urls.py urlpatterns = [ path('', views.index, name='index'), path('<slug:user>/', views.user_name, name='user_name'), # here path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] corresponding views.py for that user_name @login_required @twitter_login_required def user_name(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/home.html', {'user':user}) -
How to link to URL of related object in DRF
I’m making a music player with a DRF backend. I have two models, one is Song and the other is TrackQueue In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta. What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1) What would that url be and how can I create it? Thank you models.py class Song(models.Model): title = models.CharField(max_length=24) file = models.FileField() def __str__(self): return self.title class TrackQueue(models.Model): title = models.CharField(max_length=64) is_song = models.OneToOneField(Song, on_delete=models.CASCADE) def __str__(self): return self.title Serializers.py from rest_framework import serializers from .models import Song, TrackQueue class SongSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Song fields = ('id' ,'title', 'file') class TrackQueueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TrackQueue fields = ('id' , 'title', 'is_song') views.py from django.shortcuts import render from .serializers import SongSerializer from rest_framework import viewsets from .models import Song, TrackQueue from music.serializers import SongSerializer, TrackQueueSerializer class SongView(viewsets.ModelViewSet): serializer_class = SongSerializer queryset = Song.objects.all() class TrackQueueView(viewsets.ModelViewSet): serializer_class = TrackQueueSerializer queryset = TrackQueue.objects.all() -
Django href link not routing to correct url
The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'. I am using class based views and following chapter 3 of Django for beginners (William Vincent). pages/templates/base.html: <header> <a href="{% url 'home' %">Home</a> | <a href="{% url 'about' %">About</a> </header> pages/urls.py: from django.urls import path from .views import HomePageView, AboutPageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), path("about/", AboutPageView.as_view(), name="about"), ] portfolio/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("pages.urls")), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] pages/views.py: from django.views.generic import TemplateView # Create your views here. from django.http import HttpResponse class HomePageView(TemplateView): template_name = 'home.html' class AboutPageView(TemplateView): template_name = "about.html" The error is as follows: Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about/ [name='about'] The current path, about/{% url 'about' %, didn’t match any of these. Terminal error: Not Found: /{% url 'about' % [26/Oct/2022 11:40:02] "GET /%7B%%20url%20'about'%20% HTTP/1.1" 404 2497 I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/%7B%%20url%20'home'%20%'. I've tried … -
Nth-child does not change colour for odd and even
This a Django project, in which I loop over folders and files. The background colour of each file should be different. For example, the odd ones should be purple and the even ones should be blue. But they are all shown as purple. Here is the file div from HTML: <div class="each_key">{{file}}</div> Here is the styling in CSS: .each_key:nth-child(odd){ text-align: left; width:197px; height:42px; background-color: purple; padding:10px; } .each_key:nth-child(even){ text-align: left; width:197px; height:42px; background-color: blue; padding:10px; } I've also tried "nth-of-type" and it still gives me purple instead of changing to purple and then blue. -
Django models - Custom jsonfield update method
So my intention is to be more effective when it comes to touching the database jsonfields in my postgres db. I could of course append the jsonfield data like so (both are lists with inner dicts): obj.jsonfield = new_data + old_data obj.update_fields(["jsonfield"]) but I wonder if there is a better way for doing so, because when I got this right, the database first removes old_data and afterward updates the field once again with the old_data. Is there a better way for me to just append to the old_data list in a custom update_fields method? If what do I need to consider there? Thanks a lot -
Need help for Creating Biometric Attendance web application using Django rest api
i'm very new to this it side coming from non-it, recently got placed as python developer through self learning. joined after my company asks me to develop the biometric attendance system for the internal purpose. can anyone guide me how to develop it, what are the model fields required, how should i integrate the device with my rest api application. somebody please help and guide me. i dont know where to start