Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'str' object has no attribute 'as_widget'. How to fix?
Error: Internal Server Error: /posts/v3ttel/44/ Traceback (most recent call last): File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\posts\views.py", line 140, in post_view return render(request, 'post.html', context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 175, in render return self._render(context) ^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\test\utils.py", line 112, in instrumented_test_render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader_tags.py", line 157, in render return compiled_parent._render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\test\utils.py", line 112, in instrumented_test_render return self.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in return SafeString("".join([node.render_annotated(context) for node in self])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) ^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\loader_tags.py", line 63, in render result = block.nodelist.render(context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "B:\TEST2_2\ya_02_zad_free\venv\Lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in … -
Django - How can I pass the model_id of my loop as a parameter in the form url? The form is handled in a seperate view
In my django project, I have a forloop that goes through ModelA. During this loop, I have a form. This form is handled in a seperate view and requires the ModelA_id as a parameter. For some reason, ModelA_id, which fine in the loop, is not passed to the form view and the ModelA_id used by the form is the first one picked it. I have used this logic a few times and I cannot see what I am doing different. question: how can I pass the model_id of in my loop as a parameter in the form url? models class ModelA(models.Model): ModelA_field = models.ForeignKey(FK, null = True, blank=True, on_delete=models.CASCADE, related_name="relatednames") def __str__(self): return str(self.title) + ' - ' + str(self.venue) + ' - ' +str(self.points) views def template_function(request, venue_id): i = ModelA.objects.filter( venue=venue_id).order_by('points') return render(request, 'main/template_function.html', {'i': i}) def form_function(request, venue_id, modela_id): print(f' modela_id: {modela_id}') # prints the first modela_id, but not the one it relates to in the template loop. return redirect(url, {}) url path('form_function/<venue_id>/<modela_id>', views.form_function, name="form-function"), template {% for rewardprogram in reward_program %} <div class="row"> <div class="col"> <p class="small-text">{{ modela.id }}</p> #id is correct </div> </div> <div class="row"> <div class="col"> <a class="" onclick="openForm()"> id:{{modela.id}} #id is correct </a> … -
How can I connect an up-to-date django server to a MySQL 5.1 database? (upgrading the MySQL version is not an option)
I have a MySQL-server that is part of a software system that is not developed by me. Thus it is not possible for me to upgrade that MySQL-server to a newer version, because it might break the software system's ability to interact with that database. I need read access to that database on my public facing django application. The django version is the latest LTS (4.2). Django's documentation lists two database API driver options for MySQL: mysqlclient MySQL Connector/Python Both of these in their most current versions do not support access to MySQL 5.1 servers Option 1. still works on Debian 11, with some overwritten methods in a subclass, but not on Debian 12. How do I ensure that my django application still works, when I upgrade its production server from Debian 11 to 12? I have tried using MySQL Connector/Python with the option use_pure, but it gives me the error django.db.utils.DatabaseError: (1193, "1193 (HY000): Unknown system variable 'default_storage_engine'", 'HY000'). I am unsure what I would have to patch, when subclassing that, in order to restore compatibility with MySQL 5.1. -
I cant use Django ORM at external script
i have a Django app and i try to run an external script (for input some data with ORM) which is located at root of my app folder. I take that error: from InventoryFrontBackEnd.inventory.models import Component import pandas as pd import os import sys #this is a test: print(Component.objects.all()) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. (I use a venv which is located at another folder) As i read i have to set the: DJANGO_SETTINGS_MODULE enviroment variable, i tried many things but dont work. The folder structure is given here: the script i run is the Import_D_components.py thank you! -
Why Django Signals async post-save is locking other async ORM calls?
I have a Django 5 application that use websockets using channels, and I'm trying to switch to AsyncConsumers to take advantage of asyncronous execution for I/O or external API tasks. I already wrote a demo project and everything it's working fine, however in my application I use Django signals, and I have a long I/O task to be performed in the post_save of MyModel, previously implemented using threads: from asyncio import sleep @receiver(dj_models.signals.post_save, sender=MyModel) async def auto_process_on_change(sender, instance, **kwargs): logger.log("Starting Long Save task"); await sleep(30) logger.log("Starting Long Save task"); The websocket consumer that is serving the request is similar to the following: from channels.generic import websocket class AsyncGenericConsumer(websocket.AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() ... async def receive_json(self, message): ... user = await User.objects.aget(id=...) # Authentication code # .... # (eventually) Create MyModel, depending on request type mod = await my_models.MyModel.objects.acreate(...) Now, the problem is as follow: When Alice's request is still performing a post_save operation (i.e., awaiting the long task contained in it) and a Bob user opens up a the browser and makes a request to the same consumer, the computation gets stuck to user = await User.objects.aget(id=...) until the long task (e.g., the asyncio.sleep(30)) terminates for Alice. The … -
Django null value in column with default violates not-null constraint
I have this current table, with state as Jsonfield with default a empty dict class Channel(models.Model): agent = models.ForeignKey(Agent, on_delete=models.SET_NULL, null=True, blank=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) type = models.CharField(choices=ChannelType.choices, max_length=64, default=ChannelType.WHATSAPP) settings = models.JSONField(blank=True, default=dict) state = models.JSONField(blank=True, default=dict) disabled = ArrayField(models.CharField(), blank=True, default=list) But when i try to create a Channel Object Channel.objects.create(type=ChannelType.WHATSAPP, settings=serializer.validated_data, organization=user_utils.get_user_organization(request.user)) Django raises this error django.db.utils.IntegrityError: null value in column "state" of relation "core_channel" violates not-null constraint Failing row contains (4, WHATSAPP, {"session_id": "611a09fd-ccfd-4683-ba92-4717c9688193"},null, {}, null, 1). Why? default should not make that the default value a {}? why is working with the field disabled? -
When I try to install Pillow, I encounter this error
(env) PS D:\programing\source\Backend\Django> python -m pip install Pillow Collecting Pillow Using cached pillow-10.3.0.tar.gz (46.6 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [216 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-311 creating build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\Image.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageChops.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageCms.py -> build\lib.mingw_x86_64-cpython-311\PIL copying src\PIL\ImageColor.py -> build\lib.mingw_x86_64-cpython-311\PIL copying … -
Django prefetch_related filtered by an attribute of the outer query
I am working on a simple Django application that stores and shows programmes for events: There is a table of Participants, which are also used in Django's auth system. Each Participant can have multiple Affiliations with a number of Institutes. Each Affiliation has a (nullable) start and end timestamp. Each Slot represents a single activity (talk, meal, workshop) and has a start timestamp. Multiple people can be assigned to each slot. class Participant(models.Model): name = models.CharField(max_length=256) institutes = models.ManyToManyField('Institute', through='Affiliation', related_name='people') class Institute(models.Model): name = models.CharField(max_length=256) class Affiliation(models.Model): person = models.ForeignKey('Participant', on_delete=models.CASCADE, related_name='affiliation') institute = models.ForeignKey('Institute', on_delete=models.CASCADE, related_name='affiliation') start = models.DateField(null=True, blank=True) end = models.DateField(null=True, blank=True) class Slot(models.Model): title = models.CharField(blank=True, max_length=256) abstract = models.TextField(blank=True, max_length=4096) start = models.DateTimeField(null=True, blank=True) person = models.ManyToManyField('Participant', related_name='slots', blank=True) I would like to show a single Slot and the people responsible, along with their Affiliations, but only those that are valid at the beginning of that event (where start is null or earlier than Slot.start, and end is null or later than Slot.start). I have written a QuerySet method for that, and by itself it is working correctly, as I could verify with manage.py shell: class ParticipantQuerySet(models.QuerySet): def with_current_affiliations(self, date: datetime.date = None): date … -
Django redirect not working if called inside a function
I would like to put a redirect command inside of a function and then call this function in a Django view. Can anyone give me a hint why my code below does not redirect? This redirection works: views.py from django.shortcuts import redirect from django.http import HttpResponse def my_view(request): return redirect("https://stackoverflow.com") return HttpResponse("<p>redirection did not work</p>") This redirection does not work: views.py from django.shortcuts import redirect from django.http import HttpResponse # define subfunction def test(): return redirect("https://stackoverflow.com") def my_view(request): test() return HttpResponse("<p>redirection did not work</p>") -
Hosting Django from a directory
My directory structure is like so: C:\htdocs # web root |_ django-container +- django-project | +- core # startproject | |_ myapp1 # startapp +- public +- static # STATIC_ROOT, collectstatic | +- css | +- images | |_ js |_ media # MEDIA_ROOT Nginx config: http { # ... upstream wsgi-server { server 127.0.0.1:8080; } server { # ... location /myloc/ { proxy_pass http://wsgi-server/; } location /myloc/public/media/ { alias C:/htdocs/django-container/public/media/; autoindex off; } location /myloc/public/static/ { alias C:/htdocs/django-container/public/static/; autoindex off; } } } I run a waitress WSGI server as a service on port 8000 that runs core.wsgi.application. My settings.MEDIA_URL and settings.STATIC_URL are public/media/ and public/static/ respectively. When I do redirects in my app, or create urls in templates, it doesn't have the myloc segment, because of which all links fail. Even the public/static/ and public/media/ links. For the last 2, I could add the segment to settings.STATIC_URL and settings.MEDIA_URL, but I wanted a common way to add the myloc segment at all places, preferably automatically if possible. -
How to assign content type automatically when serving a file in Django
I have a system where certain permissions are needed to view files, and I'm using django-guardian for the permissions. I want the file to be displayed in a new tab if the browser supports it, otherwise just download the file. I can check the filename and manually set content type depending on the file extension, but there are too many and it seems like a stupid thing to do. Here is the view: @login_required def ViewDocument(request, document_id): document = Document.objects.get(id=document_id) path = document.file.name # Check user permissions to view file if not request.user.has_perm('home.view_document', document): return HttpResponseForbidden("You don't have permission to access this media.") # Construct the full path to the media file media_path = os.path.join(settings.MEDIA_ROOT, path) # can i do this more easily? if path.endswith('.pdf'): temp_content_type = "application/pdf" elif path.endswith('.png'): temp_content_type = "image/png" elif path.endswith('.jpg'): temp_content_type = "image/jpeg" else: temp_content_type = "application/octet-stream" # Serve the file with open(media_path, 'rb') as file: response = HttpResponse(file.read(), content_type=temp_content_type) return response -
Django Bokeh App does not render the chart, console says: bokeh-3.4.0.min.js:616 [bokeh 3.4.0] could not set initial ranges
I'm trying to render a Bokeh chart on my html template view but unsuccessfully, any help would be appreciated. Thanks in advance. This is the view class: from bokeh.plotting import figure, show from bokeh.embed import components from bokeh.models import ColumnDataSource from .models import FinancialInstrument, HistoricalData class Offline(View): '''Responsable to indicate the way to the Offline Analysis ''' form_class=HugeStatForm template_name='charts/offline.html' api_key = 'I0T0AM1MH4Y4X0DC' def get(self, request): user=request.user historical_me=FinancialInstrument.objects.all() form = self.form_class(historical_me=historical_me) #instruments = FinancialInstrument.objects.all() retrive=HistoricalData.objects.all() get_symbol=retrive.filter(instrument__symbol="BTUSD") x_values = [key.date for key in get_symbol] y_values = [float(key.opening_price) for key in get_symbol] source = ColumnDataSource(data=dict(dater=x_values,pricer=y_values)) plot = figure(title="New title", x_axis_label="Date", y_axis_label="Max Price", x_axis_type="datetime") plot.line(x='dater',y='pricer', source=source,line_width=1) script, div = components(plot) if user.is_authenticated: return render(request,self.template_name, {'form':form,'script':script, 'div':div,}) return redirect('home') This is a peace of my template view: <script src="https://cdn.bokeh.org/bokeh/release/bokeh-3.4.0.min.js" crossorigin="anonymous"></script> <div class="col mx-0 px-0 d-flex justify-content-start"> <!-- Bottom Section Content --> <!-- Chart goes here --> {{ script | safe }} {{ div | safe }} </div> When i load the page, it appears a blank chart and the console from the browser in the Developer mode says "bokeh-3.4.0.min.js:616 [bokeh 3.4.0] could not set initial ranges" Here i have the list of the installed apps on my virtual environment: Package Version ------------------------- ----------- aiohttp 3.9.3 … -
Is Django bulk_update slower than update?
I am trying to create and update around 30k data rows at once in the database from Django. This is taking me around 2-5 mins because all these rows have 90+ fields to be updated too, thus to reduce some time in this storage procedure I was planning to use bulk_update and bulk_create in the Django. But after the implementation I realised that this is taking a lot more time than my older process (upsert - update_or_create). Even if I remove the time taken for determining whether to create or insert (which I now realise can be directly done using an arguement in the bulk_create) it is still taking 4 times more time then my query. Based on the name of the function, I was thinking that this should be a better approach for bulk create and update of these many rows and save me sometime, but I don't know why this isn't working like that. Can anyone explain why is this happening and if there is a way to make it faster? The only reason I can come up with till now is that I have too many fields to be updated in a row, i.e., apart from 4-5 … -
Model does not exist, the problem is I get my objects from my urls.py file
I have an error in my Django 5.0 project which is Model does not exist, the cause is I get the objects from the urls.py file. Precisely I do a for loop to build my urls from my objects Model, so i get an error which is the Model does not exist, The question is : How to run migrations before the build of the urls I try to build my urls from my data's Model and i except an error which is the Model doesn't exist -
Weasyprint doesn't load the local image Django
view: from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status import base64 from django.template.loader import render_to_string from weasyprint import HTML from io import BytesIO from django.http import HttpResponse # Create your views here. import json from apps.pdf.models import Personas from django.conf import settings from apps.pdf.base_urls import PDF_BASE_FOLDER , PDF_CERT_SERV_FOLDER import os @api_view(["GET", "POST"]) def test(request): # Renderizar la plantilla HTML con los datos # datos = json.loads(request.body) datos = {"name": "pedro"} context={ "STATIC_URL" : settings.STATIC_URL } query = Personas.objects.filter(name=datos.get("name")).values()[0] html_template = render_to_string("pdfs_templates/Certificado.html", context) pdf_file = BytesIO() HTML(string=html_template).write_pdf(pdf_file) nombre_archivo = "example.pdf" ruta_carpeta_servidor = PDF_CERT_SERV_FOLDER ruta_completa_archivo = os.path.join(ruta_carpeta_servidor, nombre_archivo) with open(ruta_completa_archivo, "wb") as f: f.write(pdf_file.getvalue()) response = HttpResponse(content_type="application/pdf") # response["Content-Disposition"] = f'attachment; filename="{nombre_archivo}"' response.write(pdf_file.getvalue()) return response def vie(request): context={ "STATIC_URL" : settings.STATIC_URL } return render(request, 'pdfs_templates/Certificado.html', context) template : {% load static %} {% block content %} <!DOCTYPE html> <html> <head> <style type="text/css" media="all"> @page { /* size: A4 portrait; /* can use also 'landscape' for orientation */ margin: 100px 1cm 150px 1cm; @top-left { content: element(header); } @bottom-left { content: element(footer); } } header { position: running(header); /*height: 100px;*/ } table, th, td { border:1px solid black; } footer { position: running(footer); /*height: 150px;*/ … -
JWT token sent as cookie is being deleted when refreshing page (Next.js 14)
I'm using Django REST Framework as backend to handle login, if the user is verified, the service send a cookie with a JWT token. The code below works, I can see the cookie set in my browser. Login view: class Login(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = Usuariso.objects.filter(email=email).first() ... key = os.getenv('JWT_KEY') token = jwt.encode(payload, key, algorithm='HS256') res = Response() res.set_cookie( key='jwt', value=token, httponly=True, secure=True, max_age=60*60*24, expires=60*60*24, path='/') res.data = { 'jwt': token } return res The problem occurs when I refresh the page, CSRF and JWT cookies are deleted. The code below fetch login API: app/components/loginForm.js const login = async () => { try { const response = await fetch('http://127.0.0.1:8000/api/user/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, key: 'Access-Control-Allow-Origin', credentials: 'include', body: JSON.stringify({ email: email, password: password }) }); if (response.ok) { console.log("it works"); } } catch (error) { console.log(error) } }; I have read about JWT, when setting httOnly to true, cookie can not be accessible from javascript, so I think I should not need an third party library to commit this What I have tried: Setting httpOnlny and secure = False Commenting out httpOnly and secure Setting domain as 'localhost' -
NoReverseMatch: Reverse for '...' not found. '...' is not a valid view function or pattern name - for path include name
I have this setup: # Django Project: core/urls.py def redirect_index(request): return redirect(reverse('account'), permanent=False) urlpatterns = [ path('', redirect_index, name='index'), path('account/', include('identity.urls'), name='account'), ] # Django App: identity/urls.py app_name = 'identity' def redirect_index(request): return redirect(reverse('identity:login'), permanent=False) def view_login(request): context = {"test_context": 'This is a test context'} return render(request, "common/base.html", context) urlpatterns = [ path('', redirect_index, name='index'), path('login', view_login, name='login'), ] When I visit http://localhost:8000/, I get this error: NoReverseMatch at / Reverse for 'account' not found. 'account' is not a valid view function or pattern name. What I want is this: If user goes to /, it should redirect to /account/, and from there redirect to /account/login. I know there are 2 redirects, but I'd like to have them separate so that I can set each one separately. But I get the above error. It looks like when there is an include, the name cannot be reversed. Of course, when I use reverse('identity:index') or reverse('identity:login') instead of reverse('account') in core/urls.py, it works. Is there no way I can do it the way I described earlier? -
Angular 14 / NGIX Server | White screen on Firefox and Chrome
Recently we are having issues with the deployment of our Angular App. Its angular 14, running in a ngix server. The issue arises when we do BGD (Blue green deployment, we have two prod environments, we switch between them to have 0 downtime, while one is serving the other is building the new version), our Angular app freezes on a white screen, just loading what is in the index.html (cookies popup, Analytics, etc). Sometimes works on Firefox but not on Chrome, or viceversa. Now it only fails on Firefox and I got some extra insights, looks like when tries to load runtime.js the HTTP call fails with error: NS_ERROR_CORRUPTED_CONTENT. I checked the file exists and it does, and the content is complete, seems correct. The MIME types are correct to for js files. The weirdest thing is that if switch the boolean sourceMap on the angular.json, it works again. Its not that it works being true, it just works again when we switch from true to false or viceversa. I'm running out of ideas or thing to check, and I can't find info related with this. If anyone had a similar issue or haves any insight or different thing to … -
Django, Allegro API, error with get data form endpoint
i have problems with getting data after authorization, i can get main categories, but when a want get orders from account its display it: {'errors': [{'code': 'EMPTY_USER_ID', 'message': 'User name from JWT cannot be empty', 'details': None, 'path': '/order/events', 'userMessage': 'User name from JWT cannot be empty', 'metadata': {}}]} CLIENT_ID = settings.ALLEGRO_CLIENT_ID CLIENT_SECRET = settings.ALLEGRO_CLIENT_SECRET TOKEN_URL = "https://allegro.pl.allegrosandbox.pl/auth/oauth/token" def get_access_token(request): try: data = {'grant_type': 'client_credentials'} access_token_response = requests.post(TOKEN_URL, data=data, verify=True, allow_redirects=False, auth=(CLIENT_ID, CLIENT_SECRET)) access_token_response.raise_for_status() tokens = json.loads(access_token_response.text) access_token = tokens['access_token'] `request.session['access_token'] = access_token` `return access_token` `except requests.exceptions.HTTPError as err`: `raise SystemExit(err)` def offers(request): url = 'https://api.allegro.pl.allegrosandbox.pl/order/events' headers = { 'Authorization': f'Bearer {get_access_token(request)}', 'Accept': 'application/vnd.allegro.public.v1+json', } response = requests.get(url,headers=headers).json() print(response) return render(request, 'index.html',{'events':response}) I trying asking chat, and i doing it with allegro api tutorials, but i dont know what is happened. I just want to get orders from my account and display. -
Unable to connect to cloud datastore from local legacy project based on python2.7 and django 1.4
I have a django==1.4 project (python==2.7) that I wanted to run and make some changes. I am unable to connect to cloud datastore from my local codebase. Right now, when I run the project using dev_appserver.py like: dev_appserver.py PROJECT_NAME --enable_console It runs three different servers: API server on localhost:RANDOM_PORT Module default at localhost:8080 Admin server at localhost:8000 Now I visit http://localhost:8000/console and browse interative console and then run some python script like importing User model and fetching if there is anything there or not. And there isn't, why? Because it connects to the local AppIdentityServiceStub. And obviously there isn't any data unless I create some. Now I want to connect this codebase to my cloud datastore and I have tried different implementations that are already on stackoverflow and other platforms. One of them is setting environment variable GOOGLE_APPLICATION_CREDENTIALS to a keyfile.json that service account provides. I have the keyfile.json and I have set it to env variable but still I get connected to local datastore which has no data. Let me know if I am running this project wrong? or is there any other way to connect to cloud datastore from my local? Also, one more thing, when I do … -
Django django.db.utils.IntegrityError .................error
django.db.utils.IntegrityError: The row in table 'students_student' with primary key '2' has an invalid foreign key: students_student.Classes_id contains a value '0' that does not have a corresponding value in students_classes.id. (venv) PS C:\Student Management System> making fields default but still facing error -
Django default User Login: Can't login even with correct password
I am using Django's default User and authentication to enable login functionality. My username and passwords are correct; I've reviewed them, and I can login to the admin. But it won't work in my app, through the login page. There must be something basic I'm overlooking but I"ve been over my code several times. Views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import View from django.contrib import messages from django.urls import reverse_lazy from .forms import EntryForm, CreateUserForm, LoginForm from .models import Entry from django.views.generic.edit import DeleteView, FormView # Authentication models and functions from django.contrib.auth.models import auth from django.contrib.auth import authenticate, login, logout #this is to ensure that even after you have your login setup, a user can't just manually type in the URL from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class EntryView(LoginRequiredMixin, View): login_url = 'login' def get(self, request): logged_in_user = request.user.id entries = Entry.objects.filter(trader_id=logged_in_user).order_by("entered_date") form = EntryForm() return render(request, "entries.html", {"form":form, "entries":entries}) def post(self, request): form = EntryForm(request.POST, request.FILES) #must add request.FILES for uploads print(request.FILES) if form.is_valid(): form.save() messages.success(request, "Entry created!") return redirect("/") else: messages.error(request, "Please correct the errors below.") return render(request, "entries.html", {"form":form}) def SingleEntryView(request, pk): entry = Entry.objects.get(pk=pk) if … -
"Patients model in Django does not recognize the 'user' attribute when registering a new user."
I am practicing login, registration and logout in Django. I want to create a patient through registration and have the registration information saved in Patients, which is in my models.py. When I perform a registration I get the following error in terminal: raise self.RelatedObjectDoesNotExist( pacientes.models.Pacientes.user.RelatedObjectDoesNotExist: Pacientes has no user. Here is the code of my exercise. models.py from django.db import models from django.contrib.auth.models import User class Pacientes(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=50) fecha_nacimiento = models.DateField() genero = models.CharField(max_length=1) address = models.CharField(max_length=50) email = models.EmailField() phone = models.CharField(max_length=50) picture_profile = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username + ' ' + self.user.last_name forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import Pacientes class PacientesForm(forms.ModelForm): password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) class Meta: model = Pacientes fields = ['nombre', 'apellido', 'fecha_nacimiento', 'genero', 'address', 'email', 'phone', 'picture_profile', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Las contraseñas no coinciden") return password2 def save(self, commit=True): paciente = super().save(commit=False) user = paciente.user user.set_password(self.cleaned_data["password1"]) # Guarda la contraseña en el objeto User if commit: user.save() paciente.save() return paciente class EmailAuthenticationForm(AuthenticationForm): … -
how to correctly derive a function book.user_max2() to make xlsx export fast
When exporting .xlsx, the book.user_max2() function increases the load and clogs up the RAM. If you just take book.price from the model, there is no such problem. But I need the price to change when unloaded, so I wrote a user_max2() function in the Products model. Everything is a problem in the user_max2() function. Without it, everything is unloaded quickly and there are no memory leaks. Please help, maybe someone has already encountered this. model Products class Product(models.Model): STATUS_CHOICES = ( (0, 'Не опубликовано'), (1, 'Опубликовано'), ) STATUS_NEW = ( (0, 'Нет'), (1, 'Да'), ) id_p = models.BigIntegerField(primary_key=True, db_index=True, unique=True, verbose_name='ID продукта') artikul = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Артикул') brend = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Бренд для поиска') analog = models.CharField(max_length=500, blank=True, verbose_name='Аналоги артикула') category = models.ManyToManyField(Category, blank=True, related_name='categ', verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') product_sklad = models.ForeignKey(Sklad, on_delete=models.CASCADE, default=1, verbose_name='ID поставщика') product_time = models.IntegerField(default=0, verbose_name='Срок доставки ( дн.)') name = models.CharField(max_length=200, blank=True, verbose_name='Название продукции') image_a = models.ImageField(upload_to=get_path_upload_image_a, verbose_name='Фото A', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") image_b = models.ImageField(upload_to=get_path_upload_image_b, verbose_name='Фото B', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") image_c = models.ImageField(upload_to=get_path_upload_image_c, verbose_name='Фото С', blank=True, null=True, help_text="Фото продукта автоматитчески сохраняется под ID продукта") description = models.TextField(blank=True, verbose_name='Описание') price … -
How to force nginx to see my static files?
I'm trying to output a project to NGINX. I ask good people to help. I've been suffering for 2 days. First I ran: python manage.py collectstatic The static folder has been created! Here is the path to my manage.py: /home/ubuntu/ubuntu/project/Pet/Django/bewise/src Here are my static settings in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] Here are my NGINX settings: `server { listen 80; server_name 192.168.16.153; location /static/ { root /home/ubuntu/ubuntu/project/Pet/Django/bewise/src/static/; } location / { proxy_pass http://192.168.16.153:8000; } } And here is my gunicorn configuration:command = '/home/ubuntu/ubuntu/project/venvs/bewise/bin/gunicorn' pythonpath = '/home/ubuntu/ubuntu/project/Pet/Django/bewise/src' bind = '192.168.16.153:8000' workers = 3` I run gunicorn: gunicorn -c config.py config.wsgi Everything works fine, but I don't receive static files. When I try to go to 192.168.16.153/static/img/home.png I get err403. And I don't receive css files either.