Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django channels app is blocking when handle many requests
i have a DRF project, using django channels, i have a endpoint that handles thousands requests for each 5seconds, sometimes this endpoint is blocking my app, what would be the best way to handle it? some posts adivises to use raise StopComsumer() in the disconect method, but not resolve this is my consumer class ChargerSessionConsumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.client_id = None self.group_name = None async def connect(self): self.group_name = 'room' self.client_id = self.scope["url_route"]["kwargs"]["client_id"] await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.channel_layer.group_add( self.client_id, self.channel_name ) await self.accept() async def websocket_disconnect(self, message): await self.channel_layer.group_discard( self.group_name, self.channel_name ) await self.channel_layer.group_discard( self.client_id, self.channel_name ) raise StopConsumer() -
Add Django super user token in http request
I use Django (as backend and frontend) for a website. I want to create http request with the condition (of use) to be Django super user. But I don't know how to add in the headers the token (or the proof that the user that uses the request is a super user). I tried this with the csrf token : First I use the {% csrf_token %} in the template. <form action="#" id="admin-add-event" method="POST"> {% csrf_token %} ... <button type="submit" id="admin-submit">Add event</button> </form> const url = `${window.BASE_URL}events/`; const form = document.getElementById('admin-add-event'); const data = { ... } let xhr = new XMLHttpRequest(); xhr.open('POST', url , true); xhr.setRequestHeader('X-CSRFToken', form.elements.csrfmiddlewaretoken.value); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = function () { ... } xhr.send(JSON.stringify(data)); And in the Django view of the endpoint : @api_view(['GET', 'POST']) def all_events(request): if request.method == 'POST': if not request.user.is_superuser: return Response(status=status.HTTP_401_UNAUTHORIZED) # etc ... But the check of super user fails always I precise that I don't want to implemente a user system. I want to use the system of super user of Django. Thanks in advance ! -
How to use Django ImageField to upload to Google Cloud Storage instead of local
I want to use Django's ImageField on a model so people can upload a logo. I found the ImageField however reading from the docs it says Django stores files locally, using the MEDIAROOT***andMEDIAURL** settings.py I'm wondering how I can change the *upload_to= behavior to upload to a gcp bucket instead? If it's possible when I call .save what is saved to the database, the gcp bucket url? From reading the docs it doesn't say one way or the other if this is possible or if all images should be stored locally where the service is being ran. I have thought of saving the binary images directly to the db but that seems inefficient. -
How to add prefix before token in request using drf-yasg or drf-spectacular
I need add prefix "Token" before token in request header when using drf-yasg or drf-spectacular to create django drf API doc. I have tried multiple tests: Middleware: SWAGGER_SETTINGS 3)SPECTACULAR_SETTINGS: Token plus token in authorize form: Url configs: Options 1), 2) and 3) the request headers are: and with 4) return 401 http status code with the options 1), 2), 3) I receive 401 ""Authentication credentials were not provided." and with 4) invalid token Can you help me please? -
Django reverse() behind proxy
My Django REST API is deployed behind an API Gateway (Kong). I want to reserve() some urls in my APIViews. I would like to ask for help to get the right url format. Based on basepath of the API gateway. Communication flow: Client (requesting basepath) <-> Kong (forwarding to upstream) <-> Apache (Reverse Proxy) <-> Django Kong defines a basepath and an upstream to forward client request to Django. Kong includes X_FORWARDED_HOST and X_FORWARDED_PATH in the HTTP header. X_FORWARDED_PATH contains the basepath of the gateway. X_FORWARDED_HOST contains the gateway-url. Gateway basepath is: /gateway-basepath Upstream path is: mydomain.com/py/api/v1 Basically, without gateway, Django reverse() creates following url for users endpoint: mydomain.com/py/api/v1/users/ With the API gateway, the Django creates follow path: apigatewayurl.com/gateway-basepath/py/api/v1/users/ Django is considering X_FORWARDED_HOST, but not X_FORWARDED_PATH I need following result: apigatewayurl.com/gateway-basepath/users Otherwise the Django url resolving is not usable within the api gateway. I would appreciate any help. urls.py from rest_framework.views import APIView from rest_framework import routers from . import views class APIRootView(APIView): def get(self, request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), }) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('api/v1/', APIRootView.as_view(), name="api_root"), ] urlpatterns += router.urls views.py from rest_framework import viewsets from django.contrib.auth import models as django_models … -
Django 404 email notification
I want to get an email every time someone on my site gets a 404. I added the following code to my settings.py file DEBUG = False MANAGERS = ADMINS MIDDLEWARE = [ 'django.middleware.common.BrokenLinkEmailsMiddleware', ] The problem is that it just doesn't work. After reading this ticket I decided to try to following I went to the file django/middleware/common.py And made a change to the following class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "") if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get("HTTP_USER_AGENT", "<none>") ip = request.META.get("REMOTE_ADDR", "<none>") mail_managers( "Broken %slink on %s" % ( ( "INTERNAL " if self.is_internal_request(domain, referer) else "" ), domain, ), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), fail_silently=True, ) return response FROM referer = request.META.get("HTTP_REFERER", "") To referer = request.META.get("HTTP_REFERER", "None") New class class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "None") if not self.is_ignorable_request(request, path, domain, … -
Getting a problem after deploy a Django app on Render
I developed an app in Django using PostgreSQL as DataBase, on a local environment it works without problems, but when it was deployed on Render.com it the app throws me this error. I had to set the debug in True to watch the error This is that Render console shows me: django.db.utils.ProgrammingError: relation "management_notificacion" does not exist Jun 28 04:55:41 PM LINE 1: SELECT COUNT(*) AS "__count" FROM "management_notificacion" ... This is the line of code that is given the error, but in local works without problems context_processors.py from management.models import * def get_notificaciones(request): notificaciones = Notificacion.objects.filter(receptor=request.user.id)[:3] no_vistas = Notificacion.objects.filter(receptor=request.user.id, visto=False).count() return { 'notificaciones': notificaciones, 'no_vistas': no_vistas } def get_mensajes(request): mensajes = Mensaje.objects.filter(receptor=request.user.id)[:4] no_vistos = Mensaje.objects.filter(receptor=request.user.id, visto=False).count() return { 'mensajes': mensajes, 'no_vistos': no_vistos } If anyone can give a hint to solve this, I'll be so grateful! -
How can I modify attributes of objects in a Django queryset for data presentation without modifying the original object?
I want to present a list of objects for which I want to filter/modify one attribute during the presentation of the data. Something close to an annotation, but I did not manage to do it with annotations. These are the models class Airline (models.Model): name = models.CharField() destinations = models.ManyToManyField("city") customers = models.ManyToManyField("user") class City (models.Model): name = models.CharField() country = models.CharField() class User (models.Model): name = models.CharField() preferredDestinations = models.ManyToManyField("city") I want, for a given user, present a list of the Airlines the user is customer, and for each Airline present the list of destinations for the Airline. But instead of presenting all the airline destinations I only want to present the destinations preferred by the user. e,g, Airline1.destinations=["New York", "London", "Paris", "Madrid] Airline2.destinations=["Madrid", "Barcelona", "Rome", "Berlin", "London"] User1.preferredDestinations=["Madrid", "Barcelona", "Paris"] With user1 being a customer of Airline1 and Airline 2, I want the page to present a table showing to which of the user preferred destination every airline flies to. I.e. I do not want to see all the destinations the airline flies to, only the ones the user is interested: E.g. Welcome User1! These are your airlines that fly to your preferred destinations Airline | Destination | … -
DJANGO: replace a combobox created successfully in a list of views.py, with one created with classes in forms.py?
I'm new to Django. I saw that there are 2 different ways to create comboboxes and forms. I would like to replace my current mode, already successfully created, with another mode. WAY 1 (works well, correctly): I have a combobox that works fine, created by putting the items in a list in views.py, for example: color_choices = ("Red","Blue","Black", "Orange"). I am currently using this mode. WAY 2: Way 1 works fine correctly for me, but only now I've seen that it's possible to create comboboxes also by creating a forms.py file, importing from django import forms, and then writing the items in the classes. The combobox uses a static list QUESTION: How can I modify my code (which uses Way 1) and replace it with forms.py with Way 2 classes? I would like to use the classes and the forms.py file, and I would not like to use the items in the views.py file (it works correctly fine with Way 1). Can you show me how I can use Way 2 correctly? Thank you all! Which of the two ways is more correct and better in terms of loading speed? Thank you all! P.S: comboboxes are database independent. they don't … -
Google Analytics GA4
The number of users who have registered on my website on GA4 is less than the one I got from the DB. Anyone can help here? Both google analytics and extracted data are in the UTC time and on GA4 Im checking the total users value Thannk you! -
Django xhtml2pdf, changing to custom font not working
I'm trying to change the font in my html to pdf project using xhtml2pdf (version 0.2.11) in Django (version 4.2.2). I'm running the project on my Windows 11 Home 22H2, using python 3.11.0 Here is how I try to import the font file html snippet, but the font did not reflect on the page. html snippet @font-face { font-family: Ysabeau Infant; src: url('fonts/Ysabeau-Infant.ttf'); } Views.py def report_rednder_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'reports/pdf2.html' context = {'report': report} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') # If downloadable remove comment #response['Content-Disposition'] = 'attachment; filename="report.pdf"' # If viewable remove comment response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funny view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response I tried using the absolute path C:\Users\USER\Desktop\PROJECT\static\fonts\Ysabeau-Infant.ttf instead of the relative path, but that did not work, I get the error: TTFError Exception Value: Can't open file "C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf" and from the terminal I get the error, Permission denied: 'C:\Users\USER\AppData\Local\Temp\tmpwsd3c9z2.ttf' I tried running … -
Use user id in bigquery SQL query that is passed into the function via an argument
I'm trying to get the last synced data from bigquery for the given user The query consists of this: mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ This is the function below: def facebook_last_pulled(user): # i've tried this code on the line below and replaced user.id with current_user_id in order to make sure the id is in the form of a string as well as using the CAST method on user id in the query #current_user_id = str(user.id) mc_query = """ SELECT _fivetran_synced, connector_name FROM `database....` WHERE connector_name = 'pm_' + user.id + '_facebook_pages' """ print(user.id) last_pulled_data = google_big_query(mc_query) Where I print user.id I get the user id I'm looking for but when I put it into the query I get GenericGBQException, Reason: 400 Unrecognized name: user at [4:45]. So from the seems of it user isn't getting picked up in the variable mc_query, anyone know the reason I'm not getting user in there or a way to solve this? I've tried setting a variable for user.id and using the variable instead of user.id as well as the CAST method in order to change it to a string inside the query. … -
How to add multiple "OR" queries in Django
I have 2 models, Item and Category, the model Item has category field as a foreign key In my views.py I get a list of queries from a POST request queries = ['category1', 'category2', 'category3', ...] I don't know the number of the queries I will get from the request, and I want to filter the Item model based on category field I tried this from django.db.models import Q from .models import Item, Category from django import views class myView(views.View): def post(self, request): queries = request.POST.get('queries', '') if queries: queriesList = [] queries = queries.split(',') # queries = ['category1', 'category2', ....] for query in queries: queriesList.append(Q(category__icontains=query)) queryset = Item.objects.filter(*queriesList) # this will do AND but won't do OR # I tried: queryset = Item.objects.filter([q | Q() for q in queriesList]) but it didn't work Also I tried queryset = Item.objects.filter(category__in=queries) but it's case sensitive -
Refreshing variables shown in a html file by pressing a button
I have a program that takes data from a sensor in my raspberry pi and I want the data taken from the raspberry to be shown in a web page, the idea is that it can be updated every time you press a button that its in the web. I'm right now using django to create the web, but I don't know if it is too much complex for what I'm trying to do. Here I have my data extractor code: import bme280 import smbus2 from time import sleep port = 1 address = 0x76 # Adafruit BME280 address. Other BME280s may be different bus = smbus2.SMBus(port) bme280.load_calibration_params(bus,address) bme280_data = bme280.sample(bus,address) humidity = bme280_data.humidity pressure = bme280_data.pressure ambient_temperature = bme280_data.temperature Here I have the django views.py file: from django.shortcuts import render from django.http import HttpResponse import sys sys.path.append('/home/jordi/weather-station/data') from bme280_sensor import humidity, ambient_temperature, pressure from subprocess import run,PIPE # Create your views here. def home(request): return render(request, 'base.html', {'humitat': humidity, 'temperatura': ambient_temperature, 'pressio': pressure}) def index(request): return HttpResponse("EL temps de vilafant") and finally here I have my html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Aqui podras veure el temps de vilafant … -
Python Django API authentication
I am new to Django. I need to use some API to get the .json format data. But the API needs authentication. I have already got the username and password. I see my colleague use Postman to enter the account then he can see the JSON file in intellij. I am in Pycharm, I am wondering is there some code I can use to realize the same function of postman rather than install the postman? What I have: API URL, account username and password Any help is really appreciated, also please let me know which file I should write in the Django, views.py?? Update: thank you for all the help!I am sorry I am not familiar with the postman, I only know my colleague show me how to enter the username and password. I have the API/URL, when I click on it, it will direct me to a page with JSON format data, looks like this {"businessOutcomes":[{"businessOutcomeId":"1234","origin":"JIRA",.....]} I have over 100 this kind of URL/API, I want to get the .json file in pycharm and so I can make them as the df to do the data analysis I want. And my colleague told me that the API has some … -
Cant run gTTS in Django
I am trying to build text to voice app and I had a problem with gTTS. the code I try views.py from django.shortcuts import render from gtts import gTTS from django import forms textfortts = [] class UploadFileForm(forms.Form): tts = forms.CharField(label= " convert text to audio here") def text_to_voice(request): if request.method == "POST" : form = UploadFileForm(request.POST) if form.is_valid(): tts = form.cleaned_data["tts"] textfortts.append(tts) obj = say(language='en-us', text= textfortts) return render(request, "text_to_voice_main.html",{ "form": UploadFileForm(), "lang": "en-us", "text": "text to say", }) text_to_voice_main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text to voice</title> </head> <body> <form action=""> {% csrf_token %} <audio src="{% say lang text %}" controls {% load gTTS %} ></audio> {{form}} <input type="submit"> </form> </body> </html> I need to have a text to voice converter. can i know what is the probelms and how i can fix it? -
Django forms passing request via get_form_kwargs fails to give form access to self.request.user
Goal I need to make the user accessible to a form for validation (i.e., through self.request.user) Approach Taken I use the get_form_kwargs() function in my view to make the request available to my form (as suggested here: Very similar problem). Problem Despite following the steps outlined in the StackOverflow answer linked above, I'm getting the error 'NoneType' object has no attribute 'user' Code views.py views.py class MemberDetailView(LoginRequiredMixin, generic.DetailView): """View class for member profile page""" model = User context_object_name = 'user' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs,) context['form'] = JoinCommunityForm() return context class JoinCommunityFormView(FormView): """View class for join code for users to join communities""" form_class = JoinCommunityForm def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def post(self, request, *args, **kwargs): """posts the request to join community only if user is logged in""" if not request.user.is_authenticated: return HttpResponseForbidden return super().post(request, *args, **kwargs) class MemberDashboardView(View): """View class to bring together the MemberDetailView and the JoinCommunityFormView""" def get(self, request, *args, **kwargs): view = MemberDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = JoinCommunityFormView.as_view() form = JoinCommunityForm(request.POST) if form.is_valid(): forms.py forms.py from communities.models import Community, UserRoleWithinCommunity class JoinCommunityForm(forms.Form): pin = forms.RegexField('^[A-HJ-NP-Z1-9]$', max_length=6, label='', widget=forms.TextInput(attrs={'oninput': 'this.value = this.value.toUpperCase()'})) … -
Getting error : django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username || I'm a beginner trying to save in Djnago
I'm trying to learn django. Just started with a project. It has 2 applications so far. Employee poll I'm trying to do it via CMD. It shows the following issues. Actually I was trying to follow a tutorial for a django project. I checked, there is no UNIQUE keyword used in the code. I even tried deleting and then saving but didn't resolve. Employee :-- **models.py (employee) : ** from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) designation = models.CharField(max_length=20, null=False, blank=False) salary = models.IntegerField(null=True,blank=True) class Meta: ordering = ('-salary',) #minus sign indicates that we need the result in decending order def __str__(self): return "{0} {1}". format(self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def user_is_created(sender, instance, created, **kwargs): if created: Profile.object.create (user=instance.) else: instance.profile.save() Poll :-- **models.py (poll)** from django.db import models from django.contrib.auth.models import User # Create your models here.` `class Question(models.Model): # models.Model is the base model. we just need to extend it. #All the class varibales will be considered as the columns of the table. title = models.TextField(null=True, blank = True) status = models.CharField(default = 'inactive', max_length=10) #if we don't pass … -
use django-filters on a queryset in the backend
Assuming I have a queryset and some filters I got from the front end, can I use the pre-defined FilterSet to filter over the queryset? example: models.py class User(models.Model): name = models.CharField(...) score = models.IntegerField(...) filters.py class UserFilter(django_filters.FilterSet): q = django_filters.CharFilter(method="text_search_filter") score_min = django_filters.NumberFilter(field_name="score", lookup_expr="gte") score_max = django_filters.NumberFilter(field_name="score", lookup_expr="lte") class Meta: model = User fields = {} def text_search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value) views.py class UserView(View): filter_class = UserFilter ... def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} Can I call UserFilter and pass the filter dict? To prevent me applying those filters again, since I already have those defined in the UserFilter Here's what I tried and didn't work: views.py def post(self, request, **kwargs): qs = User.object.all() filters = {"q": "john doe", "score_min": 5, "score_max": 10} filter = UserFilter(request.GET, queryset=qs) filter.is_valid() qs = filter.filter_queryset(qs) # Did not apply the filters -
Flutter Failed to detect image file format using the file header. Image source: encoded image bytes
I have a django server that has media served by nginx, I'm trying to load the media into my flutter app: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ) The static images from the same site load just fine but the network images don't load at all, and give me this error: Failed to detect image file format using the file header. File header was [0x3c 0x21 0x44 0x4f 0x43 0x54 0x59 0x50 0x45 0x20]. Image source: encoded image bytes the static file at images/LOGO%201.png is shown before the page loads the photos, then if the photo is null it shows the same error even though it was working. I think the error is related to the widget that is loading the image Padding( padding: EdgeInsetsDirectional.fromSTEB(16.0, 16.0, 16.0, 16.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { await Navigator.push( context, PageTransition( type: PageTransitionType.fade, child: FlutterFlowExpandedImageView( image: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), fit: BoxFit.contain, ), allowRotation: false, tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), useHeroAnimation: true, ), ), ); }, child: Hero( tag: valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), transitionOnUserGestures: true, child: ClipRRect( borderRadius: BorderRadius.circular(12.0), child: Image.network( valueOrDefault<String>( FFAppState().user.photo, 'https://stpeterlibrary.crabdance.com/static/images/LOGO%201.png', ), width: MediaQuery.of(context).size.width * 1.0, height: 230.0, fit: BoxFit.contain, ), ), ), … -
How to connect my EXPO GO app in IOS to my django server? (both running on wsl)
I'm doing a project using React Native/EXPO and Django. It's not my first time using Django, but it's my first time working on mobile development. I have both of my repositories in WSL, but I can't find a way to consume an API from Django Server when I run the app on my Iphone (after reading the QR Code). I always get the same error:[AxiosError: timeout exceeded]. But if I try to consume this API with the WSL ip in postman, it works perfectly. I know that it's an IP/Port problem, but I don't know how to solve it. I would really appreciate some help here. Django Server Settings.py ALLOWED_HOSTS = ["*"] CORS_ALLOW_ALL_ORIGINS = True React-native code login.tsx const handleLogin = async () => { const networkState = await Network.getNetworkStateAsync(); console.log(networkState); const ipAddress = await Network.getIpAddressAsync(); console.log('Endereço IP:', ipAddress); try { const response = await axios.post('http://172.29.160.117:8000/api/token/', { email: email, password: password, }); const accessToken = response.data.access; // Salve o token de acesso no aplicativo (por exemplo, no AsyncStorage) console.log("Resposta do servidor: " + accessToken); // navigation.navigate('ScreenHome'); } catch (error) { console.log(error); } console.log("Finalizou função"); }; Terminal Output -
while implementing django-defender, Error (if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get')
Implementing a django-defender in web application causing an error while adding a syntax @watch_login in views.py /views.py from defender.decorators import watch_login ...`` @watch_login # error caused due to... def login_user(request): ... return render(request, 'login.html') Error- Internal Server Error: /login Traceback (most recent call last): File "/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'function' object has no attribute 'get' [28/Jun/2023 11:40:18] "GET /login HTTP/1.1" 500 62726 Any solution for it... ThankYou -
xhtml2pdf keep-with-previous.within-page
I'm using the xhtml2pdf library in Django 3.x. I don't know how to make the style work in the template, and still transfer text that is too long to the next page, but only its further part. I'm currently using this code snippet, the rest of the text is moved to the next page, but the styles don't work: <xsl:attribute name="keep-with-previous.within-page"> <tr> <th class="col332"> {{ instance.myvar|linebreaks }} </th> </tr> </xsl:attribute> -
Please I don't understand why my code keeps misbehaving [closed]
The profileimg attribute doesn't seem to work right. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='media/default_img.png') location = models.CharField(max_length=100, blank=True) I've tried using an IF block <div class="col-span-2"> <label for="profile">Profile Image</label> {% if user_profile.profileimg %} <img src="{{ user_profile.profileimg.url }}" width="100" height="100" alt="profile image" /> {% endif %} <input type="file" name="profile_img" class="shadow-none bg-gray-100"> </div> -
Imagine dont display in html page (Django) [closed]
In html file <img src="{% static 'images/welcome-left.png' %}"> this in settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "todoapp/static/"), ] maybe error in paths