Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Imagefield - display current value in ModelForm
My model contains a ImageField called cover_image. cover_image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) I have a working model form that allows users to upload book details including the cover_image from the front end. They also have the option to edit the book via the front end. In the model form the field is declared in the Meta with a FileInput widget and Bootstrap CSS class. 'cover_image': forms.FileInput(attrs={'class': "form-control"}), When edit is clicked, the form loads all the instance data except the cover image. The form can be updated and saved at this point without error. How can I access the current image path? The following both return nothing {{ form.cover_image.url }} {{ form.cover_image.path }} What's the appropriate way to deal with this? Am I expected to pass an instance of the object to the form? -
header for authentication in django and graphql
{ "Authorization": "JWT token" } and in graphQL my query is : query{ allStudents{ name roll } } but stil does't work for me I am expecting to secure my api end point because all will create tokenauth then can access data import graphene from graphene_django.types import DjangoObjectType import graphql_jwt from .models import Student from graphql_jwt.shortcuts import get_token from graphql_jwt.decorators import login_required Define the GraphQL type for the Student model class StudentType(DjangoObjectType): class Meta: model = Student class Query(graphene.ObjectType): # Query to retrieve all students all_students = graphene.List(StudentType) @login_required def resolve_all_students(self, info): return Student.objects.all() # Query to retrieve a single student by ID student = graphene.Field(StudentType, id=graphene.Int()) def resolve_student(self, info, id): try: return Student.objects.get(pk=id) except Student.DoesNotExist: return None class CreateStudent(graphene.Mutation): class Arguments: name = graphene.String() roll = graphene.String() student = graphene.Field(StudentType) def mutate(self, info, name, roll): student = Student(name=name, roll=roll) student.save() return CreateStudent(student=student) class UpdateStudent(graphene.Mutation): class Arguments: id = graphene.Int() name = graphene.String() roll = graphene.String() student = graphene.Field(StudentType) def mutate(self, info, id, name, roll): try: student = Student.objects.get(pk=id) student.name = name student.roll = roll student.save() return UpdateStudent(student=student) except Student.DoesNotExist: return None class DeleteStudent(graphene.Mutation): class Arguments: id = graphene.Int() success = graphene.Boolean() def mutate(self, info, id): try: student = Student.objects.get(pk=id) … -
How I can render a form with multiple choices field in template side?
I want to render a form in template, on of this form field has multiple entries to select(like combobox), I can show form with default django {{ form }} but in custom bootstrap form no idea about it, can anyone help me? this is my form: ` class CreateClubForm(forms.Form): name = forms.CharField(max_length=127) category = forms.ModelChoiceField(queryset=ClubCategories.objects.all()) ` I tried forloop to passing data to dropdown select but it didnt worked -
Load json file in js code from another folder in Django app
I'm developing a Django app, and I'm using intro.js to create a guided tour within one of my views. I currently load the tour steps from a JSON file located in the same folder as my JavaScript files (/static/js/stepsTours.json). function quickStartTurotial() { fetch('/static/js/stepsTours.json') .then(response => response.json()) .then(data => { jsonData = data; let steps = []; // Load steps for the selected tour if (jsonData["quick-start"]) { steps = jsonData["quick-start"]; } // Start the tutorial if (steps.length > 0) { const intro = introJs() .setOptions({ steps: steps, showProgress: true, showBullets: false, disableInteraction: true, }); intro.start(); } else { console.log("No steps found"); } }) .catch(error => console.error('Error loading JSON file:', error)); } However, I'd like to move this JSON file to a different folder, specifically a "config" folder as shown below: My Django app is named "validator". When I change the path in the fetch request to fetch('/config/stepsTours.json'), I encounter the following error: The view in the browser looks like this: How can I correctly configure the path to load the JSON file from the "config" folder? I have to configure some url in my Django app? -
How to do a pull request when using a virtual env?
This might be a silly questions but I am relatively new to programming. I am working on a project- I cloned the project and I am now using a virtual env in Pycharm CE. Once I am done making my code changes, how do I upload it to the main branch and submit a pull request since it is on a virtual env? Do I check out the branch I created in the virtual env? I am completely lost on how to upload my changes to the git after I am done. I ultimately want to make changes in the virtual env and then upload it to the bitbucket repo to request a PR -
error (400) when putting whitenoise in django cpanel whit debug in false
I get a 400 error on the entire page when I put this in the settings.py: STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" If I have the debug set to true nothing happens and everything is fine, but if I change it to false it gives me the error On the only page that this does not happen is on one that I do not have a static load, which only has files that I send from the admin -
django gmail smtp timeout on GAE environment but run ok on local... sending 1 line of text
python3.11 django4.2 on settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'the email' EMAIL_HOST_PASSWORD = 'the password' send email function : from django.core.mail import EmailMessage email = EmailMessage( "subject", "message", settings.EMAIL_HOST_USER , ["the destination"] ) email.contentsubtype = "html" email.send() error log on gae result in timeout *5 upstream prematurely closed connection while reading response header from upstream, client: 169.254.1.1, server: , request: "GET /ajax/ HTTP/1.1", upstream: "http://127.0.0.1:8081/ajax/", host: "test.de.r.appspot.com" requests.post to outside web also result in the same timeout error ex: def urltest(request): import requests url = "https://enmzxk3tnwgrr.x.pipedream.net/" #requestbin url response = requests.post(url, data={'key1': 'value1', 'key2': 'value2'}) response.raise_for_status() return HttpResponse(response.text) i have tried setting nginx timeout to be 600 sec... hence now my code tried to run the code for 10 minutes and timeout -
Weasyprint (Django) save to file or model and not use
is it possible to save the pdf file directly to model without rendering? I just want to database the PDF. I am using Weasyprint although i imagine it would be same for other services like DocRaptor. first just create the pdf. simple. context = {} template = get_template(template_path) html = template.render(context) # Generate the PDF pdf_file = HTML(string=html).write_pdf('test.pdf) then this model. class Reports(models.Model): name = models.CharField() report = models.FileField(upload_to='reports/', null=True, blank=True) and then to save. _pdf = Reports.objects.create( name = 'test', report = pdf_file, ) the name is added put nothing for the pdf. I have a feeling their is some sort of File(BytesIO(pdf_file))) required??? I was able to add the pdf by using this after the save: _pdf.report.save(f'{uuid}.pdf', File(BytesIO(pdf_file))) Why cant I include in the Reports.objects.create? Also when i use this approach the media/reports/pdf will not get deleted when the record gets deleted? is that normal? Thank you -
Django import export to xlsx/csv with custom format for nested Json field
I have the following structures: models.py: class PublicPerson(models.Model): class Meta: verbose_name = "Public Person" verbose_name_plural = "Public People" user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="public_profile", null=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='public_persons/images', null=True) date_of_birth = models.DateField(null=True, blank=True) bio = models.TextField(max_length=10000, blank=True, null=True) short_description = models.CharField(max_length=200, blank=True, null=True) meta_fields = models.JSONField(default=dict, blank=True, null=True) admin.py from import_export.admin import ImportExportModelAdmin from import_export import resources, widgets, fields as f class PublicPersonResource(resources.ModelResource): meta_fields = f.Field(attribute='meta_fields', column_name='meta_fields') def dehydrate_meta_fields(self, public_person): meta_fields = getattr(public_person, 'meta_fields', None) if meta_fields: return meta_fields return {} class PublicPersonAdmin(ImportExportModelAdmin): ... resource_class = PublicPersonResource ... I am usning django-import-export, and trying to get a more user-friendly import/export capability for the JsonField. More specifically, I have some nested Json data, which I would like to be able to import from / export to an excel (and/or csv if possible) file with a very specific format. So far, I have been able to modify only the export to Json by defining the 'dehydrate_meta_fields' method. I am not sure how to approach the other cases. Thus, export to and import from json seems to work just fine with nested data The level of nesting is not expected to change. It will always be a string : string … -
History in the django administrator
I want to disable the record, record and continue editing buttons but allow me to enter the history and view the changes made. Since if I use the has_change_permission method it returns a 403 error when trying to enter the history. What suggestions could you offer me? I tried the has_change_permission method and hoped it would work -
Django-Ajax "Uncaught ReferenceError: FOO is not defined"
I am new to AJAX. A want to make a call to a django view to update item quantity and change number on the page. I have a template ... {% for item in items %} <div id="quantity">{{ item.quantity }}</div> <button onclick="updateQuantity('{% url "invent:quote-increase-item-ajax" %}')">+</button> ... <script> function docReady(fn) { if (document.readyState === "complete" || document.readyState === "interactive") { setTimeout(fn, 1); } else { document.addEventListener("DOMContentLoaded", fn); }; }; docReady(function() { function updateQuantity(url) { fetch(url, { method: "GET", headers: { "X-Requested-With": "XMLHttpRequest", } }) .then(response => response.json()) .then(data => { document.getElementById("quantity").innerHTML = data; }); } }); </script> And a view: def increase_quote_item_ajax(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': item = QuoteItem.objects.get(id=pk) item.quantity += 1 item.save(update_fields=['quantity']) return JsonResponse({'data': item.quantity}) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') But when I click on + button I get Uncaught ReferenceError: updateQuantity is not defined Why isn't my function registering? -
Problem with user permissions and groups in Django
I am trying try to migrate the changes in my model but I get this errors: The field main.CustomUser.groups was declared with a lazy reference to 'custom_auth.group', but app 'custom_auth' isn't installed. The field main.CustomUser.user_permissions was declared with a lazy reference to 'custom_auth.permission', but app 'custom_auth' isn't installed. The field main.CustomUser_groups.group was declared with a lazy reference to 'custom_auth.group', but app 'custom_auth' isn't installed. The field main.CustomUser_user_permissions.permission was declared with a lazy reference to 'custom_auth.permission', but app 'custom_auth' isn't installed. I have custom user model and use custom user creation, registration view instead of Django's basic models and views models.py class CustomUser(AbstractUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=127, unique=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(blank=True, null=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username, email'] objects = CustomUserManager() def get_full_name(self): return self.username def get_short_nane(self): return self.username or self.email.split("@")[0] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' managers.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Users must have an email address')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') … -
Start tutorial after clicked a button that changes view (intro.js)
I have a side bar that is displayed in all views. In that side bar I have a dropdown menu to select some tours that are made with intro.js. There is a quick start, that works perfect. I want to add some options with the names of the views in the tutorial dropdown so that when I click on it I go to the view and start the tutorial. Important, there is an option to start a tutorial when you enter that view, but I don't want that, because if I access redirected from another part it will always start the tutorial, I want it to start only from the tutorial dropdown menu. The problem I have is that my js function switches me to another view but the tutorial starts and stops from one (it shows a fraction of a second). This is what i have. The dropdown menu: <div class="language-selector"> <!-- Dropdown Trigger --> <a id="tutorial" class="dropdown-trigger sidebar-links a" href="#" data-target="tutorialDropdown"> <span style="display: flex; align-items: center;"> <i class="fas fa-question-circle"></i> {% trans "Tutorial" %} <i class="fas fa-caret-down"></i> </span> </a> <!-- Dropdown Structure --> <ul id="tutorialDropdown" class="dropdown-content"> <li> <button class="start-tour-button" onclick="startTourAndRedirect('quick-start', '')"> Quick Start </button> </li> <li> <button class="start-tour-button" onclick="startTourAndRedirect('review-panel', … -
The settings for connecting mysql database in django settings
"django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'lkocalhost'")" When trying to manage.py runserver, The error above keeps popping up that access denied for me to connect mysql to my django project. functionality of local host -
Problems trying to update a record wi a imagefield base64 with django rest framework using drf_extra_fields Base64ImageField
I'm trying to correct a django rest framework api that must save an imagefield with base64 character set image file. I'm doing something wrong but not sure what it is, here my code in details. In settings BASE_DIR = Path(file).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In my models.py firma_pax = models.ImageField(blank=True, upload_to='img') My database is an Oracle Database, CLOB datatype for column firma_pax -- In my serializers.py from drf_extra_fields.fields import Base64ImageField from .models import Scresolipaxservi class ScreSoliPaxServiFirmSerializer(serializers.ModelSerializer): firma_pax = Base64ImageField(max_length=4000, required=False) class Meta: model = Scresolipaxservi fields = ['firma_pax'] def update(self, instance, validated_data): instance.firma_pax = validated_data.get('firma_pax', instance.firma_pax) return Scresolipaxservi.objects.filter(pk=instance.id).update(firma_pax=instance.firma_pax.url) In my Api View from rest_framework.decorators import api_view from clientes.serializers import ScReSoliPaxServiSerializer, ScreSoliPaxServiFirmSerializer from .models import Scresolipaxservi @api_view(['GET','PUT']) def ReservaPax(request,pk=None): #Consulta de la reserva reserva = Scresolipaxservi.objects.get(id=pk) **# Validate if exits** if reserva: ** #Query: ** if request.method == 'GET': reserva_serializer = ScReSoliPaxServiSerializer(reserva) return Response(reserva_serializer.data, status=status.HTTP_200_OK) **#Update: Image ** if request.method == 'PUT': reserva_serializer = ScreSoliPaxServiFirmSerializer(reserva, data=request.data) if reserva_serializer.is_valid(): reserva_serializer.save() return Response(status=status.HTTP_200_OK) return Response(reserva_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'message':'Reserva No Existe'}, status=status.HTTP_400_BAD_REQUEST) This api work fine with the EndPoint that Query the record with GET method, but the update just set a value like "/media/7e94085e-b6f5-4e51-9bfd-ee18ff803bc1.jpg" to the 'firma_pax' field and not … -
Django-Python: You must set settings.ALLOWED_HOSTS if DEBUG is False
I am trying to deploy a Django-Python based web application in Kubernetes. I'm also trying to setup OpenTelemetry so that I could capture the application metrics and visualise it using prometheus and Grafana. However, when I try to instrument the application data to the OpenTelemetry collector, I am getting the below error: Defaulted container "trojanwall-django" out of: trojanwall-django, opentelemetry-auto-instrumentation-python (init). CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. The first line is specifying the name of the Kubernetes pod which is trojanwall-django and also saying that OpenTelemetry auto-instrumentation has started. Besides that, the below command says something about the ALLOWED_HOSTS in the settings.py file. I tried to add ALLOWED_HOSTS = ["*"] and also ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'otel-collector.otel.svc.cluster.local', '0.0.0.0'] where otel-collector.otel.svc.cluster.local is the host name of the OpenTelemetry collector. I tried to set DEBUG = False, yet still the resulting log is the same. Is this a host blocking issue in the settings.py file? Does anyone know how to fix this? -
Django create connected objects simultaneously
I'm new to Django and wanted to ask how can I solve a problem that I have class InventoryId(models.Model): inventory_id = models.AutoField(primary_key=True) class Laptop(models.Model): name = models.CharField(max_length=30) inventory_id = models.ForeignKey(InventoryId, on_delete=models.CASCADE) class Desktop(models.Model): name = models.CharField(max_length=30) inventory_id = models.ForeignKey(InventoryId, on_delete=models.CASCADE) In the example above I would like models Laptop and Desktop to use inventory_id's that are stored in the same table and are incremental to avoid collisions. example: laptop1 --> inventory_id = 1 desktop1 --> inventory_id = 2 laptop2 --> inventory_id = 3 what's the correct way of doing that in django? I found something that recommends using signals to do that. but i was discouraged by documentation that it may be not the best idea -
Djano webapplication
All of a sudden my login via Microsoft AD (Active Directory) is broken. Post logging in, redirect to http://localhost:8000/auth/redirect?code=0.xxx# 1 gives AuthSecurityError at /auth/redirect Failed to match request state with session state Request Method: GET Request URL: http://localhost:8000/auth/redirect?code=0.xxxm&state=xxxx-xxxx-xxxx-xxxx-xxxx&session_state=xxxx-xxxx-xxxx-xxxx-xxxx Django Version: 4.2.5 Exception Type: AuthSecurityError Exception Value: Failed to match request state with session state Exception Location: D:\workspace\django\projectX\env\lib\site-packages\ms_identity_web_init_.py, line 259, in _verify_state Raised during: ms_identity_web.django.msal_views_and_urls.aad_redirect Python Executable: D:\workspace\django\projectX\env\Scripts\python.exe Python Version: 3.10.10 Can someone help me to identify this issue. earlier it was worming fine in production but suddenly giving this error. -
Django Datatables with HTMX Refresh Causes to Lose Functionality
I'm using Django with bootstrap datatables to display my data. I have it mostly working, but it seems that when I do a call back refresh with HTMX, all of the buttons break. I think what is happening is that a new table is being overlaid on top as the buttons still technically work, but it refers to the old data. Raw table Working filter Filter breaking after refresh As you can see, the table looks slightly different and the search status at the bottom says "showing 1 to 1 of 1 entries). So it works, but isn't updating the div anymore to only show applicable results like it used to. This is how i'm refreshing the table <table class='table table-bordered' id="alert-table" hx-get="{% url 'alert_list' %}" hx-trigger="every 15s" hx-swap="innerHTML"> JS of the datatable: <script> $(document).ready(function () { var table = $("#alert-table").DataTable({ autoWidth: true, lengthChange: true, searching: true, ordering: false, columnDefs: [ { targets: 3, render: function ( data, type, row ) { } } ], dom: 'lBrtip', buttons: [ { // COPY extend: 'copy', text: '<i class="bi bi-files"></i>', className: 'btn btn-secondary', titleAttr: 'Copy' }, { // EXCEL extend: 'excel', text: '<i class="bi bi-file-earmark-spreadsheet"></i>', className: 'btn btn-secondary', titleAttr: 'Excel' } ] … -
AWS ECS Fargate - django runserver will be billed 24/7?
I have a django app in a dockerfile, and I deployed it with ECS Fargate. It works well, but I'm am not sure about how pricing works. python manage.py runserver has to be running all the time because it needs to be listening the incoming requests. Does it mean that my fargate is beign used 24/7. and subsequently billed 24/7?. If that is true, what is the correct way to use a monolithic app in a fargate container minimizing costs? Dockerfile FROM python:3.11-alpine RUN mkdir /app WORKDIR /app COPY . . RUN sed -i 's/\r$//g' ./local/entrypoint.sh RUN chmod +x ./local/entrypoint.sh RUN pip install -r ./local/requirements.txt EXPOSE 8000 ENTRYPOINT ["/bin/sh", "./local/entrypoint.sh"] entrypoint.sh #!/bin/sh set -o errexit set -o pipefail set -o nounset echo "------- RUNNING DJANGO COMMANDS -------" python /app/manage.py makemigrations python /app/manage.py migrate python /app/manage.py runserver 0.0.0.0:8000 -
WhatsApp FLows - Could not decrypt the response received from the server
I'm trying to generate the response for the WhatsApp flow using the WhatsApp bussines api with the following code ` def post(self, request, *args, **kwargs): try: dict_data = json.loads(request.body.decode('utf-8')) encrypted_flow_data_b64 = dict_data['encrypted_flow_data'] encrypted_aes_key_b64 = dict_data['encrypted_aes_key'] initial_vector_b64 = dict_data['initial_vector'] flipped_iv = self.flip_iv(initial_vector_b64.encode('utf-8')) encrypted_aes_key = b64decode(encrypted_aes_key_b64) key_private = open('*******.pem', 'rb').read().decode('utf-8') private_key = load_pem_private_key(key_private.encode('utf-8'), password="*************".encode('utf-8')) aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) aes_key_b64 = b64encode(aes_key).decode('utf-8') flow_data = b64decode(encrypted_flow_data_b64) key = b64decode(aes_key_b64) iv = b64decode(initial_vector_b64) encrypted_flow_data_body = flow_data[:-16] encrypted_flow_data_tag = flow_data[-16:] cipher = Cipher(algorithms.AES(key), modes.GCM(iv,encrypted_flow_data_tag)) decryptor = cipher.decryptor() decrypted_data = decryptor.update(encrypted_flow_data_body) + decryptor.finalize() flow_data_request_raw = decrypted_data.decode("utf-8") hello_world_text = "HELLO WORLD" response_data = { "version": "3.0", "screen": "MY_FIRST_SCREEN", "data": { "hello_world_text": hello_world_text } } response_json = json.dumps(response_data) # Obtendo a chave AES após descriptografar encrypted_aes_key fb_aes_key = private_key.decrypt(encrypted_aes_key, OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # Usando a chave AES para criptografar a resposta response_cipher = Cipher(algorithms.AES(fb_aes_key), modes.GCM(iv)) encryptor = response_cipher.encryptor() encrypted_response = ( encryptor.update(response_json.encode("utf-8")) + encryptor.finalize() + encryptor.tag ) encrypted_response_b64 = b64encode(encrypted_response).decode("utf-8") # Construct the final response final_response = { "encrypted_flow_data": encrypted_response_b64, "encrypted_aes_key": encrypted_aes_key_b64, "initial_vector": initial_vector_b64 } return JsonResponse(final_response, status=200) except Exception as e: print(e) return HttpResponse(status=500, content='ok') def flip_iv(self, iv): flipped_bytes = [] for byte in iv: flipped_byte = byte ^ 0xFF flipped_bytes.append(flipped_byte) return bytes(flipped_bytes) ` The entire … -
Problem deploying Dockerised Django app in Heroku and Fly
I've successfully deployed my Django app with Fly.io. But ever since I followed William Vincent's 'Django for Professionals' by trying to Dockerise my project, I have had no luck with updating my production server. In fact, I cannot deploy at all anymore. I ran heroku logs --tail and this is what I got. May you please offer any explanation as to why my 'release command' is failing? heroku logs --tail » Warning: heroku update available from 7.53.0 to 8.6.0. 2023-10-23T12:37:29.030037+00:00 app[api]: Initial release by user 2023-10-23T12:37:29.030037+00:00 app[api]: Release v1 created by user 2023-10-23T12:37:29.160630+00:00 app[api]: Enable Logplex by user 2023-10-23T12:37:29.160630+00:00 app[api]: Release v2 created by user 2023-10-23T12:39:34.797658+00:00 app[api]: Stack changed from heroku-22 to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Upgrade stack to container by user 2023-10-23T12:39:34.813238+00:00 app[api]: Release v3 created by user 2023-10-23T12:49:12.780220+00:00 app[api]: Attach DATABASE (@ref:postgresql-clean-38410) by user 2023-10-23T12:49:12.780220+00:00 app[api]: Running release v4 commands by user 2023-10-23T12:49:12.794484+00:00 app[api]: Release v5 created by user 2023-10-23T12:49:12.794484+00:00 app[api]: @ref:postgresql-clean-38410 completed provisioning, setting DATABASE_URL. by user 2023-10-23T12:53:19.000000+00:00 app[api]: Build started by user 2023-10-23T12:54:06.000000+00:00 app[api]: Build succeeded 2023-10-23T12:54:06.158579+00:00 app[api]: Deploy e59a06da by user 2023-10-23T12:54:06.158579+00:00 app[api]: Running release v6 commands by user 2023-10-23T12:54:06.997250+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry … -
Django sessions for anonymous users get deleted when logging in: how to handle shop baskets?
I'm building a webshop where we want anonymous users to also be able to add things to their basket. I thought I'd be smart and created a Basket model like this: class Basket(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) session = models.ForeignKey(Session, blank=True, null=True, on_delete=models.CASCADE) So for logged in users I'd assign the owner field, and for anonymous users I'd assign the session field. Then when the session expires the basket would also be cleaned up, so I wouldn't end up with a ton of database records for baskets that can never be checked out anymore. So far so good. When an anonymous user logs in, I want to assign the basket to that user. And this is where the complications start to add up because when a user logs in they get a new session key, which is not accessible in the request. While I could create some kind of middleware that keeps track of the previous session key, the biggest problem is that by the time user_logged_in signal is called, the session record has already been deleted from the database and thus my basket has also been deleted. I could do a few things, but none seem very … -
Shipping event created from the dashboard does not call handle_shipping_event (django-oscar)
I'm trying to change the shipping event type from the django oscar admin dashboard and send an email to the customer but it seems like it doesn't call the handle_shipping_event under order/processing.py So far, I created a shipping event type and associated it with a communication event type. Then I inherited order/processing.py and add a send email function, however, it seems the shipping event created from the dashboard doesn't call handle_shipping_event under order/processing.py. I can see the shipping event written to the db. from oscar.apps.order.processing import EventHandler as CoreEventHandler class EventHandler(CoreEventHandler): def handle_shipping_event(self, order, event_type, lines, line_quantities, **kwargs): print('It does not print this') # Example implementation self.validate_shipping_event( order, event_type, lines, line_quantities, **kwargs) # send tracking mail self.send_shipped_email(order) return self.create_shipping_event( order, event_type, lines, line_quantities, **kwargs) django-oscar version: 3.1 Python 3.8.10 Thanks -
Customizing PasswordResetView using Django auth views
Well, I need to create a customized view based on Django's PasswordReset view, but for when the User is already logged in. I originally used PasswordChangeView for this, but it automatically redirect the user to PasswordChangeForm, where the user inputs the older password and the new password and then save it. But, for a matter of security, I was requested to, when the user clicks the link to change their password, it automatically send a Password Reset email to they, showing the 'password_reset_done.html' and sending the password reset password. (Don't know if I'm making myself really clear I'm currently studying and this is my first time using stack overflow. I already a custom_password_change view that uses PasswordResetView. `def custom_password_change(request): if request.method == "POST": user = request.user if user.is_authenticated: # Call the Django built-in view for password reset return PasswordResetView.as_view( template_name='registration/password_change_form.html', email_template_name='registration/password_change_email.html', success_url='/password_change/done/' )(request) return render(request, "registration/password_change_form.html")` But it stills demands user to input their email on the PasswordResetForm and then sends the email. I need it to send the email when the user clicks "change password" instead and returning the 'password_reset_done.html' template.