Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a Django Model for Funds Transfer in a Banking Application
I'm a Django developer with a project to create a banking application. One of the biggest problems is fund transfers between users. To achieve this, I need to design a Django model that includes both a sender and a receiver for fund transfers so that when the sender sends the funds, it will update the receiver's 'account_balance' field in the 'account' model. How can I create a 'Transfer' model that includes a sender and a receiver in one model, and how can I differentiate between the sender and receiver when making fund transfers in the 'views.py' file? my models: class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() account_balance = models.DecimalField(max_digits=12, decimal_places=6) class CustomUser(AbstractUser): username = models.CharField(max_length=30) full_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=16) address = models.CharField(max_length=200) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(max_length=20, choices=GENDER) email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return str(self.username) Can you please provide a detailed breakdown of the key components this model should have, including fields, relationships, and any security measures or transaction management techniques I should implement? -
Django page not found although everything seems okay
I am new to Django and I am doing everything that is indicated in Django documentation but I can not figure out why it keeps saying Page Not Found I tried changing the path or Debug=True to Debug=False but nothing interesting happened. It once worked but now it keeps saying Page Not Found. from django.urls import path from . import views urlpatterns = [ path("mainpage/", views.index, name="index"), ] this is urls.py mainpage from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("My first page") this is views.py mainpage from django.contrib import admin from django.urls import path from django.contrib import admin from django.urls import include, path urlpatterns = [ path("mainpage/", include("mainpage.urls")), path('admin/', admin.site.urls), ] ```and this one is urls.py mysite this is the result: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: mainpage/ mainpage/ [name='mainpage'] admin/ The current path, mainpage/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. http://127.0.0.1:8000/mainpage/ -
Django and docker-compose serving with NGINX: file not found
I've been trying to set up my django project with gunicorn and nginx. The server runs, but I've been struggling to get the admin page to serve static files (I haven't created any other static files for the project, so I'm just starting with admin). I bit the bullet and just copied the original django admin static file into my own project, but when I load the admin page, there are no static files. My docker "web" image shows: web_image_name | Not Found: /static/admin/js/... web_image_name | Not Found: /static/admin/css/... ... This error is interesting, since when I go into that image's terminal and do "ls", I can see the static directory. Is this problem related to nginx, docker, or both? Code: nginx.conf: # nginx.conf events { worker_connections 1024; } http { server { listen 80; server_name your_domain.com; # Change to your domain or IP address location / { proxy_pass http://web:8000; # Points to your Gunicorn service proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { alias /app/static/; } } } docker-compose.yml (truncated): version: "3" services: web: container_name: newspigeon_web build: context: . dockerfile: Dockerfile command: > bash -c "python manage.py migrate && gunicorn --workers=4 --bind=0.0.0.0:8000 newspigeon.wsgi:application" ports: … -
django allauth github organizations restriction
i have created a Django webapp, and i want to use allauth to create a sso for github. I have set it up, and it works fine. But now all github users can login to my webapp. I want to restrict it only to my github organization. So that all users of my organization can login to the web app and users which are not in the organization cant login. Is there any option from allauth to realize this? i have checked the allauth documentation, but i can't find any option for that. Or is there any other way which i can use to realize my requirement? -
Django Admin Display Problem (TabularInline)
as you see in the photos "Member" table is too long , there is a one to one relation between User and Member. this is the admin.py code class MemberInLine(admin.TabularInline): model = Member class UserAdmin(admin.ModelAdmin): list_display = ('username','is_active', 'is_staff','is_superuser') list_filter = ('is_active', 'is_staff') search_fields = ("username",) ordering = ('username',) filter_horizontal = () filter_vertical = () fieldsets = () inlines=[ MemberInLine, ] admin.site.register(User,UserAdmin) -
Trouble getting past CORS error in Django
I'm getting a CORS error whilst trying to use React with Django and postgresql. I have tried many ways to configure the CORS settings in Django however nothing seems to work. When I made a simple route that passes "Hi" it works. So I am not sure if there is an error with my view or something is wrong with the front end at React. I have also ensured that the VITE_SERVER is correct by console logging it and that my endpoints used are accurate. This are my Django settings: ALLOWED_HOSTS = [] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ 'content-type', 'authorization', ] CORS_ALLOWED_ALL_ORIGINS = True ALLOWED_HOSTS = [ "127.0.0.1", ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:8000/"] AUTH_USER_MODEL = 'customers.CustomerAccount' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'customers', 'dealer', 'restful_apis', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] This is my fetch hook that I used: import React from "react"; const useFetch = () => { const fetchData = async (endpoint, method, body, token) => { const res = await fetch(import.meta.env.VITE_SERVER + endpoint, { // mode: "no-cors", method, headers: { "Content-Type": "application/json", Authorization: "Bearer … -
How to change the year range of datepicker in django jalali date?
In my Django project, I am looking to get users birth dates. For this purpose, I used a django-jalali-date and jdatetime packages. Currently, the user has access to 10 years before and 10 years after today's date and can picker. I am looking for it to display only 100 years before the current date. model: class Student(models.Model): birthday_date = models.DateField(null=True) form: class StudentForm(forms.ModelForm): birthday_date = JalaliDateField(widget=AdminJalaliDateWidget) class Meta: model = Student fields = ( 'birthday_date', ) template: {% load jalali_tags %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Success singup</title> </head> <body> {% comment %} <p>{{ request.user.date_joined|to_jalali:'%y/%m/%d _ %H:%M:%S' }}</p> {% endcomment %} <form method="post" action="{% url 'accounts:student_success_signup' pk=pk %}"> {% csrf_token %} {{ customuser_form.as_p }} {{ student_form.as_p }} {{ phonenumber_form.as_p }} <button type="submit">Submit</button> </form> <!-- By default, Datepicker using jQuery, you need to set your script after loading jQuery! --> <!-- loading directly --> <link rel="stylesheet" href="{% static 'admin/jquery.ui.datepicker.jalali/themes/base/jquery-ui.min.css' %}"> <script src="{% static 'admin/js/django_jalali.min.js' %}"></script> <!-- OR --> <!-- loading by form (if used AdminJalaliDateWidget) --> {{ form.media }} </body> </html> AdminJalaliDateWidget: class AdminJalaliDateWidget(AdminDateWidget): @property def media(self): js = settings.JALALI_DATE_DEFAULTS['Static']['js'] css = settings.JALALI_DATE_DEFAULTS['Static']['css'] return forms.Media(js=[static(path) for path in … -
Designing a Secure and Efficient Django Model for Money Transactions
I'm worki on Django application that involves sending and receiving money between users. I want to ensure that my database model is designed efficiently and securely to handle these transactions. What are the best practices and considerations I should keep in mind when designing the Django model for managing money transfers? Are there any specific patterns that can help with this? I'm particularly interested in: Ensuring the security and integrity of financial transactions. Handling different types of transactions (e.g., transfers between users, deposits, withdrawals). The best practices for structuring the database model to track money transactions accurately? Any insights or code examples would be greatly appreciated. -
Which Relationship between Django Models
I'm trying to code a DB based web app with Python/Django and I have some issues figuring out which is the best approach for my purpose, so I'll try to explain myself the best way possible. The DB stores objects that represent a videogame PG's Armor Pieces. Every piece has some positive/negative abilities scores: wearing a complete Armor set (Helmet, Jacket etc..), the scores for each ability sum up and can give different effects. So, every armor piece can have different abilities, and each Ability can be shared between several Armor Pieces, but the scores for each Ability may be different for different Armor Pieces. Once finished, this app should be able to find - if possible - a complete ArmorSet composed of 5 ArmorPiece which have the PieceAbility.scores necessary to activate one or more Effects the user would like. from django.db import models class Ability(models.Model): name = models.CharField(max_length=20) def __str__(self) -> str: return self.name class ArmorSetPart(models.Model): part = models.CharField(max_length=10) def __str__(self) -> str: return self.part class WeaponClass(models.Model): type = models.CharField(max_length=20) def __str__(self) -> str: return self.type class Rank(models.Model): rank = models.CharField(max_length=10) def __str__(self) -> str: return self.rank class PieceAbility(models.Model): name = models.ForeignKey(Ability, related_name='pieces', on_delete=models.CASCADE) score = models.IntegerField(default=0, ) def … -
Issue with Loading and Sorting Comments Using JavaScript (FETCH API) and Django
I'm working on a blog using Django and JavaScript, where users can submit and view comments on a post. I have implemented a functionality to sort these comments based on "newest", "Most liked", and "oldest" using a dropdown menu. Additionally, I've added a "Load more comments" button to paginate the comments. When the page initially loads, the first ten comments are displayed, which is what i want. When a user clicks on the "load more comments" button, i want the next batch of ten comments to be displayed underneath, and so on until there is no more comment to be displayed, at which point the "Load more comments" button is hidden. However, I'm facing some issues, and they are - After clicking the "Load more comments" button, the initial set of comments is replaced by the next set of comments. Instead, I want the new comments to be appended below the existing ones. The intended behaviour of the "Load more comments" button is only achieved AFTER changing the sorting option back and forth. What I mean is that after initially loading up the page, the "load more comments" button when clicked, replaces the 10 existing displayed comments with the next … -
python data formatting in Django
I get this flow of data from database. but I couldn't figure out how to format it. this is how I want it; This is how it is. [{'date': datetime.date(2023, 5, 27), 'pnl': '69'}, {'date': datetime.date(2023, 7, 23), 'pnl': '81'}, {'date': datetime.date(2023, 9, 12), 'pnl': '67'} ] This is how I want it [[69, 27, 5, 2023],[81, 23, 7, 2023],[67, 12, 9, 2023]] [0] = pnl, [1] = date, [2] = month, [3] = year -
Axios instance does not attach Authorization header in GET requests despite attaching it in POST requests
I use axios to call my API(Django server) from a react website, I want an authorization header with a Bearer token to be present in every request in the authorization header. This is how I set the authorization header apiClient.defaults.headers.common['Authorization'] = Bearer ${token}; When I call my api with a post request: const response = await apiClient.post('posts/', payload); It works as expected, the authorization token is present in the request. However whenever I call any GET request: apiClient.get(posts/${router.query.id}/), I see no Authorization header in the requests header in the network tab of the browser. I verified that it is the same axios instance and that it is not an issue of an incorrect request. I also noticed that before each POST request an OPTIONS request is being sent, perhaps it is somehow telling axios to attach authorization header? Thank you in advance, if needed I can attach also the code in the backend responsible for the API endpoints. -
error while running the codeException in thread django-main-thread Traceback
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [Previous line repeated 988 more times] File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 62, in _load_all_namespaces namespaces = [ ^ RecursionError: maximum recursion depth exceeded can anyone tell ma what can I do to solve it -
I am using Railway to host my Django project, but the static files do not load even after correctly configuring the directories in settings.py
I have correctly configured the path of static urls in settings.py but Railway keeps displaying my pages without any CSS. I don't have any other pages other than the admin panel and rest framework pages because it is just a backend project. Usually (according to all tutorials I watched), running python manage.py collectstatic after correctly configuring the paths in settings.py is enough to make Railway detect staticfiles and use them in deployment. I did and it is successfully deploying my project but logs that it couldn't find all of my static files hence displaying plain HTML. Here's the Static URLs configuration: STATIC_URL = '/static/' STATIC_ROOT =os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -
Django query by parent id without join
Let's say I've two models Parent and Child related by foreign key want to query all children without making a join with the parent table will Child.objects.filter( parent_id=parent_id ) do the trick? notice I'm doing a single underscore instead of double, so in theory it should only look through parent_id column in child table instead of making the joins, right? -
why this class in my views.py not working
class UserLoginView(View): form_class = UserLoginForm template_name = 'accounts/login.html' def get(self,request): form = self.form_class context = {'form':form} return render(request,self.template_name,context) def post(self,request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,username=cd['username'],password=cd['password']) if user is not None: login(request,user) messages.success(request,'Your login successfully','success') return redirect('home:home') messages.error(request,'username or password is wrong','warning') return render(request,self.template_name,{'form':form}) my pc does not know if form.is_valid -
Doesn't call python print function?
My urls is : from django.contrib.auth.views import LoginView path('login/', LoginView.as_view(),name='login') class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): print('new dispatch')#Does not call if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_success_url(self): url = self.get_redirect_url() print(url)#Does not call print('ok')#Does not call return url or resolve_url(settings.LOGIN_REDIRECT_URL) Send request to view doesn't print print() methods...? -
User Interface is not working with apache2 for django project but working on local server
I have created a django project that is working fine on the local server(127.0.0.1). I was trying to push the code to amazon aws. The code and the migrations are working but the ui is missing. I'm attaching the screenshot of the working page along with the 000-default.conf. Working page on localhost Page working on apache on aws 000-default.conf file I tried to change the staticfiles path but the result was the same. -
Best practice for validators in Django serializers?
I am currently new to DRF, working on validators for a "Book Edition" serializer. They seem to be working as intended, but as I am looking into documentation it seems most people override the validate() or include them in the Meta class. I am wondering if I am going about this completely wrong now! My main questions are: Is it appropriate to add these validators through the serializers.IntegerField()s? Will both these validators for the ISBN be called when the data is serialized? Here is my code: class EditionSerializer(serializers.ModelSerializer): ISBN = serializers.IntegerField( validators=[ UniqueValidator( queryset=Edition.objects.all(), message="ISBN must be unique." ), ], ) def validate_ISBN(self, value): errors = {} if len(str(value)) != 10 and len(str(value)) != 13: errors[ "digits" ] = "A valid ISBN number must contain either 10 or 13 digits." if errors: raise ValidationError(errors) return value year_published = serializers.IntegerField( validators=[MaxValueValidator(limit_value=timezone.now().year)] ) -
How to Solve Not Compatible Python Libraries on Google Kubernetes Engine?
During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 135, in handle self.handle_request`enter code here`(listener, req, client, addr) File "/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 178, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/env/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 152, in handle_uncaught_exception callback = resolver.resolve_error_handler(500) File "/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 615, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/env/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/vmagent/app/mysite/urls.py", line 38, in <module> re_path(r'^rosetta/', include('rosetta.urls')) File "/env/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, … -
Django - confused about naming class and parameters (when to use uppercase / plural form)?
Such confusion reflects unclear understanding about class and framework. I'm learning database in Django models. I get confused about naming class. When to use uppercase / lowercase, when to use singular and plural? I'm following the lecture from freecodecamp with this example: In models.py, I assign a class called Feature(models.Model). Then, in views.py, I assign features for templates: features = def index(request): Features.objects.all() return render (request, "index.html", ({"features": features}) In index.html, there exists a for loop, therefore I run the syntax for feature in features: with the variable {{feature.name}} and {{feature.details}} At this moment I just memorize without understanding when deciding when to use Feature vs feature, features vs feature. I find it rather difficult in memorizing the code views.py. I need a real understanding about naming. Below is the flow of some of the code. Thank you so much for your help. models.py class Feature(models.Model): name = models.CharField(max_length = 100) details = models.CharField(max_length = 500) ------ settings.py python manage.py makemigrations python manage.py migrate python manage.py createsuperuser ---- admin.py from .models import Feature admin.site.register(Feature) ---- views.py def index(req): features = Feature.objects.all() return render(req, "index.html", ({'features': features}) ---- index.html for feature in features: ....{feature.name} ....{feature.details} -
Would like to build a dynamic website on AWS with files in S3 backend
Here is a requirement: We would like to have a dynamic website hosted in AWS through which we will be able to edit/update few text files. More elaborately, I know how to code in Python and Flask and I prefer to use that (or maybe Django) and the files will need to be stored in S3 in some bucket. I had used my own EC2 Server to host a dynamic website. But I never used that to change/edit/update any file etc. in S3. So that part is new to me - I need to figure it out. I thought if there are other approaches I do not know of (and my AWS knowledge is limited). Please suggest some alternatives or rather the best way (best AWS features to use) to solve this. Thank you all AWS experts! Appreciate your help, in advance. -SDN -
Django storages adding “;amp” to staticfiles query string parameter only for Django-jet files resulting in unauthorized access
Some staticfiles links have wrong params, what i noticed that they are only related to "django-jet" package. Normal Django staticfiles URL: https://daal.nyc3.digitaloceanspaces.com/static/css/admin.css?AWSAccessKeyId=****&Signature=***&Expires=1694226003 Django JET staticfiles URL: https://daal.nyc3.digitaloceanspaces.com/static/jet/css/icons/style.css?AWSAccessKeyId=*****&amp;Signature=*****&amp;Expires=1694226003&v=1.3.3 This is causing request headers to have invalid names: Note sure what is causing this? I couldn't find out why -
Command run 'pylint' on github action does not recognize Django setup
I have been trying to refactor my pylint workflow to comply with results of my local machine. After some wrestling, I am unable to make it understand the Django structure and apply environment installation. Source code: https://github.com/trouchet/tarzan/blob/main/.github/workflows/pylint.yml name: Pylint on: [push] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10"] steps: - name: Checkout Code uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Set DJANGO_SETTINGS_MODULE run: export DJANGO_SETTINGS_MODULE=src.settings - name: Set up Poetry and pylint run: | # Install Poetry if not already installed curl -sSL https://install.python-poetry.org | python - # Configure Poetry to use the correct Python version poetry env use ${{ matrix.python-version }} - name: Set up Poetry and pylint run: | pip install pylint-django - name: Install project dependencies run: | # Install dependencies using Poetry poetry install - name: Analyze the code with pylint run: | # Run Pylint on Python files pylint $(git ls-files '*.py') -
Merging dictionaries in Django's views.py creates \n in JSON output
Merging dictionaries in django's views.py creates \n in Rest API json output @api_view(['GET']) def json_test(request): dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged_dict = {**dict1, **dict2} result = json.dumps(merged_dict, indent=4) return Response(result) Result in postman " {\n "a":1,\n. "b":2,\n "c":3,\n "d":4,\n}" I am expecting \n to not show up in api results and should look like below **{ "a":1, "b":2, "c":3 }" **