Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SystemCheckError when running makemigrations for Wagtail models
I'm trying to create migrations for my Wagtail models, but I encountered a SystemCheckError with some fields.E304 and fields.E305 errors. I'm using Django with Wagtail to build my web application, and the specific error message is as follows: SystemCheckError: System check identified some issues: ERRORS: app.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'app.HomePage.page_ptr' clashes with reverse accessor for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. app.HomePage.page_ptr: (fields.E305) Reverse query name for 'app.HomePage.page_ptr' clashes with reverse query name for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'home.HomePage.page_ptr' clashes with reverse accessor for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E305) Reverse query name for 'home.HomePage.page_ptr' clashes with reverse query name for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. I have a Django project with two Wagtail models: HomePage in the app app and HomePage in the home app. Both models inherit from the Wagtail Page model. I added some custom fields to each model, and the HomePage model has an additional field called … -
Build a backend in django from scratch without using ORM [closed]
I'm required to build a simple api but I'm not to use any ORM while using relational db. I have to do authentication as well. I am stuck even after some research and don't know how to aproach this. I have been doin django with ORM, and maybe DB first aproach is the go to here but still is there a way to create tables directly from django without getting models, involved? -
How to run a query with group by over a 'select_related' field in django ORM
I'm developing a reservations system and on my database I have Products, different Items of the products and orders related to specific items. The intention is to get the list of available items of an specific product that are not already reserved between two dates. These are my models: class Product(models.Model): # Aqui se almacenaran los modelos name = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) stock = models.IntegerField() def __str__(self): return self.name class Item(models.Model): # Aqui se almacenaran las matriculas especificas disponibles name = models.CharField(max_length=50, unique=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return f"{self.product.name} - {self.name}" class Order(models.Model): status = models.CharField(max_length=50) item = models.ForeignKey(Item, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() notes = models.TextField(max_length=2000, null=True, blank=True) assigned_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.item.name} - {self.start_date} - {self.end_date}" After some tests in SQL in the database, I've reached the following query that gives me the expected result: SELECT calendarapp_item.id, calendarapp_item.product_id as product, count(orders.id) AS active_orders FROM calendarapp_item LEFT JOIN (SELECT * FROM calendarapp_order WHERE start_date<='{}' AND end_date>='{}' AND status='completed') AS orders ON orders.item_id=calendarapp_item.id GROUP BY calendarapp_item.id HAVING active_orders=0 and product={} I would like to translate this query to Django ORM in order … -
Return field value when referencing model instance
If I have the following Model: class VATPercentage(models.Model): percentage = models.IntegerField(default=21) Is there anyway I can make it so that when you reference an instance of it, you actually get the value stored in the percentage field? For example, I want to be able to do: Service.vat_percentage instead of Service.vat_percentage.percentage Similar to how _ str _ would work if you called str() on the model, but I need an integer.. I tried to look for something similar like defining an _ int _ function but i dont think thats a thing.. -
Django, user confirmation with try and except
I am facing an error with a function that needs the confirmation that a user is there. Here is the code in views.py: Imports: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User The view: def (enclosed)View(request, creator_username): try: creator = get_object_or_404(User, username=creator_username) except User.DoesNotExist: messages.error(request, "Creator not found.") return redirect("homepage") # Redirect to some error page or homepage The error: Class 'User' has no 'DoesNotExist' member I have tried adding the "get_object_or_404" but it still doesn't work. I don't know any other way to get it to work. -
aws ssh server connect port 22: operation timed out
I am working on this tutorial (https://testdriven.io/blog/deploying-django-to-ecs-with-terraform/#nginx)and while I was following the steps, I tried to connect all of my instances via ssh by following these instructions (https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/). And by following the section where it starts by "connecting to an instance using EC2 Instance Connect", I typed in "$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id i-0989ec3292613a4f9 --availability-zone us-east-1f --instance-os-user ec2-user --ssh-public-key file://mynew_key.pub {" command on the terminal to push the public key to the instance using the send-ssh-public-key. After that, I tried to connect to the instance using the associated private key: $ ssh -I mynew_key ec2-user@ec2-34-204-200-76.compute-1.amazonaws.com". And it successfully worked out and I came to the end of the deploying Django tutorial. But when I was testing whether it properly connects to the server using the "http://(load balancer IP)" template, I kept getting a "503 service unavailable" error. So, I fixed the issue by changing the inbound rule sources to "0.0.0.0/0", but after that, it still gave me a "502 Bad Gateway" error. To find where the issue was happening, I checked whether the instances were connected properly and it gave me an error saying "ssh: connect to host xx port 22: Operation timed out". To resolve this, I … -
sqlite3 Database file is not visible in pycharm after migrate
enter image description herePycharm IDE is not generating database file I have followed all the commands correctly First I used -- > python manage.py makemigrations reels Yes it created a file like 0001_initial.py, After that I tried to migrate your text using ---> python manage.py migrate But the database file is not showing anything, I don't see anything there. Can someone please help me. -
How to create a mixin for `django_filters.FilterSet`?
I have a bunch of FilterSets to which I'd like to add the same new filters, but whenever I do something like below, I get an error saying that FilterSet.Meta must specify a model. E.G: class ModifiedAtMixin: modified_at_until = django_filters.DateTimeFilter(method="modified_until") def modified_until(self, queryset, name, value): return queryset.filter(modified_at__lte=value) class Meta: fields = ("modified_at_until",) class FooFilterSet(ModifiedAtMixin, django_filters.rest_framework.FilterSet): created_at_until = django_filters.DateTimeFilter(method="created_until") def created_until(self, queryset, name, value): return queryset.filter(created_at__lte=value) class Meta: model = Foo fields = ModifiedAtMixin.Meta.fields + ("created_at_until",) For reference, I also tried changing the order of parent classes in FooFilterSet and got nothing. How can I created a reusable mixin such as ModifiedAtMixin -
Editable frontend solution for a 2d array in a Django form
I am building a Django app, where a model "Foo" has a ManyToMany relation with "Bar" like this: Foo(Model): [field1] [field2] ... Bar(Model) [general_field1] [general_field2] ... FooBar(Model) ForeignKey(Foo) ForeignKey(Bar) [specific_field1] [specific_field2] ... The main model is Foo. I display each Foo in a template with it's fields and a 2D list of FooBars with general and specific fields (ordered list with several FooBars on each line). I need a solution to save this to the database (Problem 1) and more importantly to create a form or custom input fields for the user to populate it (Problem 2). The user should see (after the input fields for the Foo fields) some kind of blank list. There should be a search field with prerendered Bar models beneath it. As the user types in the search field the results beneath it are filtered. If the user selects a Bar a modal should open with fields to populate the "specific" fields for the actual FooBar (the general fields of the Bar are preset). After that the FooBar should appear in the list and the process continues. If the search result is blank (the user can't find the desired Foo) a "Create new Foo" option … -
Can not upload image
I try to upload an image in Django but I can't. I don't know what is the problem. The error: django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/media/uploads/87176296b7b2425e81e266eaed65019b.png' Bad Request: /api/upload_file/ Bad Request: /api/upload_file/ [03/Aug/2023 17:47:52] "POST /api/upload_file/ HTTP/1.1" 400 17430 /api/upload_file: def upload_file(request): request_file = request.FILES['file'] if 'file' in request.FILES else None if request_file is None: data={ "error": "No file", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) if request_file.size > 20*1024*1024: data={ "error": "Image file too large (>20mb)", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) allowed_file_types = ['jpeg', 'jpg', 'png'] file_type = imghdr.what(request_file) if file_type not in allowed_file_types: data = { "error": "Invalid file type", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) upload = Upload(image=request_file) upload.save() data = { "upload_id": upload.id, } return Response(status=status.HTTP_200_OK, data=data) The Upload model: class Upload(models.Model): image = models.ImageField( verbose_name="Image", upload_to=path_and_rename_upload, ) patient = models.ForeignKey( "users.Patient", verbose_name="Patient", related_name="uploads", on_delete=models.SET_NULL, null=True, blank=True, ) upload_date = models.DateTimeField( verbose_name="Upload Date", auto_now_add=True, ) def __str__(self): return self.image.name @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename) -> str: ext = filename.split(".")[-1] filename = f"{uuid4().hex}.{ext}".lower() return os.path.join(self.path, filename) path_and_rename_upload = PathAndRename("/media/uploads") I tried making the path BASE_DIR/self.path/filename but didn't make any differences. My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] if not DEBUG: … -
Trying to make a Roster class out of a Player class (in Django), Help! This is for a class assignment
Working on my models.py for my Team manager app and I can't figure out how to layout my class for a roster. I am new to Django so any help is greatly appreciated. The idea is to have the players on the team but then having a roster to show who is playing which game. Here's what I have so far: class Player(models.Model): player_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) cap_number = models.CharField(max_length=45, blank=True, default='') def __str__(self): result = '' if self.cap_number == '': result = '%s, %s' % (self.last_name, self.first_name) else: result = '%s, %s (%s)' % (self.last_name, self.first_name, self.cap_number) return result class Meta: ordering = ['last_name', 'first_name', 'cap_number'] constraints = [ UniqueConstraint(fields=['last_name', 'first_name', 'cap_number'], name='unique_player') ] class Roster(models.Model): roster_id = models.AutoField(primary_key=True) roster_name = models.CharField(max_length=45) player = models.ManyToManyField(Player) def __str__(self, data=None): return f'{self.roster_name} - {self.player}' class Meta: ordering = ['roster_name', 'player'] And this is the error I get when I try to run makemigrations: ERRORS: organizer.Roster: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'player'. Do I have to make another class to put the players into a list? -
Is python zipfile save to aws s3 bucket
Is anyone know that the location of zipfile created in python can be changed to aws s3 bucket? For now, my zipfile is created in my root folder. I know that I can add the directory path to the begin of the file name to change the create location, but how about s3 bucket? -
i am getting following error when i tried to create a django project ? i am using python 3.11 with pip 23.2.1 ? Any help is appreciated
i am trying to create a django project but i am not able to create it. $ django-admin startproject web Fatal error in launcher: Unable to create process using '"C:\Users\laupha\AppData\Local\Programs\Python\Python311\python.exe" "C:\Users\laupha\AppData\Local\Programs\Python\Python311\Scripts\django-admin.exe" startproject web': The system cannot find the file specified. -
AttributeError: 'Command' object has no attribute 'scriptable'
After updating Django 3->4.2.4 One of my UpdateView shows 'SomeModel' instance needs to have a primary key value before this relationship can be used. I think there could be some model need migrate ./manage.py makemigrations --dry-run File "/Users/user/Git/erp/venv/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 99, in log_output return self.stderr if self.scriptable else self.stdout ^^^^^^^^^^^^^^^ AttributeError: 'Command' object has no attribute 'scriptable' -
TypeError at / Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000025FE3733310>>
Im trying to make my openai chatbot save chats for the user that is making them, but it is giving me this error: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\__init__.py", line 2053, in get_prep_value return int(value) ^^^^^^^^^^ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'SimpleLazyObject' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 29, in chatbot chats = Chat.objects.filter(user=request.user) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( ^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1480, in build_filter condition = self.build_lookup(lookups, col, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1307, in build_lookup lookup = lookup_class(lhs, rhs) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan … -
How to solve error while running pip install mysql on MAC( Exception: Can not find valid pkg-config name)
Already tried re-installing everything. still got this message /bin/sh: pkg-config: command not found /bin/sh: pkg-config: command not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 323, in _get_build_requires self.run_setup() File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 338, in run_setup exec(code, locals()) File "", line 154, in File "", line 48, in get_config_posix File "", line 27, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. -
Django constraint for "field one not in field two for any row"?
Suppose I have a Django model with two fields one and two: class MyModel(models.Model): one = models.CharField(max_length=100, unique=True) two = models.CharField(max_length=100) unique=True means if I try to put in a row with one="one" when another such row already exists, a unique constraint will be violated. How would I make a Django constraint that says if there is a row with one="one", then I can't put in a row with two="one"? This does seem related to this question and this answer, but I don't quite see the answer to my question. -
How to override the templates of `django-two-factor-auth` for Django Admin?
I'm trying to override the templates of django-two-factor-auth for Django Admin but I don't know how to do it. *I don't have frontend with Django. Instead, I have frontend with Next.js and backend with Django. This is my django project: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-urls.py └-templates And, how I set django-two-factor-auth following the doc is first, I installed django-two-factor-auth[phonenumbers]: pip install django-two-factor-auth[phonenumbers] Then, set these apps below to INSTALLED_APPS, OTPMiddleware to MIDDLEWARE, LOGIN_URL and LOGIN_REDIRECT_URL in core/settings.py as shown below: # "core/settings.py" INSTALLED_APPS = [ ... 'django_otp', # Here 'django_otp.plugins.otp_static', # Here 'django_otp.plugins.otp_totp', # Here 'two_factor' # Here ] ... MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', # Here ... ] LOGIN_URL = 'two_factor:login' # Here # this one is optional LOGIN_REDIRECT_URL = 'two_factor:profile' # Here ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates', ], ... }, ] Then, set the path below to core/urls.py: # "core/urls.py" ... from two_factor.urls import urlpatterns as tf_urls urlpatterns = [ ... path('', include(tf_urls)) # Here ] Finally, migrate: python manage.py migrate And, this is Login page: http://localhost:8000/account/login/ My questions: How can I override the templates of django-two-factor-auth for Django Admin? Are there … -
Setting local time and date conversion in Python
I run the following code on the system and server and get different results How to set the time zone to get the same result regardless of the system or server settings print(datetime(2023,6,6,0,0).timestamp()) -
Steam OpenID dj-rest-auth dont return access token
urls.py from django.contrib import admin from django.urls import path, include, re_path from rest_framework.routers import SimpleRouter from store.views import CaseViewSet, auth, GoogleLogin, VkLogin from .settings import STEAM_CALLBACK_URL from allauth.socialaccount.providers.steam.views import SteamOpenIDLoginView import allauth router = SimpleRouter() router.register(r"case", CaseViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('auth/google/', GoogleLogin.as_view(), name='google_login'), path("auth/vk", VkLogin.as_view(), name = "vk_login"),\ path("auth/steam", SteamOpenIDLoginView.as_view(), name = "steam_login"), path('auth/steamcallback', allauth.socialaccount.providers.steam.views.SteamOpenIDCallbackView.as_view(), name = STEAM_CALLBACK_URL), ] urlpatterns += router.urls in this code i create 2 endpoints. I open page and login with steam openid and it return dont JWT . -
SMTPServerDisconnected in Google App Engine Standard (but it works in Flexible)
I am trying to switch my Django (Python) app from from GAE Flexible environment to Standard. Everything works fine except sending emails via gmail SMTP. It works with a version in flexible env, but it doesnt work in the same code with standard. my app.yaml file includes inbound_services: - mail - mail_bounce My settings is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'hidden@hidden.com' EMAIL_HOST_PASSWORD = 'hidden' DEFAULT_FROM_EMAIL = 'hidden@hidden.com' SERVER_EMAIL = 'hidden@hidden.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True The strange thing is that SMTP and the same email work fine in my other project with GAE standard with the same settings. -
Django i18n cannot use translated text in a dict
I am unable to store the translated texts in a dict class TestAPIView(APIView): def get(self, request): return Response({'msg': _("My error msg")}) The code above works. However when I tried to put the text into a dict. msg = { 123 : _("My error msg") } class TestAPIView(APIView): def get(self, request): return Response({'msg': msg[123]}) This doesn't translated the text. I have tried rerunning the makemessages and compilemessages, but it doesn't help. Any help? -
im trying to test this but it dont work pls help in django python
i dont know how to test this, pls can you guys find a way to test this i dont get it and i dont find videos on youtube aswell.I'm pretty new to this and so stressed because im so bad at programming right now. @login_required def update_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) form = BillingForm(instance=user) if request.method == "POST": form = BillingForm(instance=user, data=request.POST) if form.is_valid(): user = form.save() return redirect('show_billing_information') ctx = {"form": form} return render(request, "customer/_billing_edit.html", ctx) @login_required def show_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) ctx = {"user": user} return render(request, "customer/_billing_show.html", ctx) and chatgpt gave me this shit User = get_user_model() class BillingInformationTestCase(test.TestCase): def setUp(self): self.user = User.objects.create_user(email='Testuser32@gmail.com', password='testpassword', dob = date(1990, 1, 1)) self.factory = test.RequestFactory() self.client = Client() self.client.force_login(self.user) def test_update_billing_information_valid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : 'Tim', "last_name" : 'Herb', "address1" : '123 Main Street', "address2" : 'Apt 2B', "city" : 'New York', "state" : 'Ny', "zip" : '12345', } request.POST = form_data response = update_billing_information(request) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/views/customer/billing') def test_update_billing_information_invalid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : '', "last_name" : '', "address1" … -
mod_wsgi with two python versions
I have an Ubuntu-18.04 LTS EC2 serving a django application with mysql Ver 8.0.16, Apache/2.4.29 and mod_wsgi/4.6.5complied withpython3.6. Now, I am targeting to deploy a new django application in the same Ubuntu EC2 serve and it requires python3.11+ virtualenv for installing its requirements.txt, now i am facing issues while deploying the new application. here are few other informations, Using Pyenv for creating virtualenvs, mod_wsgi is installed from source and compiled using ./configure --with-python=/home/ubuntu/.pyenv/shims/python3.6 after deploying the new django application the domain returns 500 error and logs are as follows api.log [03/Aug/2023:18:42:14 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 api_error.log [Thu Aug 03 18:43:18.047679 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Failed to exec Python script file '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047724 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Exception occurred processing WSGI script '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047795 2023] [wsgi:error] [pid 170353:tid 140404074731072] Traceback (most recent call last): [Thu Aug 03 18:43:18.047810 2023] [wsgi:error] [pid 170353:tid 140404074731072] File "/var/www/project/newdjango/wsgi.py", line 12, in <module> [Thu Aug 03 … -
Pycharm is not allowing me to make a password for a super user on my Django project
I am trying to create a superuser on the terminal on pycharm but It's not typing anyting when I try to create a password for that superuser in the terminal. I tried to recall the command "python manage.py createsuperuser" a few times but I still ran into the same issue. I was expecting it to type in the password, but no matter what I type it's not typing anything. I am following this tutorial: Python Tutorial-Python Full Course For Beginners and my issue is at 5 hrs and 38 mins. I am able to type in the username and email, but just not the password.