Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run Django migrations in Visual Studio 2022
I have created a Django project in my Visual Studio solution. The db.sqlite3 file was also created. There are a few classes in models.py. class Question(models.Model): q_id = models.IntegerField() text = models.CharField(max_length=500) class Option(): option_num = models.IntegerField() text = models.CharField(max_length=1000) When I right click on the project, there are these options - Make Migrations, Migrate & Create Superuser. When I execute Django Make Migrations, in the terminal it says Executing manage.py makemigrations, but nothing happens. Then I execute Migrate. It says, a command is already running. The __init__.py isn't updated. I also tried, executing this command in VS Terminal, but there is no response. python manage.py makemigrations -
How can I implement jaeger with django project to view traces in grafana?
I have a legacy django project in python 2 where I needed to implement jaeger in it. How can I do that, Can anyone guide me on the same? python 2.7 django-1.11.1 -
Is it possible to use python-social-auth's EmailAuth with drf-social-oauth2 for registration
I have a facebook authentication in my project, and I've set up some pipelines. So It would be nice for non-social email registration to also utilize these pipelines. I tried adding EmailAuth to the authentication backends list, but I don't know what view to use now for registratioin. So, is it possible (or reasonable) to use EmailAuth with drf-social-oauth2 for non-social registration, and if so, how do I do it? -
Django Search Query Vulnerable to XSS - How to Prevent It?
I am working on a Django search functionality, and I noticed that when I pass JavaScript code in the URL query parameter, it executes on the page. Problem When I enter the following URL in my browser: http://127.0.0.1:8000/search/?q=%3Cscript%3Ealert(%27Hacked!%27)%3C/script%3E it shows an alert box with "Hacked!". I suspect my site is vulnerable to Reflected XSS. views.py from django.shortcuts import render def search_view(request): q = request.GET.get("q", "") # Get query parameter return render(request, "search.html", {"q": q}) search.html <h1>Search Results for: {{ q }}</h1> <!-- Displays the search query --> If I enter <script>alert('Hacked!')</script> in the search box, the JavaScript executes on the page instead of being displayed as plain text. What I Need Help With Why is this happening? What is the correct way to prevent XSS in this case? Does Django provide a built-in security mechanism for this? I appreciate any guidance on securing my search functionality. -
here i have some models and its linked with other models. each model is dependant with other model but now its not depending
[enter image description here][1][here before selecting sub department i have to select main department and sub comes under main department.][2] [1]: https://i.sstatic.net/3GSQjtkl.png [2]: https://i.sstatic.net/Tp9kg2uJ.png these are the models. models.py class Department(models.Model): department_name = models.CharField(max_length=255) # ✅ Correct field company_name = models.ForeignKey(CompanyName, on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=[('active', 'Active'), ('inactive', 'Inactive')]) def __str__(self): return self.department_name class SubDepartment(models.Model): sub_department_name=models.CharField(max_length=100,null=False,blank=False) department_name=models.ForeignKey(Department,on_delete=models.CASCADE) company_name=models.ForeignKey(CompanyName,on_delete=models.CASCADE) status=models.CharField(max_length=20, choices=[('active','Active'),('inactive','Inactive')]) def __str__(self): should i make any change in forms or views? forms.py class DepartmentForm(forms.ModelForm): class Meta: model = Department fields = ['department_name', 'company_name', 'status'] class SubDepartmentForm(forms.ModelForm): class Meta: model = SubDepartment fields = ['sub_department_name', 'department_name', 'company_name', 'status'] i already give one to many into the fields but its not working as dependant. here when i select the department the corresponding sub department only should come but without selecting the dept the sub department is listing. **views.py** def dept_view(request): if request.method == "POST": form = DepartmentForm(request.POST) if form.is_valid(): form.save() return redirect('department-view') else: form = DepartmentForm() depts = Department.objects.all() return render(request, "dept.html", {"form": form, "depts": depts}) # @login_required(login_url="signin") def delete_department(request, department_id): if request.method == "POST": department = get_object_or_404(Department, id=department_id) department.delete() return JsonResponse({"success": True}) return JsonResponse({"success": False}) def sub_dept_view(request): if request.method == "POST": form = SubDepartmentForm(request.POST) if form.is_valid(): form.save() return redirect("sub-department") # Redirect … -
fieldsets(legend) in modelform django
I have a model form forms.py class (forms.ModelForm): class Meta: model = InfoPersonal fields = [ 'name', 'phone_number' ] models.py class InfoPersonal(models.Model): name = models.CharField(_('Имя'), max_length=50) phone_number = PhoneNumberField( _('Номер телефона'), max_length=20, unique=True, blank=True, null=True, personal_info-add.html <form enctype="multipart/form-data" action="{% url 'workflows:personal_info-add' user.pk %}" method="post"> {% include "_parts/form.html" with form=form %} </form> I want to get the result as shown in the picture( email -> name passord -> tel). Is it possible to add a tag in the module itself? I need the <name> and <phone_number> fields to be inside the tag <fieldset> (legend)enter image description here how to implement it help please!!! -
Google Calendar API on EC2 (AWS) - webbrowser.Error: could not locate runnable browser
I am developing a Django App where a user can access his Google Calendar using this script credentials = None token = os.path.join(folder, "token.pickle") if os.path.exists(token): with open(token, 'rb') as tk: credentials = pickle.load(tk) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: credentials = os.path.join(folder, "credentials.json") flow = InstalledAppFlow.from_client_secrets_file( credentials, scopes=['openid', 'https://www.googleapis.com/auth/calendar'] ) flow.authorization_url( # Recommended, enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Optional, enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', # # Optional, if your application knows which user is trying to authenticate, it can use this # # parameter to provide a hint to the Google Authentication Server. login_hint=useremail, # Optional, set prompt to 'consent' will prompt the user for consent prompt='consent') flow.run_local_server() credentials = flow.credentials with open(token, 'wb') as tk: pickle.dump(credentials, tk) service = build('calendar', 'v3', credentials = credentials) When I test it on my local machine everything works fine. However, I run it on a EC2 instance on AWS I get this error: flow.run_local_server() File "/home/ubuntu/webapp/lib/python3.12/site-packages/google_auth_oauthlib/flow.py", line 447, in run_local_server webbrowser.get(browser).open(auth_url, new=1, autoraise=True) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/webbrowser.py", line 66, in get … -
Can I create foreign key with specific value match from parent table
Suppose Parent table is CREATE TABLE departments ( department_id SERIAL PRIMARY KEY, department_name VARCHAR(100) NOT NULL, department_type VARCHAR(100) NOT NULL ); Suppose department_type is Type A and Type B. I want to create Table Employee with foreign key department_id, but department type is always Type A. CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, employee_name VARCHAR(100) NOT NULL, department_id INT, CONSTRAINT fk_department FOREIGN KEY (department_id, **department_type ='Type A'** ) REFERENCES departments(department_id) ); Is it Possible? -
How can i edit external link format converter rule in wagtail cms draftail editor
When someone adds an external link in Wagtail CMS, they should have the option to choose whether to make the link 'nofollow' or 'noreferrer.' To achieve this, I have inherited the existing link form, and the code is provided here class CustomExternalLinkChooserForm(ExternalLinkChooserForm): rel = forms.ChoiceField( choices=[ ("noreferrer", "Noreferrer"), ("nofollow", "Nofollow"), ], required=False, label=_("Rel Attribute"), ) i have also inherited view class CustomExternalLinkView(ExternalLinkView): form_class = CustomExternalLinkChooserForm i registered this in wagtail hooks so admin take this override core view @hooks.register("register_admin_urls") def register_custom_external_link_view(): return [ path( "admin/choose-external-link/", CustomExternalLinkView.as_view(), name="wagtailadmin_choose_page_external_link", ) ] By using the above, it gives me an output like this, but the main issue is that when the Draftail rich text editor saves the link in the database, it does not add the rel attribute in href url. How can I solve this issue? -
Issue with Loading Static Files and Images from Amazon S3 in Django
# Amazon S3 Configuration AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # STORAGES Configuration STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", # Directory for media files "file_overwrite": False, # Prevent overwriting files }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", # Directory for static files }, }, } # Configuration during development STATIC_URL = "/static/" # URL for static files STATICFILES_DIRS = [BASE_DIR / "config" / "static"] # Directories for static files STATIC_ROOT = BASE_DIR / "staticfiles" # Root directory for collected static files MEDIA_URL = "/media/" # URL for media files MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Root directory for media files # S3 Configuration for production if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" The documentation used was from https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html. I am using Django version 5.1.4. Although the static files (CSS, JS, assets) are being collected correctly, when accessing the application, the layout is broken, with no styles applied or images loaded from the static/assets folder. Could anyone help me resolve this issue and ensure that the static files are loaded correctly in the production environment? The … -
Update datetime field in bulk save json object Python Django
i am very bad in django fw. I make simple django resp api. I want to save multiple json object to db. If one of objects is already exist in db(has the same uniq fields) i need just to update filed with datetime. My Model Like: class CheckPort(models.Model): created = models.DateTimeField(auto_now_add=True) ip = models.CharField(max_length=15, blank= False) port = models.PositiveIntegerField(default=0) type = models.CharField(max_length=5 ,default='tcp') class Meta: ordering = ['created'] unique_together = ('ip', 'port','type') My view: @api_view(['GET', 'POST']) def port_list(request): if request.method == 'GET': offers = CheckPort.objects.all() serializer = OfferSerializer(offers, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = OfferSerializer(data=request.data,many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how to validate this? -
Problema no Carregamento de Arquivos Estáticos e Imagens com Amazon S3 em Django [closed]
# Configuração do Amazon S3 AWS_ACCESS_KEY_ID = "<your-access-key-id>" AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>" AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_S3_QUERYSTRING_AUTH = False # Configuração de STORAGES STORAGES = { "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "location": "media", "file_overwrite": False, }, }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3StaticStorage", "OPTIONS": { "location": "static", }, }, } # Configuração durante o desenvolvimento STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "config" / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Configuração S3 para produção if not DEBUG: STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" A documentação utilizada foi a do https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html Embora os arquivos estáticos (CSS, JS, assets) sejam coletados corretamente, ao acessar a aplicação, o layout está quebrado, sem a aplicação dos estilos ou o carregamento das imagens da pasta static/assets. Alguém poderia me ajudar a resolver esse problema e garantir que os arquivos estáticos sejam carregados corretamente no ambiente de produção? -
Django Datetime TypeError: fromisoformat: argument must be str
I am having this error while using django. I try to get the date that one transaction happened but i get this error: File "/usr/local/lib/python3.11/site-packages/django/utils/dateparse.py", line 114, in parse_datetime return datetime.datetime.fromisoformat(value) TypeError: fromisoformat: argument must be str code error code snippet ` next_due_date = models.DateField(blank=True, null=True) # The next date when this transaction will be added transaction_date = models.DateTimeField(default=timezone.now) def __str__(self): # Check if transaction_date is set and valid before formatting if self.transaction_date: return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" else: return f"{self.transaction_type} of {self.amount}"` Here is also my already made transactions.: [{"id":1,"user":1,"transaction_type":"expense","amount":"33.00","description":"Cosmote","category":null,"recurrence":null,"next_due_date":null,"transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":2,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":3,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":4,"user":1,"transaction_type":"income","amount":"450.00","description":"Rent","category":"Rent","recurrence":"biweekly","next_due_date":"2025-03-01","transaction_date":"2025-03-26T14:03:02.430961Z"}] i can't understand the reason why is this happening i tried using directly timezone.now(): transaction_date = timezone.now() instead of transaction_date = models.DateTimeField(default=timezone.now) but it got the same error, also tries using if else statement to check in the str function but nothing last i tried using this format in str return f"{self.transaction_type} of {self.amount} on {self.transaction_date}" return f"{self.transaction_type} of {self.amount} on {self.transaction_date.strftime('%B %d, %Y')}" any idea why may this is happening? -
Labels in the form is not showing
This is my model.py file code: class Review(models.Model): VOTE_TYPE = ( ('up','Up Vote'), ('down','Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null = True) project = models.ForeignKey(Project, on_delete=models.CASCADE) # when the model is deleted, all the reviews should also be deleted. body = models.TextField(null = True, blank=True) value = models.CharField(max_length=200, choices = VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) This is my forms.py code: class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value': 'Place your vote', 'body': 'Add a comment with your code' } def __init__(self,*args,**kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class':'input'}) This my html file code <form class="form" action="{% url 'project' project.id %}" method="POST"> {% for field in form %} <!-- 'form' IS THE WORLD WE PUT IN CONTEXT DICT IN PROJECTS VIEW. --> <div class="form__field"> <label for="formInput#textarea">{{ field.label }}</label> {{ field }} </div> {% endfor %} <input class="btn btn--sub btn--lg" type="submit" value="Add Review" /> </form> The label's CSS is here: .comments { margin-top: 4rem; padding-top: 3rem; border-top: 2px solid var(--color-light); } .comments .form label { position: absolute; margin: -9999px; } .commentList { margin: 3rem 0; } .comment { display: flex; gap: 2rem; } the problem is that Labels … -
Tailwind CSS does not generate CSS for all classes
I'm new to Tailwind CSS and I'm looking to include it in my Django/FastAPI project. I'm using Tailwind version 4.0.17. The problem I'm having is that Tailwind doesn't recognize the HTML tags I have in my template files... I run the following command : npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css This generates a CSS file for me, but it doesn't have all the classes in it... On the other hand, when I test with this command : npx tailwindcss --content ./templates/test_endpoint.html --dry-run > output.css This time, all the CSS classes of the HTML template are present in the output file, but not the others (those of the other HTML templates). Here is the code for the tailwind.config.js file: /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./templates/**/*.html", "./templates/*.html", "templates/main/index.html", "templates/base.html", "./**/templates/**/*.html", "./static/**/*.css", "./fastapi_app/**/*.html", "./main/**/*.html" ], theme: { extend: {}, }, plugins: [], } I've tried reinstalling Tailwind several times, changing the paths, trying other commands, and the result is always the same. If you have any ideas on how to solve this problem, that would be great! Thanks -
Most efficient way to write a "Many to Occasional" field in Django
So I read that ManytoMany fields in Django were slower than ForeignKey lookups (as they make use of a helper table). I am creating an application that allows performers to catalog their acts. Each act they have in their catalog can have multiple images. However, I also want to specify one "Hero Image" of the Act which will be used for preview when they search through their catalog. each act can have many images, but only one of those could be a header image. I came up with three options but I want to hear what the hive has to think. ManytoManyField from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ManyToManyField(Act) image = models.ImageField(upload_to='images/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Two Foreign Keys from django.db import models from django.contrib.auth.models import User # Create your models here. class Act(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() hero_image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Image(models.Model): act = models.ForeignKey(Act, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') … -
not able to connect to postgresql server
So I'm having trouble connecting my postgresql db server. I'm relatively new to Ubuntu, this is a brand new computer. My db name, username and password are all correct as per my Django settings. I hope I don't have to edit my pg_hba.conf file. I had similar issues regarding this with Fedora, but I didn't think I would have this problem with Ubuntu. I did in fact create a new database via the linux terminal. I'm also in my virtual environment. I even tried opening the psql shell and got more warnings. Here is the complete trackeback error after running python manage.py makemigrations and psql. FYI the name for my Ubuntu system is corey-james show_sunset_warning() /home/corey-james/Arborhub/arborhubenv/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "cortec" warnings.warn( No changes detected (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ psql psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: role "corey-james" does not exist (arborhubenv) corey-james@corey-james-HP-Laptop-14-dq0xxx:~/Arborhub/MyProject$ -
Django + HTMX: how to have a CreateView that looks up information via HTMX and updates the form dynamically?
I'm a python and Django newbie. Also a newbie in StackOverflow... I'm trying to build a CreateView with a form that contains a button to lookup information via a GET request using HTMX. A user would encounter the form completely blank at first. Once they input a specific field (in this case a serial number), they can click the button that initiates the lookup/GET request. After the information is retrieved via the GET, I would like to update specific fields in the form with some of the information from the GET (essentially like an auto-complete). So far I have been able to build the initial CreateView (which is straightforward) and have been able to setup the button that does the HTMX GET request; I have also been able to retrieve the information needed but where I'm stuck is on being able to update/inject the values retrieved into specific fields from the form after the GET request. What are the steps I should take to handle that specific part? I have tried adding the form into the view that manages the HTMX get request and assigning some of the "initial" values, later having the form with the values defined as "initial" … -
How to propagate error on create method in DRF serializer?
I'm trying to raise some error based on some business logic as in below class ConsultationViewset(BaseModelViewset, ListModelViewsetMixin, RetrieveModelViewsetMixin, CreateModelViewsetMixin, UpdateModelViewsetMixin): serializer_class = ConsultationSerializer .... class ConsultationSerializer(serializers.ModelSerializer): def create(self, validated_data): consultation = ConsultationService.create_consultation(validated_data.pop('customer', None), validated_data) return consultation def create_consultation(customer: CustomerFactory.Models.CUSTOMER, validated_data): if ticket is None: raise exceptions.PermissionDenied("No active ticket found for this customer, request is forbidden") My aim is to send the raised message in create_consultation in the response. Yet I keep getting AssertionError: create() did not return an object instance.instead. I could send a custom message if I re-raise the error in the viewset like below, but it felt wrong as the error is AssertionError. class ConsultationViewset(...): def perform_create(self, serializer): try: serializer.save() except AssertionError as e: raise exceptions.PermissionDenied('custom message') How to properly raise a PermissionDenied error? -
How to send CSRF token using Django API and a Flutter-web frontend ? HeaderDisallowedByPreflightResponse
I have a python/django web API with a single endpoint, let's call it /api/v1/form. That API is called from a Flutter-web frontend application. I currently use the following configuration that disables CSRF token verification, and it works : requirements.txt Django==5.1.7 django-cors-headers==4.7.0 webserver/settings.py ... ALLOWED_HOSTS = ["localhost"] CORS_ALLOWED_ORIGINS = ["http://localhost:8001"] # flutter dev port INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'webserver', ] ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... webserver/urls.py from django.urls import path import webserver.views urlpatterns = [ path('api/v1/form', webserver.views.api_v1_form, name="api_v1_form"), ] ... webserver/views.py from django.http import HttpResponse, HttpResponseBadRequest def api_v1_form(request): if request.method == "POST": process_request(request.body) return HttpResponse("request successfully processed.") return HttpResponseBadRequest("Expected a POST request") flutter/lib/page_form.dart Future<int> sendForm(MyData data) async { final response = await http.post( Uri.parse("http://localhost:8000/api/v1/form"), body: data.toString(), ); return response.statusCode; } Here is what I don't understand : if I disable to the CORS package in order to simply use a vanilla Django server, then I find myself capable of sending requests to the API but unable to receive an answer. Why is that the case ? The following is the configuration used to get the CSRF token and use it in the requests. settings.py ALLOWED_HOSTS = ["localhost"] … -
Django with chartjs > 2.9.3
I'm using version Django==5.0.6 and attempting in integrate charts using chartjs and plugin datalabels. When I use the charts render without issue, but I'm not able to see any datalabels. If I try to add Chart.register(ChartDataLabels); the graph no longer renders. I've also tried Chart.plugins.register(ChartDataLabels); I'd like to be able to use the most updated version of chartjs but when I change the chart version to anything other than 2.9.3, the graphs don't render. base.html <!DOCTYPE html> <html> {% load static %} {% load django_bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <head> <title>{{ template_data.title }}</title> <link rel= "stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href= "https://fonts.googleapis.com/ css2?family=Poppins:wght@300;400;500;600;700&display= swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script> </head> ... data.html {% extends "base.html" %} {% load django_tables2 %} {% block head %} <p><h3>Job data</h3>{{year}}</p> {% endblock head %} {% block content %} <canvas id="chart" style="position: relative; height:100vh; width:100vw"></canvas> <script> let ctx = document.getElementById("chart").getContext('2d'); /* Chart.register(ChartDataLabels); Chart.plugins.register(ChartDataLabels); */ let chart = new Chart(ctx, { type: "horizontalBar", data: { labels: [{% for data in labels %} '{{data}}', {% endfor %}], datasets: [ { label: "Job Week 13", backgroundColor: "#2d9f42", borderColor: "#030202", data: [{% for data in week13_count … -
Which is better: using Django Constraints or raising a ValueError in the save method?
I’ve come across two ways to enforce a condition in Django models: Using the save method with a ValueError: class MyModel(models.Model): field_name = models.CharField(max_length=100) def save(self, *args, **kwargs): if not self.field_name: # Example condition raise ValueError("Field name cannot be empty.") super().save(*args, **kwargs) Using Django's Constraints (like CheckConstraint): from django.db import models from django.db.models import Q class MyModel(models.Model): field_name = models.CharField(max_length=100) class Meta: constraints = [ models.CheckConstraint( check=~Q(field_name=""), # Example condition name="field_name_not_empty", ) ] I know both approaches can enforce conditions, but I’m wondering: Which approach is more efficient? Which one is generally better to use in real-world scenarios? -
Calling a Django Management Command from a Celery Task and Redirecting Logs
I'm trying to call a Management Command with call_command within a Celery task. The management command writes logs in different ways: through print statements, self.stdout.write, or using the logger defined at the script's module level. I want to capture all these log messages in the Celery logger to make them visible in Datadog. Is this possible? I tried the worker_redirect_stdouts_level option, but it impacts the global Celery logging configuration. -
Django formset with nested single inline form of each formset object(form)
I'm trying to figure out the logic of building such structure: class Order(models.Model): id = ... class OrderItem(models.Model): order = FK(Order) quantity = CharField() category = CharField(choices=..) class OrderItemSchema(models.Model): class Meta: abstract = True order_item = OneToOneField(OrderItem) brand = CharField() model = CharField() class SomeProduct1Schema(OrderItemSchema): size = PositivieIntegerField() class SomeProduct2Schema(OrderItemSchema): weight = CharField() type = CharField() Let's assume some customer has created new Order which "Company" has to produce. There are different types of products (not much: 2-10) which may not have even single common parameter/field but still be placed withing one Order. The question is: How to manage FormSet (or there is another way?) of OrderItem elements where each element may has different fields? Example: OrderItem: [SomeProduct1Schema] \ category \ quantity \ brand \ model \ size OrderItem: [SomeProduct2Schema] \ category \ quantity \ brand \ model \ weight \ type So far I've added OrderItem inline formset to Order and both SomeProduct1Schema \ SomeProduct2Schema inline formsets attached to OrderItemFormSet as nested form. But it's works well with single nested formset class and becoming mess when need to handle multiple dynamically. Now I'm thinking to make SomeProduct1Schema classes to inherit from OrderItem directly using multi-table inheritance. Performance is not … -
Django decorator import issue: 'cannot import name' when used in views.py
when trying to start the server it cannot find the decorator from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ... @staff_member_required def delete_service_view(request, service_id): service = get_object_or_404(Service, pk=service_id) service.delete() return redirect('index') @staff_member_required def toggle_trusted_from_service_view(request, user_id): if request.method == 'POST': try: user = User.objects.get(pk=user_id) user.isTrusted = not user.isTrusted user.save() return redirect('service_detail', service_id=request.POST.get('service_id')) except User.DoesNotExist: return HttpResponseForbidden("User not found.") else: return HttpResponseForbidden("Invalid enquiry method.") When i try python manage.py runserver File "C:\Users\alexe\djangoshop\dshop\main\views.py", line 3, in <module> from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ImportError: cannot import name 'staff_member_required' from 'django.contrib.auth.decorators' (C:\Users\alexe\djangoshop\dshop\dshop_new_env\Lib\site-packages\django\contrib\auth\decorators.py) I've already recreated the environment and reinstalled all dependencies