Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Inline Formset "update" functionality is not working
Django project: For Create and Update, I used Class Based View method. In there, I have form (parent) and formset (of child). Both ParentForm and ChildFormset are in the same page. Create functionality is working perfectly. Problem: Update functionality is not saving changes because of already existing formset. It only refreshes the current page. How to fix it? class ParentInline(): form_class = ParentForm model = Parent template_name = "parent_create_or_update.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) self.object = form.save() # for every formset, attempt to find a specific formset save function # otherwise, just save. for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('/parent_list') def formset_childs_valid(self, formset): """ Hook for custom formset saving.Useful if you have multiple formsets """ childs = formset.save(commit=False) # self.save_formset(formset, contact) for child in childs: child.parent_Id = self.object child.save() class ParentCreate(ParentInline, CreateView): def get_context_data(self, **kwargs): ctx = super(ParentCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'childs': ChildFormSet(prefix='childs'), } else: return { 'childs': ChildFormSet(self.request.POST or None, self.request.FILES or None, prefix='childs'), } class ParentUpdate(ParentInline, UpdateView): def get_context_data(self, **kwargs): ctx = super(ParentUpdate, self).get_context_data(**kwargs) … -
Need help choosing backend end / front end languages (I'm beginner) [closed]
I want to create a website with machine learning logic in python on the back-end and use react on the front-end. I'm going to do everything myself, as I'm a beginner any tip is welcome. So my thought process is to use Django to handle all the python and back-end, and use Next.js for the front-end. I'll create a simple guitar tuner as a starting point, and as I learn new stuff, I'll implement it to the site and create new features for it like some kind of music sheet. Is this the best approach? I want to use these languages because I already know them, do Django and Next.js work well together? Or is using just next.js enough by now? This is just a personal project for now, if I'm satisfied with the end result I will host it somewhere in the future -
Difference between creating indexes in Django using db_index=true and Class Meta: indexes=[ models.Index(fields=[col1, col2,..]),]
I was looking into how to create an index in Django. I came across two ways: Class Student(models.Model): name= models.CharField(........, db_index=True) age= models.CharField(........, db_index=True) Class Student(models.Model): name= models.CharField(........) age= models.CharField(........) Class Meta: indexes = [models.Index(name="first_index",fields=["name","age"],)] Can someone clarify what the difference between them is? Moreover, in the db_index=true method, is there a single index for all the fields with db_index=true ? -
Django LogEntry without user
In my app there's a Project model which users can create, request to join, invite others to join, accept/reject requests/invites to join, leave, etc. I'm using the Django LogEntry to help the application admins keep track of all changes to each Project, but also changes to related objects such as ProjectMember, ProjectMemberRequest and ProjectMemberInvite. Both ProjectMemberRequest and ProjectMemberInvite have expiration dates which means that, if they aren't accepted/rejected within 3 days after being created, the system automatically sets them as 'expired'. How can I log this automatic expiration of ProjectMemberRequest and ProjectMemberInvite, knowing that LogEntry requires a user and this expiration actions are not triggered by a user? A workaround I could use is to create a "System" superuser and log these automatic actions to that user. Is there anything better? -
How to use AWS SES inside Django running in a Fargate container?
I have a Django App running in an AWS ECS Fargate container and want to set up the possibility to send mails from Django. This is not too difficult using the built in function. I have set up SES on AWS and granted the Task Role of my Fargate task full access to SES. As far as I understand, AWS automatically generates credentials for the Task role (see e.g. here. To set up the SES mailing function in Django, I need the EMAIL_HOST_USER which in case of AWS SES will be an AWS_ACCESS_KEY_ID and the Password which would be the secret key of this user. Now I am slightly confused since I actually want to use the Task role of the Fargate task to send emails. Do I have to somehow get the credentials inside the Django code and set the environment variables? Or can I leave them blank and somehow Fargate automatically connects to SES by its Task Role. -
I'm experiencing the following log in my docker containers while putting together a django web app:ERROR: cannot drop the currently open database
Have been experiencing issues connecting to the ports based on my log entries but I have assured that my ports in postgres are assigned properly and restarted my workspace repeatedly, clearing all volumes and images as to better understand the nature of my issue but am still being met with the following log entry consistently. (Apologies for lack of detail in advance as this is my first time posting instead of reading here) 2023-04-21 08:51:07 sh: locale: not found 2023-04-21 08:51:07 2023-04-21 12:51:07.859 UTC [31] WARNING: no usable system locales were found 2023-04-21 08:51:09 initdb: warning: enabling "trust" authentication for local connections 2023-04-21 08:51:09 You can change this by editing pg_hba.conf or using the option -A, or 2023-04-21 08:51:09 --auth-local and --auth-host, the next time you run initdb. 2023-04-21 08:51:09 psql:/docker-entrypoint-initdb.d/1-django-init.sql:1: ERROR: cannot drop the currently open database 2023-04-21 08:51:10 2023-04-21 12:51:10.334 UTC [1] LOG: starting PostgreSQL 13.2 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit 2023-04-21 08:51:10 2023-04-21 12:51:10.334 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2023-04-21 08:51:10 2023-04-21 12:51:10.334 UTC [1] LOG: listening on IPv6 address "::", port 5432 2023-04-21 08:51:10 2023-04-21 12:51:10.341 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2023-04-21 08:51:10 … -
In a django template, how to access dynamically to each attribute for every database table row?
I'm building a table in a django template to show all the records from a database table. I need to build dynamically (both rows and columns) but I am having problems to access each record attribute. My code's result, is an empty table with the same amount of database rows. I created a variable field_name to be assigned the attribute name, and then access that attribute aplying this variable to each record. The result, is an empty table with the same amount of database rows. I printed field_name and the attribute name is assigned okey, but then it's not applied correctly to the record. How should I code it? <tbody> {% for record in table_records %} <tr> {% for field in table_fields %} {% with field_name = field.name %} <td>{{ record.field_name }}</td> {% endwith %} {% endfor %} </tr> {% endfor %} </tbody> -
Problem is displaying frameset when connecting to django
there is a code #index.html <html> <head> <title></title> </head> <frameset rows=100% > <frameset rows=76%,24% > <frameset cols=64%,36% > <frame name=reports src="reports.html" > <frame name=fg_log src=/****.py > </frameset> <frameset cols=64%,36% > <frame name=fp_log src=/********.py?fp=3&files=on > <frame name=ls src=/*******.py > </frameset> </frameset> </frameset> </html> at startup, simply by opening index.html through the browser - I see the data of the first frame but if you start displaying the same index.html through django - I see 404 instead of hello world and I also see an error in the terminal I have not found the answer why this is happening and how to solve it, but I need to use frameset -
How can I create registration form for custom user model in Django?
I'm trying to create custom user form in Django, but it doesn't work. Pls help me views.py: def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = form.cleaned_data['email'] user.save() profile = user.objects.create( user=user, avatar=form.cleaned_data['avatar'] ) return redirect('/login/') return render(request, 'reg_form.html') models.py: class user(models.Model): profile = models.OneToOneField(User,on_delete=models.PROTECT) nickname = models.CharField(max_length=100,default='') avatar = models.ImageField(null=True,blank=True) objects = userManager() def __str__(self): return f'{self.nickname}' forms.py: class RegistrationForm(UserCreationForm,forms.ModelForm): email = forms.EmailField(required=True) class Meta: model=user fields = ('username', 'email','nickname', 'password1', 'password2', 'avatar', ) I tried to make form for Django's user model and it works good, but I need to make it for custom user -
Django javascript Canvas late update draw
I made a form that calculates a rectangle in Django. I made a form in the html file and had it calculated with javascript and gave the data to the screen. But when I submit again by changing the data in the form, the "result" changes but the canvas is not updated. It only gets updated when I press the submit button a few times. What is the reason of this? <div class="container"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card"> <div class="card-header"> <h4 class="text-center">Dikdörtgen Hesaplayıcı</h4> </div> <div class="card-body"> <form id="area-form"> <label for="shape">Hesaplanması istenen değerleri Seçin:</label> <select id="shape" class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="shape"> <option value="Dikdörtgen_alan_çevre">Alan ve Çevre</option> <option value="Dikdörtgen_köşegen_uzunluk">Köşegen Uzunluk</option> <option value="Dikdörtgen_kenar_uzunluk">Kenar Uzunluk</option> </select> <br><br> <div id="Dikdörtgen_alan_çevre"> <label for="length" class="form-label" >Uzun Kenar:</label> <input type="number" class="form-control" step="0.0001" id="length" name="length"> <br><br> <label for="width" class="form-label" >Kısa Kenar:</label> <input type="number" class="form-control" step="0.0001" id="width" name="width"> </div> <div id="Dikdörtgen_köşegen_uzunluk" style="display:none;"> <label for="köşegen_length" class="form-label">Uzun Kenar:</label> <input type="number" class="form-control" step="0.0001" id="köşegen_length" name="köşegen_length"> <br><br> <label for="köşegen_width" class="form-label" >Kısa Kenar:</label> <input type="number" class="form-control"step="0.0001" id="köşegen_width" name="köşegen_width"> </div> <div id="Dikdörtgen_kenar_uzunluk" style="display:none;"> <label for="kenar_length" class="form-label" >Kenar Uzunluk:</label> <input type="number" class="form-control" step="0.0001" id="kenar_length" name="kenar_length"> <br><br> <label for="Köşegen" class="form-label">Köşegen Uzunluk:</label> <input type="number" class="form-control" step="0.0001" id="Köşegen" name="Köşegen"> </div> <br><br> <button type="submit" class="btn btn-primary">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> … -
Serializer NOT displaying object on Django Rest Framework
I have created a test view to test the API, as follows: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from profiles_api import serializers class HelloApiView(APIView): """Test API View""" serializers_class = serializers.HelloSerializer # specifies the Input expected when GET,PUT,POST,DELETE is requested def get(self, request, format=None): """Returns a list of APIView features""" an_apiview = [ "Uses HTTP methods as function (get, post, patch, put, delete)", "Similar to django view, but specific for APIs", "Gives you the most control over your application", "Is mapped manually to urls", ] return Response({"message": "Hello!", "an_apiview": an_apiview}) def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) # serializers_class comes with the APIView that retrieves the configured Serializer Class for our view (Standard way) if serializer.is_valid(): name = serializer.validated_data.get("name") message = f"Hello {name}" return Response({"message": message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py file looks like the following: from rest_framework import serializers class HelloSerializer(serializers.Serializer): """Serializes a name field for testing APIView""" # similar to django forms name = serializers.CharField(max_length=10) When i run the server, the Django rest Framework does NOT show a form called name, but one called Content, and when i try to post a name for example "Hola", … -
New Access & Refresh Tokens not generating after refresh token after expiration time
When the user is logged in then the new refresh and access tokens are generated which are stored in the local storage using reactjs. When the access token is expired then no new access token is created and stored in the local storage and same goes for refresh token. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', 'main', 'ecom', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] INTERNAL_IPS = [ # ... '127.0.0.1', # ... ] CORS_ORIGIN_ALLOW_ALL = True ROOT_URLCONF = 'shopy.urls' AUTH_USER_MODEL = 'main.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'main.custom_authenticators.CustomAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5), 'REFRESH_TOKEN_LIFETIME': timedelta(seconds=5), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), } main/custom_authenticators.py from rest_framework_simplejwt.authentication import JWTAuthentication class CustomAuthentication(JWTAuthentication): def authenticate(self, request): if request.method == 'GET': return None return super().authenticate(request) interceptors/axios.js import axios from 'axios'; import dayjs from 'dayjs'; import jwt_decode from 'jwt-decode'; axios.defaults.baseURL = 'http://localhost:8000/'; axios.interceptors.request.use(function (config) { const access_token = localStorage.getItem('access_token'); if (access_token) { config.headers.Authorization = `Bearer ${access_token}`; } return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use(function (response) { return response; }, async function (error) { const originalRequest = error.config; if (error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = … -
Django messages only work if DEBUG = True
I'm using Django with Wagtail CMS. I'm trying to give the user a message on registering an account and when you cancel the account. At this moment this both work, but only when when I have the settings DEBUG = True, if I set DEBUG to false (as it has to be in production) the messages no longer come up. My Django settings: INSTALLED_APPS = [ 'home', 'search', 'user', 'blog', 'rss', 'rosetta', #'wagtailorderable', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.styleguide', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail', #'wagtail.images.panels', 'wagtailfontawesome', 'wagtail_color_panel', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'django.contrib.sites', "django.contrib.sitemaps", 'wagtail.contrib.modeladmin', # Don't repeat if it's there already 'sorl.thumbnail', ] MIDDLEWARE = [ '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', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] DEBUG = True Here is how I call the message when the user registers, I'm using a signal from allauth: from django.utils.translation import gettext_lazy as _ from django.dispatch import receiver from django.contrib import messages from allauth.account.signals import user_signed_up class User(AbstractUser): class Meta: db_table = 'auth_user' @receiver(user_signed_up) def user_signed_up_callback(sender, request, user, **kwargs): return messages.success(request, _('Thank you for creating an account')) I have already tried several fixes found online including: changing MESSAGE_LEVEL to an integer, and … -
monitoring celery task in Django
I am using celery-results and celery-beats in my Django app. I am using React framework in my frontend and I'd like to create a component to monitor all statuses in all celery tasks but celery-beats displays only statuses: STARTED, FAILURE, SUCCESS. What I want is to display all possible statuses in my database. I am using Flower and it is working fine but I need just to save all statuses to my PostgreSQL db. Question What would be the best way to do it? I know that TaskResults is just storing completed tasks but how to extend this library to store all statuses to my db? I configured celery to show me STARTED status but it is not enough. I need all possible states, especially RECEIVED. -
How to annotate a value of related filtered and aggregated object?
I have two objects: Course (one) and TeachingAssistantsNumberApprovalRequest (many). Each request has fields: closedAt - time status - (Approved, Pending, Rejected) requestedNumberOfTAs - integer As a result there is a table for TeachingAssistantsNumberApprovalRequest: course_id status closedAt requestedNumberOfTAs 1 Pending null 3 1 Approved 9:40 21.04.23 2 1 Approved 3:40 19.04.23 3 1 Rejected 2:10 19.04.23 4 2 Approved 10:40 21.04.23 2 2 Approved 9:40 21.04.23 3 2 Rejected 3:40 19.04.23 4 2 Rejected 2:10 19.04.23 5 I need to annotate the latest approved requestedNumberOfTAs. This is how I managed to do it with raw SQL: select web_course.*, CASE when ta_requested_number_approved.requested_tas > 0 then ta_requested_number_approved.requested_tas else 0 end as tas_request_approved from web_course left join ( select web_course.id as course_id, req."requestedNumberOfTAs" as requested_tas from web_course left join web_numberoftaupdaterequest as req on req.course_id = web_course.id inner join ( select web_course.id as id, max(req."closedAt") as closed_at from web_numberoftaupdaterequest as req inner join web_course on req.course_id = web_course.id where web_course.year = '{year}' and web_course.term = '{term}' and req.status = 'Pending' group by web_course.id order by web_course.id ) as max_date on max_date.id = req.course_id and max_date.closed_at = req."closedAt" where web_course.year = '{year}' and web_course.term = '{term}' and req.status = 'Pending' order by web_course.id ) as ta_requested_number_pending … -
Where! can I write a code after cmd "py manage.py shell" in Django while creating a database in Django?
I'm stuck. I have been creating my first database in Django following a course, but now, I don't understand where to put a code (from filmy.models import Film, Genre*my_film(Film(...))after the above mentioned command "py manage.py shell". What happend, but mainly where! There is something in migrations like "0001_initial.py", however, there is already a code written - shoud I just write the other code below? Thx a lot! I've expected 2 tables created somewhere... -
'site.com didn't send any data' using django
I have a Django webapp that takes a name and triggers a scrapy spider depending on the given name. My app works perfectly when I run it on localhost, but when trying to deploy it via PythonAnywhere.com I get an error message (on the browser, not the logs) that reads (translated) This page does not work azservices.pythonanywhere.com did not send any data. ERR_EMPTY_RESPONSE my views.py file is as follows: def index(request): THIS_FOLDER = Path(__file__).parent.parent.resolve() print(f'THIS_FOLDER is: {THIS_FOLDER}') if request.method == "POST": artist = request.POST.get("artist") print(f'artist is: {artist}') try: # configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'}) crawler = CrawlerRunner(get_project_settings()) q = crawler.crawl(PostsSpider, artist=artist) q.addBoth(lambda _: reactor.stop()) reactor.run() #download the XLSX file file_path = os.path.join(THIS_FOLDER, 'output.xlsx') print(f'file path is:{file_path}') response = FileResponse(open(file_path, 'rb'), as_attachment=True, filename='output.xlsx') print('hallo, ik ben zelfs hier') return response except Exception as e: print('Error', str(e)) return render(request, 'index.html') Through some extremely advanced commenting out code and print statements, I am confident that the code gets stuck at 'reactor.run()' Why do I get this error and how do I resolve it? -
How to save html files in db
I have some tasks about saving card we decided to save them like html with frontend by vue this would do my frontend developer And i dont know how can i do that on backend with django-rest-framework Should i save somehow this html card in my model db and then send that with api? If yes how can i do that? I mean save html in my db model I was trying to maybe use: models.TextField() and save html into text field but i dont think that this is how should work -
How to convert UTC time to Local timezone of user?
I can show UTC time of Django with this code. {{ data_log.field1 }} I want to convert UTC time to local time like this code. <script> var utc = new Date(); var offset = utc.getTimezoneOffset(); var local = new Date({{ data_log.field1 |safe }} + offset * 60000); document.getElementById("result").innerHTML = local; </script> {{ data_log.field1 }} <div id="result1"></div> It show error. Property assignment expected.javascript I can't send data_log.field1 to javascript code. How to fix it? -
Render React component in Django template view and replace original tag with component content
We have a Django template that includes a custom HTML tag, . We want to replace this tag with a React component, HelloWorld, while keeping the final DOM structure as clean as possible. However, the current implementation results in an extra div element wrapping the component content, and we are unable to remove it. Django template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>My Website</title> </head> <body> <HelloWorld name="Alice" /> </body> </html> React component: import React from 'react'; function HelloWorld(props) { return ( <div> <h1>Hello, {props.name}!</h1> </div> ); } export default HelloWorld; Current implementation: We are using the following code to render the HelloWorld component and replace the original tag in the Django template: function initReactApp() { const components = { HelloWorld, }; for (const componentName of Object.keys(components)) { // find components by their HTML tag name const componentElements = document.getElementsByTagName(componentName); for (let element of componentElements) { // assign the actual component function of the componentName const Component = components[componentName]; // collect all properties of the element to pass them to the dynamic component const props = Object.fromEntries( [...element.attributes].map(({ name, value }) => [name, value]) ); // render the dynamic component and mount it in the DOM const domNode … -
Django 4.1+ and Celery DB connection already closed
Django 4.1 introduced https://docs.djangoproject.com/en/4.2/ref/settings/#conn-health-checks, and when used in conjunction with CONN_MAX_AGE I've run into occasional Celery errors of the form Couldn't apply scheduled task xxx: connection already closed I have a workaround in my celery.py file (I happen to know of this solution because I also use Django's ORM in Flask, and it has the same issues): @task_prerun.connect def on_task_prerun(sender=None, headers=None, body=None, **kwargs): close_old_connections() I can't find anyone else experiencing the same issue, and before I create a PR for Celery I wanted to check with others first. Anyone else seen something similar? -
TypeError: QuerySet.create() takes 1 positional argument but 4 were given
I am trying to create a superuser for my django project, based on a user model i created. But when i run python manage.py createsuperuser and provide all the necessary information, i get an error that says TypeError: QuerySet.create() takes 1 positional argument but 4 were given. Here is the full Traceback: Traceback (most recent call last): File "/Users/xxxx/Desktop/django-rest-tutorial/django/manage.py", line 21, in <module> main() File "/Users/xxxx/Desktop/django-rest-tutorial/django/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 156, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/Users/xxxx/Desktop/django-rest-tutorial/django/profiles_api/models.py", line 30, in create_superuser user = self.create(email, name, password) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/xxxx/Desktop/django-rest-tutorial/django/venv/lib/python3.11/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: QuerySet.create() takes 1 positional argument but 4 were given Here is my User Model defined in the models.py file: from django.db import models # Imports to override the default django user model from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" # Define functions that manipulate … -
crete history record only when it change specific fields using django-simple-history
I want to use django-simple-history for store history in database, but thing is i want to store history only defined specific field change, not when other field change. i didn't found any specific things for this. it has option for execlude_fields, but it won't helpful because it just ignore those fields from history. Is there any suggestion? -
Django ORM - How to access annotated field value?
Let's assume I have the next models: class A(model): b = models.ManyToManyField("b", through="AB") class B(model): id = models.CharField() class AB(model): a = models.ForeignKey("a") b = models.ForeignKey("b") I want to retrieve all related A objects for specific B object and plus annotated field count_something for each A object. b_obj = B.objects.prefetch_related(Prefetch('ab_set', queryset=AB.objects.select_related('a') .annotate(count_something = Count(....)))) .get(id=<b_id>) I've tried this way, but it does not work a_qs = [ab.a for ab in b_obj.ab_set.all()] for a in a_qs: print(a.count_something) error: "A" object has no attribute 'count_something' What is the correct way to achieve what I want? -
I cannot deploy my app. It keeps crashing. I dont know why
Tried to deploy my railway app via django. But it wont post and crashes instead. No idea why my railway app keeps crashing. Only error I see is for TK, which i verified is installed. What is the problem? Here is the log: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/app/api_tutorial/wsgi.py", line 16, in <module> application = get_wsgi_application() ^^^^^^^^^^^^^^^^^^^^^^ File "/opt/venv/lib/python3.11/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/opt/venv/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/root/.nix-profile/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/app/drinks_app/models.py", line 1, in <module> from turtle import width File "/root/.nix-profile/lib/python3.11/turtle.py", line 107, in <module> import tkinter as TK File …