Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Profile is not registered with auto created User via signals
I have a django application where the following model named Employee plays the role of the user Profile that is in relation with the User from the auth module: class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) phone = models.IntegerField(blank=True) is_chef_de_project = models.BooleanField( default=False ) is_chef_de_produit = models.BooleanField( default=False ) is_ghr = models.BooleanField( default=False ) account = models.OneToOneField( User, on_delete=models.CASCADE, null=True ) i want to automatically to create a User during registration of an Employee so i created the following signals.py file: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth import hashers from django.dispatch import receiver from .models import Employee def generate_password(): import secrets import string alphabet = string.ascii_letters + string.digits return ''.join(secrets.choice(alphabet) for i in range(10)) @receiver(post_save, sender=Employee) def create_user(sender, instance, created, **kwargs): breakpoint() if created: uname = instance.first_name[0].lower() + instance.last_name.lower() passd = generate_password() User.objects.create(employee=instance, username=uname, password=passd) print("generated credentials:" + uname + ":" + passd) @receiver(post_save, sender=Employee) def save_user(sender, instance, **kwargs): breakpoint() instance.account.save() but after registration i find the account attribute in the created Employee instance null: null account any hints what's going on ? i was expecting the User instance created to be referenced by the registered Employee -
inconsistent django session key
I am implementing a cart function which gets session key since it doesnt have user login. But every time I add something to the cart, it gets different session key. When I check the django admin panel, it adds data to the cart but I get an empty array whenever I call my Get Cart api. @api_view(['POST']) def add_to_cart(request): try: session_key = request.session.session_key if not session_key: request.session.create() session_key = request.session.session_key product_id = request.data.get('product') quantity = request.data.get('quantity') size_id = request.data.get('size') if not all([product_id, quantity, size_id]): return Response({'error': 'Missing required fields'}, status=status.HTTP_400_BAD_REQUEST) cart_item = Cart.objects.create( product_id=product_id, quantity=quantity, size_id=size_id, session_key=session_key ) serializer = CartSerializer(cart_item) return Response(serializer.data, status=status.HTTP_201_CREATED) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['GET']) def get_cart_items(request): session_key = request.session.session_key cart_items = Cart.objects.filter(session_key=session_key) serializer = CartSerializer(cart_items, many=True) return Response(serializer.data) -
Huey Connection Refused
I keep getting "connection failed: connection to the server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections" when running my task in production?" This does not happen in local development. @db_periodic_task(crontab(minute='*/1'), queue='application_expiration') def parcel_expiration_task(): # current date and time current_timestamp = timezone.localtime(timezone.now()) # get all event get_events = Event.objects.order_by('-creation_time').filter( time_ends__lt=current_timestamp ) if get_events.exists(): .... I have tried to add a db. connection in the supervisor: [program: application] command='...' user='...' autostart=true autorestart=true redirect_stderr = true stdout_logfile = '....' environment=DATABASE_URL="postgresql://username: password@localhost:5432/db_name" I have also edited the pg_hba.conf file and added the following entry at the end of the file: host all all 0.0.0.0/0 md5 host all all ::/0 md5 -
Will a dynamic list of choices in a Django model evaluate when the model is migrated or when a user tries to select a choice for a model?
Code Let's say I have the following model: class Course(models.Model): title = models.CharField(max_length=48) YEAR_CHOICES = [(r, r) for r in range( datetime.date.today().year-1, datetime.date.today().year+2 ) ] year = models.IntegerField(_('year'), choices=YEAR_CHOICES) Question Will the datetime.date.today() statements be evaluated right when the model is migrated, or will they be evaluated whenever the user accesses a form to set the year value for the Course model? In other words, is my YEAR_CHOICES code above frozen to when I migrated my model or will it dynamically update as the years go by? -
django generic UpdateView with some custom fields
My question is quite close to this one UpdateView with additionnals fields, so I used the info, but I still lack some details to complete the process So, I have a simple toy model : class TxtPlus(models.Model): txt = models.CharField(max_length=140) def __str__(self): return f'TxtPlus<{self.id},{self.txt}>' def get_absolute_url(self): return reverse("tplus_detail", kwargs={"pk": self.pk}) When editing an instance, I want to add a field, and thus according to the answer above, I define a custom Model class TxtPlusForm(ModelForm): info = CharField(widget=Textarea(attrs={"rows":"2"})) class Meta: model = TxtPlus fields = ["txt", ] the using the UpdateView is easy class TxtPlusUpdateView(UpdateView): model = TxtPlus template_name = "adding_to_model_forms/tplus_update.html" form_class = TxtPlusForm But, what I wish to do is roughly: def infos_associated_to_object(object): return f'there is more about object:{object.pk}' def test_edit(request,pk): object = TxtPlus.objects.get(id=pk) info = infos_associated_to_object(object) if request.method == 'GET': form = TxtPlusForm(instance=object,initial={'info': info}) up_log = None if request.method == 'POST': form = TxtPlusForm(request.POST,instance=object) up_log = f"change '{info}' to '{form.data['info']}'" form.save() #... add here form.data['info'] saving return render( request, "adding_to_model_forms/tplus_edit.html", { "object" : object, "form" : form, "info" : info, "up_log" : up_log } ) (of course, infos_associated_to_object, is here a toy version..) In particular, my problem with UpdateView, is on : first the part initial={'info': info} (where info … -
Images not showing, using Django admin, cloudinary and deploying to Heroku
I'm trying to add images to my project (in the albums) using django admin, cloudinary and then it is being deployed to Heroku. I can't seem to make it work, sat with a tutor for 2 hours yesterday and we made it work and now it's just gone again. Header image is just black and the image for the album is coming back as a 404 even if I checked that the image is where it should be. When I upload on Django admin the image file does not go to the workspace and stays in cloudinary so I think it is because of that. Anyone who has any other ideas? enter image description here Where it's black shoul be a static image and further down where the image icon is should be an image loaded from Django admin panel. -
getting an error saying assessment must be an instance
in my assessment section model i have defined an foreign key like this: assessment_id = models.ForeignKey(to=Assessment, on_delete=models.CASCADE, related_name='section_assessment_mapping', null=False, blank=False, help_text="The assessment associated with this section.") this points to assessment model's id whichis primary key. in assessment section serializer i have defined the assessment id like this: assessment_id = serializers.UUIDField(required=True) this is the create method of the serializer: def create(self, validated_data): print('validdata',validated_data) print(validated_data.get('assessment_id')) section_obj = AssessmentSection.objects.create_with_defaults(**validated_data) return section_obj and this is the create api for assessment section: def create(self, request, *args, **kwargs): try: serializer = AssessmentSectionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) except ValidationError as e: service_logger.error(str(e)) return Response({'error': True, 'message': e.args[0]}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: service_logger.error(str(e)) raise StandardizedException(error_status=True, error_obj=e, status_code=status.HTTP_400_BAD_REQUEST) now when i hit the API with payload containing assessment_id having some valid assessment id which is present in the DB it gives this error: Cannot assign \"UUID('7025deca-afb8-4ad3-93b8-6035599bcf6e')\": \"AssessmentSection.assessment_id\" must be a \"Assessment\" instance." } I have tried several approaches but they are not working. I just need to store the assessment id in the table with section info. Thank you in advance. tried using source=assesment.id in the serializer field but didnt work. -
Pure SQL from postgres to django
We have a pure SQL in postgres that groups the instance visits registered in that table grouped by country, what I need is to pass this pure query to django queryset to get the same result Here is the pure SQL query: SELECT country, SUM(difference) AS total_difference FROM ( SELECT id, entry_or_exit_datetime AS entry_time, LEAD(entry_or_exit_datetime) OVER (ORDER BY entry_or_exit_datetime) AS exit_time, EXTRACT(EPOCH FROM (LEAD(entry_or_exit_datetime) OVER (ORDER BY entry_or_exit_datetime) - entry_or_exit_datetime)) AS difference, country FROM ( SELECT id, entry_or_exit_datetime, country, LAG(is_joining) OVER (ORDER BY entry_or_exit_datetime) AS prev_is_joining FROM public.access_sectionslog WHERE date(entry_or_exit_datetime) >= '2024-05-17' AND date(entry_or_exit_datetime) <= '2024-05-23' AND section_name = 'landing-page' AND country IN ('VE', 'CO') ) AS subquery ) AS subquery_with_difference GROUP BY country; This is the model in django: class SectionsLog(BaseModel): class SectionNameChoice(models.TextChoices): GROUPS = "section-groups", _("Groups") FEED = "section-feed", _("Feed") NEWS = "section-news", _("News") LANDING_PAGE = "landing-page", _("Landing Page") EXTERNALS_SHARING = "external-sharing", _("External Sharing") LIVESCORE = "section-livescore", _("Livescore") SALES_PAGE = "sales-page", _("Sales page") ON_BOARDING = "onboarding", _("On boarding") user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True, related_name="sections_log", ) section_name = models.CharField( max_length=20, choices=SectionNameChoice.choices, null=True, blank=True, ) is_joining = models.BooleanField( blank=True, null=True, help_text="Enter the Section(True)/Leave the Section(False)", ) is_anonymous = models.BooleanField( default=False, blank=True, null=True, help_text="Is True to anybody who enter … -
Django migration keeps generating old model attributes (is it cached somewhere?)
I am new to Django but have some experience with MVC web development. I am encountered with a weird problem, hopefully, it is only weird to me, not all folks. After doing some changes (changing attribute's names) in models project_name/models.py. I ran: python manage.py makemigrations to migrate the DB with new changes. But it showed that "No changes." So I decided to do a fresh re-migrate DB :( Delete DB and recreate empty DB Delete migrations/ folder and recreate folder with __init__.py Re-run makemigrations OK. Now the weird thing happens. No matter how I change in models.py, the migrations/0001_initial.py file always keep generate old attribute. # models.py class Task(models.Model): STATUS_CHOICES = [ ('PENDING', 'Pending'), ('PROCESSING', 'Processing'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed'), ] pdf_file = models.FileField(upload_to='pdfs/') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='PENDING') #Previously `preview_url` preview_img = models.ImageField(blank=True, null=True, upload_to='previews/') #Previously `thumbnail_url` thumbnail_img = models.ImageField(blank=True, null=True, upload_to='thumbnails/') error_message = models.TextField(blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"Task: {self.id} - {self.status}: {self.pdf_file.name}" # migrations/0001_initial.py ... operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pdf_file', models.FileField(upload_to='uploads/')), ('status', models.CharField(choices=[('PENDING', 'Pending'), ('PROCESSING', 'Processing'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed')], default='PENDING', max_length=10)), ('preview_url', models.URLField(blank=True, null=True)), # WEIRD ('thumbnail_url', models.URLField(blank=True, null=True)), # WEIRD ('error_message', models.TextField(blank=True, … -
How to add a button for interaction in the Django admin panel
I want to create a button in test model page in Admin panel that, when clicked, will automatically add a new question based on the test the user selected. Is this possible? Is there a way to implement this functionality using the existing tools and technology in the Admin panel? If not, what steps or modifications would be required to achieve this feature? -
How to do bulk upload in particular key value for json field in django
I need to update a particular key value in json field and other field should not be impacted or override. variant_to_update = master_models.Variant.objects.filter( trust_markers__contains = {trust_marker_type: True}) model_to_update = master_models.Model.objects.filter( trust_markers__contains = {trust_marker_type: True}) for variant in variant_to_update: variant.trust_markers[trust_marker_type] = False variant.save(update_fields = ['trust_markers']) for model in model_to_update: model.trust_markers[trust_marker_type] = False model.save(update_fields = ['trust_markers']) I find this solution of appending it to a list and then do bulk upload master_models.Variant.objects.bulk_update(variant_updates, ['trust_markers']) -
Adding Custom Description Input Field Next to File Names in FilePond
I'm using FilePond for file uploads in my Django project. I want to add a custom description input field next to each file name in the list of files to be uploaded. When I use the following HTML, the description fields appear but they are outside the FilePond design. This way, I can upload files, but I can't add a custom input field next to the file name within the FilePond structure. Here is the HTML I'm using: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FilePond File Upload</title> <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"> <link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <style> .filepond--item { width: calc(100% - 0.5em); } </style> </head> <body> <div class="container"> <form action="{% url 'upload_file' %}" method="POST" enctype="multipart/form-data" id="file-upload-form"> {% csrf_token %} <input type="file" class="filepond" name="file"> <div id="description-container"></div> <button type="button" id="upload-button" class="btn btn-primary mt-3">Upload</button> </form> </div> <script src="https://unpkg.com/filepond-plugin-file-validate-size/dist/filepond-plugin-file-validate-size.js"></script> <script src="https://unpkg.com/filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.js"></script> <script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.js"></script> <script src="https://unpkg.com/filepond/dist/filepond.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script> // Register the plugins FilePond.registerPlugin( FilePondPluginFileValidateSize, FilePondPluginFileValidateType, ); // Set FilePond global options FilePond.setOptions({ maxFileSize: '100KB', credits: false, allowMultiple: true, maxFiles: 50, server: { process: { url: '{% url "upload_file" %}', method: 'POST', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, onload: (response) => { console.log('File uploaded … -
Airflow UI doesn't show dags
I'm using airflow for an enough time, but this is the first time, when I don't know why it's not working correctly. I have my django app and airflow as a scheduler (both on docker), it's working good when i was using one postgres db for both of them, but when i tried to split them and make on two different clusters i faced a problem: airflow see my dags, but doesn't show in ui: it sees that there is 311 dags, but also says 'no result' I checked me connection with db: psql -h host -U username -p port -d dbname, for both (django db and airflow db) it's working on, also in airflow db in table dag there is 311 elements as it has to be (i tried to delete them and do 'airflow db init') Logs is clear for 3 services of airflow in docker: worker, scheduler and webserver (of course after all my changes i did 'docker-compose restart worker scheduler webserver' or 'down --volumes' and 'up --build -d') I correctly set db's parameters in Dockerfile, docker-compose.yml and airflow.cfg When i try in some airflow's container run 'airflow dags list' it shows them correctly I thought problem … -
django : CSRF verification failed. Request aborted. (tutorial2)
There is an error when logging in from the django admin page. I'm working on tutorial02, and I've tried various things and found related documents, so there's no change. Please understand that the image is not uploaded, so it will be uploaded as a text message Thanks in advance. ============================================================================= [cmd window] System check identified no issues (0 silenced). May 24, 2024 - 14:14:40 Django version 5.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [24/May/2024 14:14:46] "GET /admin/ HTTP/1.1" 302 0 [24/May/2024 14:14:46] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 4158 Forbidden (CSRF cookie not set.): /admin/login/ [24/May/2024 14:14:49] "POST /admin/login/?next=/admin/ HTTP/1.1" 403 2869 ============================================================================= [web browser] Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. Help Reason given for failure: CSRF cookie not set. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’sCSRF mechanism has … -
I want to create a json file from my Django sqlite3 database as a backup rather than displaying it on a webpage
I am able to get the data from my sqlite3 database and project it in a webpage in Json but am having trouble replicating that when wanting to create a file. I am new to python, Django and working with databases. I have been looking around and tried several pieces of code, but the information I could find pertained to what I have already achieved, which is displaying the data on a webpage. This is how I currently use my views.py file to display the data on a webpage. import json from django.utils import timezone from django.db.models import Q from django.http import JsonResponse from django.views import View from chpapi.models import BlockedList class IPListJsonView(View): def get(self, request): json_response = { "version": "", "description": "", "objects": [ { "name": "", "id": "", "description": "", "ranges": ["2.2.2.2"], }, ], } group_map = {} for ip in BlockedList.objects.filter( Q(end_date__isnull=True) | Q(end_date__gte=timezone.now()) ).select_related("group"): group_id = str(ip.group.id) if group_id not in group_map: group_map[group_id] = { "name": ip.group.name, "id": ip.group.group_id, "description": ip.group.description, "ranges": [], } group_map[group_id]["ranges"].append(ip.address) json_response["objects"] = list(group_map.values()) return JsonResponse(json_response) The above code does produce what I want, I have to leave out some objects, but basically the four columns I am grabbing from my models.py … -
Creating foreign fields in Django right after the object creation
I am getting a JSON input with the fields description and choices for a Question model. The Choice model also has a foreign key field pointing to Question with a related name of choices. However, in the JSON, the Choice will come without the question_id field, in order to be assigned after the creation of the Question I am getting all kind of errors when trying to create a Question and then assigning all incoming to it. Searched a lot for the error Direct assignment to the forward side and didn't found anything that solves my problem I can't change the related name and the JSON input fields, if this was a possibility I'd have already done it class CreateQuestionSerializer(serializers.ModelSerializer): description = serializers.CharField(max_length=1024, allow_blank=False, required=True) choices = CreateChoiceSerializer(many=True, required=True) def create(self, validated_data): choices = validated_data.pop('choices') question = Question.objects.create(**validated_data) choices_serializer = CreateChoiceSerializer(data=choices, many=True, context={'question': question}) if choices_serializer.is_valid(): choices_serializer.save() return question -
How to Encrypt the Password before sending it to backend in django
I am making user authentication django project and for frontend I am just using templates and not any frontend library like react so when user submits the sign up form i want to encrypt the password before sending it to backend how can i do it? I tried of using fetch to encrypt the password so when the form is submitted i am encrypting the password and sending it backend using fetch // adding on_submit event listener to the form document.addEventListener("DOMContentLoaded", function () { console.log(' in submit event') const form = document.querySelector("#forgot_password_form"); form.addEventListener("submit", async function (event) { // preventing form from reloading when submitted event.preventDefault(); // fetching user entered details ie., email,password,confirm password const email = document.getElementById("forgot_password_mail").value; console.log('user details', email) error_in_signin_data = false document.getElementById('email_required_msg').style.display='none' document.getElementById('valid_email_required_msg').style.display='none' document.getElementById("forgot_password_mail").style.borderColor = '#e3e3e3'; // check if email is empty or not if (email.length == 0) { // error_fields.push("signin_email") // error_message_array.push("Email") document.getElementById('email_required_msg').style.display='block' document.getElementById("forgot_password_mail").style.borderColor = 'red'; error_in_signin_data = true; } else{ // Check if the email is in correct format if (!email.match(emailRegex)) { // error_fields.push("signin_email") // error_message_array.push("Valid Email") document.getElementById('valid_email_required_msg').style.display='block' document.getElementById("forgot_password_mail").style.borderColor = 'red'; error_in_signin_data = true; } } // fetching CSRF token from form const csrfToken = form.querySelector("[name='csrfmiddlewaretoken']").value; const formData = new FormData(); formData.append("email", email); // console log … -
Singleton Pulsar Producer Using Python Client Not Working
I'm struggling with creating a singleton Apache Pulsar producer in a Django app. I have a Django application that needs to produce hundreds of messages every second. Instead of creating a new producer every time, I want to reuse the same producer that was created the first time. The problem I'm facing is that the producer gets successfully created, I can see the logs. but if I try to send a message using the producer, it gets stuck without any error. Below is my code for creating the producer. import logging import os import threading import pulsar from sastaticketpk.settings.config import PULSAR_ENABLED logger = logging.getLogger(__name__) PULSAR_ENV = os.environ.get("PULSAR_CONTAINER") class PulsarClient: __producer = None __lock = threading.Lock() # A lock to ensure thread-safe initialization of the singleton producer def __init__(self): """ Virtually private constructor. """ raise RuntimeError("Call get_producer() instead") @classmethod def initialize_producer(cls): if PULSAR_ENABLED and PULSAR_ENV: logger.info("Creating pulsar producer") client = pulsar.Client( "pulsar://k8s-tooling-pulsarpr-7.elb.ap-southeast-1.amazonaws.com:6650" ) # Create the producer try: cls.__producer = client.create_producer( "persistent://public/default/gaf", send_timeout_millis=1000 ) logger.info("Producer created successfully") except pulsar._pulsar.TopicNotFound as e: logger.error(f"Error creating producer: {e}") except Exception as e: logger.error(f"Error creating producer: {e}") @classmethod def get_producer(cls): logger.info(f"Producer value {cls.__producer}") if cls.__producer is None: with cls.__lock: if cls.__producer is None: cls.initialize_producer() logger.info(f"Is … -
Converting Django PWA to iOS and Android Apps Using Capacitor: Handling Django Templates and Offline Support
I have a web application developed using Django and Django PWA. The application uses Django templates to render HTML with context passed from the views. I am considering converting this web application into a mobile application for both iOS and Android using Capacitor. I have a few questions and concerns about this process: Django Templates and Context: Will the context passed to Django templates work correctly when the application is converted to a mobile app using Capacitor? Are there any specific considerations or adjustments needed to ensure smooth operation? Offline Support: Given that Django templates are rendered server-side, will the application encounter issues when accessed offline in the mobile app? How can I implement offline support effectively in this scenario? Best Practices for Conversion: What are the best practices for converting a Django web application to mobile apps for both Android and iOS? Are there any recommended tools or frameworks that could facilitate this process more efficiently? I would appreciate any insights, experiences, or suggestions from those who have undertaken similar conversions. Thank you in advance for your help! -
How to read external config file in Django and have it available everywhere
I want to define an external config file, for example, in Yaml. How can I read it in once at initialization and then have it available everywhere, without having to re-read the file each time? For example, if I put this in apps.py def ready(self) config = yaml.safe_load(open("config.yml")) How do I reference this from, for example, views.py -
stripe dashbaord showing 400 even though stripe listen cli is retuning 200
As a sanity check, I am immediately returning a status 200. as you can see in the screenshots below, my cli says everything is okay and returning 200 back to stripe, but in my dashboard I am getting status 400s. This is for a django app. does the dashboard response even matter if the cli is picking it up? We have constructed the even @method_decorator(csrf_exempt, name='dispatch') class StripeWebhook(APIView): def post(self, request, *args, **kwargs): return HttpResponse({status: "success"},status=200) #all the code below is our normal logic. we are just trying to do a sanity test #to see if the dashboard picks up the 200 print('received payment. in webhook') stripe.api_key = settings.STRIPE_TEST_SECRET event = None payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] try: event = stripe.Webhook.construct_event( payload, sig_header, 'settings.WEBHOOK_SECRET' ) except ValueError as e: print("aaa") print(e) return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: print('bbb') print(e) return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': print('payment success') elif event['type'] == 'payment_intent.payment_failed': # Handle failed payment intent event print('payment failed') return HttpResponse('something went wrong', status=400) return HttpResponse({'status': 'success'}) (https://i.sstatic.net/BUgJsnzu.png) (https://i.sstatic.net/itoTZ4bj.png) we tried immediately returning a 200 status to stripe. -
Empty values in JSON dict from javascript
I have JavaScript at Front: var mix = { methods: { signIn () { const username = document.querySelector('#login').value const password = document.querySelector('#password').value var dict = {} dict['username']=username this.postData('/api/sign-in/', JSON.stringify(dict)) .then(({ data, status }) => { location.assign(`/`) }) .catch(() => { alert('Error auth') }) } }, mounted() { }, data() { return {} } } And when I send POST query like {"username": "aa"} I receive dict like: {'{"username":"aa"}': ''} As you can see value is empty, all data set as key. What can be a problem? Thx. -
Saving HTML with Jinja (or Django Template Language) into the Sqlite model
I am trying to save the HTML with Jinja output into an Sqlite model. I want the rendered output (without curly braces {} or %% signs) to be saved into the model. I have no idea on how to format it. Tried the render_to_string function but it does not seem an appropriate solution. Thank you. -
Website shows Server error 500. Suspect it's SSL releated
My site was working just fine, and then it stopped for reasons I don’t know. I get a Server Error 500. I believe it’s related to SSL, because in most browsers I get that error, but in Brave it goes to http and works fine (as http). My site log lists no errors, and I don’t see any in the apache logs either. The relevant settings.py: secure proxy SSL header and secure cookies SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True session expire at browser close SESSION_EXPIRE_AT_BROWSER_CLOSE = True wsgi scheme os.environ['wsgi.url_scheme'] = 'https' and wsgi.py: os.environ['HTTPS'] = "on" and in my apache 000-default_ssl.conf: SSL section SSLEngine on SSLCertificateFile /etc/ssl/certs/mysite.crt SSLCertificateKeyFile /etc/ssl/private/mysite.key and lastly, in the 000-default.conf I have: RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] I could really use some help. Thanks. I checked the site log, and the apache logs. There's no evidence of errors. I only suspect it's an SSL problem because it oddly works in a Brave browser and not others. -
Separate database for each user in web app
I’m creating a web app. I need to give each user a separate database. I know this isn’t seen as a great practice and a single database is usually used in these scenarios, but for this project this is the way it needs to be. I have a current working solution in Django. However, my current solution means that if the customer was ever to delete one of their users and add a new one I would have to rebuild and deploy the project to them. Also to clarify, the web app will be deployed on a per customer basis on their own server so this isn’t really a multitenant solution I’m looking for. Would this be easier in flask? This is my first time using django or web apps in general so I'm still learning a lot. My current solution in Django involves routing requests to a specific database based on the user’s credentials. The database names are still defined in settings.py before deployment and named after the some form of user credentials like an id or email. But like I mentioned, there are lots of cases where I would have to reconfigure the databases in settings.py and redeploy …