Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
exporting data from sqlite database to postgress database in django
i wanted to transform my data from sqlite database onto posgres database in django. first of all i write the command: python -Xutf8 .\manage.py dumpdata --indent=4 --output=data.json to exporting data (in utf-8 encode) in a json file. everything was good and data exported properly, but when i want to import data in postgres (after configuration in settings.py) so i used python .\manage.py loaddata data.json and got this error: django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\Bardia\Desktop\webapp\data.json': Could not load contenttypes.ContentType(pk=7): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(blog, post) already exists. can anyone help my in this situation? thanks a lot loading data in new postgres database in django -
Is the __unicode__ method still required for a dynamic Django model? [duplicate]
I found code in our codebase that defines a __unicode__ dunder method for a dynamically created Django model. We are using Python 3.11 and Django 4.2. Is the __unicode__ method still required? Here is the code snippet: from typing import Type from django.db import models MODEL_NAME = "MyReport" MODEL_FIELDS = ["field1", "field2"] type( MODEL_NAME, (models.Model,), { "__module__": __name__, "__unicode__": lambda _: MODEL_NAME, **{ field_name: models.Field() for field_name in MODEL_FIELDS }, }, ) I've read __str__ versus __unicode__, but the question dates back to 2009 and the answers are mostly outdated. -
Captcha solving using Python
I am trying to extract values from below CAPTCHA image but my code is giving me output as none. I am getting empty string as output. I have tried using below code. While it was working fine with below image. def read_captcha(): ptes.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' try: img = cv2.imread('ss.png', 0) img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] imagetext = ptes.image_to_string(img) except TypeError: imagetext="a b" l = imagetext.split() s = "" for i in range(len(l)): s += l[i] if len(s)>0: return s else: return ""` -
Add button for django formset
I'm starting to use Django 5 and I'm building a web project to organize a Secret Santa gift exchange. My problem is that when using formsets, they are not dynamic, so I can't create a variable number of forms at the user's request. I have this form: class ParticipanteForm(forms.ModelForm): class Meta: model = Participante fields = ['nombre', 'email'] ParticipanteFormSet = formset_factory(ParticipanteForm) This model: class Participante(models.Model): sorteo = models.ForeignKey(Sorteo, related_name='participantes', on_delete=models.CASCADE) nombre = models.CharField(max_length=100) email = models.EmailField() And this view where I render the forms and save the data: def crear_sorteo(request): sorteo_form = SorteoForm(request.POST or None) ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3) participante_formset = ParticipanteFormSet(request.POST or None) context = { 'sorteo_form': sorteo_form, 'participante_formset': participante_formset, } if request.method == 'POST': if sorteo_form.is_valid(): sorteo = sorteo_form.save() # Save the draw first if participante_formset.is_valid(): for participante_form in participante_formset: participante = participante_form.save(commit=False) participante.sorteo = sorteo # Assign the draw to the participant participante.save() return render(request, 'sorteo_realizado.html') return render(request, 'crear_sorteo.html', context) As you can see, ParticipanteFormSet = formset_factory(ParticipanteForm, extra=3) depending on the number of extra you specify, that will be the number of forms that will be created. But I would like in the template: <body> <form action="" method="post"> {% csrf_token %} {{ sorteo_form }} {{ participante_formset.management_data }} … -
delete instance of factory boy from another one
I have two FactoryBoy and I tried to delete the first one from the second, What I want to accomplish is when I delete a ShareLinksFactory instance, the associated WebShareFileFactoryBoy and its corresponding file should also be deleted. Below is the class ShareLinksFactory: class ShareLinksFactory(factory.django.DjangoModelFactory): class Meta: model = ShareLinks id = factory.LazyFunction(create_id) web_share_file_folder = factory.SubFactory(WebShareFileFactoryBoy) create_user = UuidCifsUsers.objects.get(cifs_user='user_test').id limit_datetime = factory.LazyFunction(lambda: timezone.now() + timedelta(days=30)) created_by_factory = True WebshareFileFactoryBoy class WebShareFileFactoryBoy(factory.django.DjangoModelFactory): class Meta: model = WebShareFileFolders django_get_or_create = ('inode',) name = factory.Faker('file_name', extension='txt') path = factory.Faker('name') inode = factory.Faker('random_number') is_dir = False @factory.post_generation def create_file_on_disk(self, create, extracted, **kwargs): self.name = self.name + str(uuid.uuid4())[:6] # these permit to make a unique name for the file automatic_folder_path = os.path.join(NAS_PATH, 'Share/automatic/') Path(automatic_folder_path).mkdir(parents=True, exist_ok=True) full_path = os.path.join(automatic_folder_path, str(self.name)) file_size_mo = kwargs.pop('file_size_mo', None) with open(full_path, 'w') as file: file.write( f'Name: {self.name} \n' f'Is a folder: {self.is_dir} \n' f'make with love: True \n' f'where: {full_path}' ) if file_size_mo: file_size = file_size_mo * 1024 * 1024 file.seek(file_size - 1) file.write('\0') self.inode = os.stat(full_path).st_ino self.path = 'Share/automatic/' + str(self.name) self.save() std, err, code = popen_wrapper([ 'sudo', '/set_webshare_extattr.sh', str(self.id), full_path ]) I try to overide the delete function from the class but I get an error django.core.exceptions.FieldError: Invalid field … -
In Django, why is my JSONFormField generating a style 'display: none'?
I am using django_jsonform (2.22.0) with django (4.2.11) to edit a configuration file written in JSON. I have verified the schema is correct and I can use it with the playground (https://bhch.github.io/react-json-form/playground/). When I egnerate the form, I print the form output and it has 'style "display: none"' emedded in it. from pathlib import Path from django import forms from django_jsonform.forms.fields import JSONFormField from testsite import settings class ConfigurationForm(forms.Form): configuration = JSONFormField(schema=Path(settings.CONFIG_ROOT) / 'config2.schema.json') def configuration(request: Request): if request.method == "POST": form = ConfigurationForm(request.POST) if form.is_valid(): return HttpResponseRedirect("/thanks/") else: with open(Path(settings.CONFIG_ROOT) / 'config.json') as configFile: data = json.load(configFile) form = ConfigurationForm(initial={'configuration': data}) print(f'form data = {form}') return render(request, "admin/preferences/preferences.html", context={"form": form}) The print(f'form data = {form}') statment produces this: form data = <tr> <th><label for="id_configuration">Configuration:</label></th> <td> <div data-django-jsonform-container="true" class="django-jsonform-container"></div> <textarea cols="40" id="id_configuration" name="configuration" rows="10" style="display: none;" data-django-jsonform="{&quot;data&quot;: &quot;{ <!-- sensitive data removed --> }&quot;, &quot;schema&quot;: {}, &quot;fileHandler&quot;: &quot;&quot;, &quot;fileHandlerArgs&quot;: {&quot;field_name&quot;: &quot;configuration&quot;, &quot;model_name&quot;: &quot;&quot;}, &quot;errorMap&quot;: {}, &quot;validateOnSubmit&quot;: false, &quot;readonly&quot;: false}"></textarea> </td> </tr> So what am I doing wrong? -
Django Templates - How can I have correct Root vs App Lookup
How can I have view load the templates from the corresponding app (root vs child)? Here's the full structure: Create django project - universe Created an app - let's call it earth. Created a (container) template for / -> universe/universe/templates/main.html Created a (container) template for /earth -> universe/earth/templates/main.html Created a (content) template for / and /earth at universe/universe/templates/index.html and universe/earth/templates/index.html respectively. In universe/universe/views.py, I have: from django.shortcuts import render def index(request): context = {} return render(request, 'index.html', context) In universe/earth/views.py, I have the same: from django.shortcuts import render def index(request): context = {} return render(request, 'index.html', context) When I run this, I get an error TemplateDoesNotExist at /. Why are templates not found? If I update universe/universe/settings.py TEMPLATES = [ ... 'DIRS': [ BASE_DIR / 'universe/templates' ] ] only the universe templates are picked up. How can I ensure that when I refer to the correct index.html based on the app? -
Logged out redirection
If I press Enter using http://127.0.0.1:8000/dashboard/ after logged out I am redirecting to http://127.0.0.1:8000/login/?next=/dashboard/. How can I redirect to http://127.0.0.1:8000/login/ after logged out by press Enter ? -
Limit the dropdown to logged in user for a table field
My tables are: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, ) address_line_1 = models.CharField(max_length=200,blank=True) class ProfileCar(models.Model): profile = models.ForeignKey(Profile,on_delete=models.CASCADE) car_model = models.ForeignKey(CarModel,on_delete=models.CASCADE) class AvailableRide(models.Model): profilecar = models.ForeignKey(ProfileCar,on_delete=models.CASCADE) ride_route = models.ForeignKey(Route,on_delete=models.CASCADE) ride_datetime = models.DateTimeField(default=timezone.now) In AvailableRide table, when running it, it shows the complete list of profilecar values, meaning all the users get listed. I want to limit this list to only logged in user. The list needs to be limited to logged in user only, who has onetoone profile record. -
Django: Generate multiple random time
I have Schedule class which has dates, routes and time. I have a problem generating random time. I saw this, (Create random time stamp list in python), but it only generate random time which only has minutes gap each. This is how I did mine, which is just very simple: no_of_route = int(request.POST.get('no_of_route')) time = random.sample(range(1, 24), no_of_route) But this one is just a whole number, I wanted to have results like 9:30, 1:45, and so on. There is no need of min and max time. Is this possible? I'm new to this, so I'm not sure how to do it exactly. Thank you for your help. -
How to publish a page in Wagtail CMS?
I'm trying to publish a page in Wagtail CMS, but I'm having trouble with the publishing process. I can access the Wagtail admin interface, but I can't seem to find the "Publish" button in the preview mode.The root page ("Welcome to your new Wagtail site!") is visible, but the page I created is not. Here are the steps I've taken: Created a new page in the Wagtail admin interface. Edited the page content and saved it as a draft. Tried to preview the page, but there's no "Publish" button in the preview mode. I've also tried going to the "Pages" section in the admin interface, finding the page I created and got to the promote and edit the slug as test1, when I go to the link with slug, I get the following error: Page not found (404) Request Method: GET Request URL: https://chat-jj.pythonanywhere.com/test1/ Raised by: wagtail.views.serve Using the URLconf defined in PyChat.urls, Django tried these URL patterns, in this order: admin/ documents/ _util/authenticate_with_password/<int:page_view_restriction_id>/<int:page_id>/ [name='wagtailcore_authenticate_with_password'] _util/login/ [name='wagtailcore_login'] ^((?:[\w\-]+/)*)$ [name='wagtail_serve'] The current path, test1/, matched the last one. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display … -
How to get data from django database model
What I did: views.py class CandidateView(View): def get(self, request, **kwargs): pk = kwargs['pk'] candidates = Resume.objects.get(pk=pk) posts = Post.objects.all().values() post_contents = [] for post in posts: if isinstance(post, dict) : continue elif isinstance(post, Post): post_contents.append(post.content) return render(request, 'blog/candidate.html', {'candidate':candidates, 'posts': post_contents}) models.py class Resume(models.Model): name = models.CharField(max_length=100) dob = models.DateField(auto_now=False, auto_now_add=False) gender = models.CharField(max_length=100) locality = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.PositiveIntegerField() state = models.CharField(choices=STATE_CHOICE, max_length=50) mobile = models.PositiveIntegerField() email = models.EmailField() job_city = models.CharField(max_length=50) profile_image = models.ImageField(upload_to='profileimg', blank=True) my_file = models.FileField(upload_to='doc', blank=True) blog_post = models.CharField(max_length=100000) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='posts', null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I'm new to Django and I want to get my blog content from Post model to CandidateView. Main idea is getting all the blog content and showing it into resume. but I cant figure it out how to do it or what I am doing wrong. -
Why does adding `only()` to my queryset cause an N+1?
I have a Django queryset called qs. When I evaluate it, it executes the following SQL query: SELECT "projects_issue"."id", "projects_issue"."name", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."milestone_id" = 1 ORDER BY "projects_issue"."name" ASC LIMIT 21 Now I only want to select the id field, so I evaluate qs.only("id"). This executes more than one query: SELECT "projects_issue"."id" FROM "projects_issue" WHERE "projects_issue"."milestone_id" = 1 ORDER BY "projects_issue"."name" ASC LIMIT 21 SELECT "projects_issue"."id", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."id" = 1 LIMIT 21 SELECT "projects_issue"."id", "projects_issue"."milestone_id" FROM "projects_issue" WHERE "projects_issue"."id" = 2 LIMIT 21 The extra queries are an N+1, executing a query for each returned item in the queryset. I don't have any Django signals registered. What could be causing these extra queries? Is there anything I can look for in the queryset to introspect it and understand this behaviour better? -
Django restframework user email already exists error
I am trying to write a login view in django restframe work to authenticate a user into the application but each time I send a request to the server I keep getting this error `{ 'email': ['email already exist'] }`` here is how I wrote my login serializer class UserLoginSerializer(serializers.ModelSerializer): full_name: str = serializers.CharField(source='get_name', read_only=True) tokens: str = serializers.CharField(source='get_token', read_only=True) class Meta: model = User fields = ( 'id', 'full_name', 'email', 'password', 'is_superuser', 'is_seller', 'created_at', 'profile_pic', 'tokens' ) extra_kwargs = { 'password' : {'write_only':True, 'required': True}, 'id': {'read_only': True}, 'is_superuser': {'read_only': True}, 'is_seller': {'read_only': True}, 'created_at': {'read_only': True}, 'profile_pic': {'read_only': True} } def validate(self, data: dict) -> dict: email: str = data.get('email', '') password: str = data.get('password', '') print(password, email) user: auth = auth.authenticate(email=email, password=password) print(user) data = { 'email': user.email, 'tokens': user.get_token() } return data and here is how I wrote my loginapiview class UserLoginAPIView(generics.GenericAPIView): serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) -
"error": "invalid_client" django-oauth-toolkit with grant_type = 'authentication_code'
So, i'm following this tutorial to apply oauth2 in my django project I handled to get an client_id, secret, code_verifier and code as it is described in the tutorial but then the tutorial asks the following: Now that you have the user authorization is time to get an access token: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=${ID}" -d "client_secret=${SECRET}" -d "code=${CODE}" -d "code_verifier=${CODE_VERIFIER}" -d "redirect_uri=http://127.0.0.1:8000/noexist/callback" -d "grant_type=authorization_code" I tried everything, checked the credentials 100 of times but the terminal output is always: {"error": "invalid_client"} I can't see what is wrong -
issue while trying to install misaka
Collecting misaka Using cached misaka-2.1.1.tar.gz (125 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: cffi>=1.0.0 in c:\users\owner\appdata\local\programs\python\python39\lib\site-packages (from misaka) (1.16.0) Requirement already satisfied: pycparser in c:\users\owner\appdata\local\programs\python\python39\lib\site-packages (from cffi>=1.0.0->misaka) (2.22) Building wheels for collected packages: misaka Building wheel for misaka (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [27 lines of output] c:\users\owner\appdata\local\programs\python\python39\lib\site-packages\setuptools_init_.py:81: _DeprecatedInstaller: setuptools.installer and fetch_build_eggs are deprecated. !! ******************************************************************************** Requirements should be satisfied by a PEP 517 installer. If you are using pip, you can try `pip install --use-pep517`. ******************************************************************************** !! dist.fetch_build_eggs(dist.setup_requires) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-39 creating build\lib.win-amd64-cpython-39\misaka copying misaka\api.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\callbacks.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\constants.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\utils.py -> build\lib.win-amd64-cpython-39\misaka copying misaka\__init__.py -> build\lib.win-amd64-cpython-39\misaka running build_ext generating cffi module 'build\\temp.win-amd64-cpython-39\\Release\\misaka._hoedown.c' creating build\temp.win-amd64-cpython-39 creating build\temp.win-amd64-cpython-39\Release building 'misaka._hoedown' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for misaka Running setup.py clean for misaka Failed to build misaka ERROR: Could not build wheels for misaka, which is required to … -
How can do reset password with django and angular
i don t know what is the problem exactly i try only with backend everything works any solutions pls ? i want when the user try to connect can click on reset password after that they enter the email and they will receive the email How can do reset password with django and angular How can do reset password with django and angular How can do reset password with django and angular How can do reset password with django and angular -
Refresh JWT Tokens using PyJWT
Upon using a login system bases on authentication tokens stored in cookies, I am encountering issues while trying to refresh the token without using login and password again. Is it possible to refresh the jwt tokens using PyJWT ? def get(self, request): token = request.COOKIES.get('userJwt') if token is None: raise AuthenticationFailed('Unauthenticated!') response = Response(status=200) try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: # payload['exp'] = datetime.utcnow() + timedelta(seconds=20) # new_token = jwt.encode(payload, "secret", algorithm="HS256") # response.set_cookie(key='userJwt', value=new_token, httponly=True) return Response({"message": "Expired"}, status=200) user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) response.data = serializer.data return response -
Django view function returns status code 302 when using @login_required decorator
In my views.py file in my Django app, I use the @login_required decorator for every method in the file. When the user logs in, all method function normally except for one, the getFields method. I cannot put my hand one what is going wrong regarding this one method. when I remove the @login_required decorator is functions normally. Why is it not detecting that the user is logged in for that one method? View function: @login_required def getFields(request): try: POST = json.loads(request.body) fields = Field.objects.all() field_list = [] for field in fields: field_list.append(field.to_dict()) print(field_list) return JsonResponse({ 'status': 200, 'fields': field_list }) except(ObjectDoesNotExist): return JsonResponse({ 'status': 404 }) urls.py: from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.login,name="login"), path('logout', views.logout,name='logout'), path('editProfile', views.editProfile,name='EditProfile'), path('createTable',views.creatTable,name="createTable"), path("accounts/", include("django.contrib.auth.urls")), path('signup',views.signup,name="signup"), path('forgotPassword',views.forgotPassword,name="forgotPassword"), path('getTable', views.getTable, name="getTable"), path('modifyrow', views.modifyrow, name="modifyrow"), path('deleteRow', views.deleteRow, name="deleteRow"), path('addColumn', views.addColumn, name="addColumn"), path('deleteColumn', views.deleteColumn, name='deleteColumn'), path('EditColumn', views.EditColumn, name='EditColumn'), path('getExperts', views.getExperts, name='getExperts'), path('sendemail', views.sendemail, name='sendemail'), path('getFields', views.getFields,name='getFields'), path('createExpert', views.createExpert,name='createExpert'), Calling the method using javascript: try{ const response = await fetch(`http://127.0.0.1:8000/getFields`,{ method:'GET', headers:{ 'Content-Type': 'application-json', 'X-CSRFToken': Cookies.get('csrftoken'), }, credentails: 'include' }) -
Check if payment is complete in Django Template
I use django with jinja tempates + frontend. I need to connect QR Code to pay products in the cart. I use official Bank API to create payment, but there is no redirect URL after successed payment, so I need to empty the user's cart after successful payment, but I don't know how. Cart is working on frontend with localStorage and frontend clear cart when user go to payments/success url. But with this method I can't redirect user to this url because QR Code does not support it. How can I check if the payment is successfully done and frontend can clear user's cart? To be clear, Bank API send callback when the payment is completed, but I don't think if its can help with my problem I've seen QR code payment on other sites, they somehow knew my payment was successful and showed me a notification + emptied my cart. -
coding error when adding a category via the admin panel
I have created a database for categories, an error appears when adding: IntegrityError at /admin/goods/categorymodel/add/ ������������: INSERT ������ UPDATE �� �������������� "django_admin_log" ���������������� ���������������������� ���������������� ���������� "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: �������� (user_id)=(5) ���������������������� �� �������������� "auth_user". I was redefining a custom model to my own I have also redefined email or username authorization backends.py: class UserModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get( Q(username=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: return None except MultipleObjectsReturned: return UserModel.objects.filter(email=username).order_by('id').first() else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None the error occurs when I try to add a category how can I fix the error? Django: 4.2.11 Python: 3.11.8 I found information about redefining authorization, but it didn't help -
i need help django-pytest invalid token error due to fixtures or token generator
fixtures.py, this is where my fixtures are located from django.test import Client from pearmonie.auth.models import User from pearmonie.settings.models import BusinessSettings import pytest @pytest.fixture def BASE_URL(): return "http://localhost:8000" @pytest.fixture def user_sub_info(): return {"email": "a@gmail.com", "fcm_token": ""} @pytest.fixture def user_info(): return { "phone": "+234955443322", "password": "Password.1", } @pytest.fixture def user_info_mail(): return { "phone": "+234955443322", "password": "Password.1", "email": "a@gmail.com", } @pytest.fixture(scope="session", autouse=True) def HTTP_AUTHORIZATION(): return {"HTTP_AUTHORIZATION": ""} @pytest.mark.django_db() def user(user_info, user_sub_info): user = User.objects.create(email=user_sub_info["email"], **user_info) BusinessSettings.objects.create(business_name="my store", user=user) return user @pytest.fixture(scope="session", autouse=True) def client(): return Client() @pytest.fixture def codes(): return { "otp": "000000", "transaction_pin1": "000000", "transaction_pin2": "111111", "pinId": "222222", } auth/tests.py import pytest from pearmonie.auth.models import Otp, User from pearmonie.auth.lambdas import gen_token from utils.fixtures import ( client, HTTP_AUTHORIZATION, BASE_URL, user_info, user_sub_info, codes, user_fixture, user_info_mail ) @pytest.mark.django_db def test_auth( client, BASE_URL, HTTP_AUTHORIZATION, user_fixture, user_info, user_sub_info, user_info_mail, codes ): client.login(**user_info) otp = Otp.objects.create(code=codes["otp"], pinId=codes["pinId"], user=user_fixture, is_verified=True) assert otp.code == codes["otp"] assert otp.is_verified token = gen_token(data = user_info_mail) HTTP_AUTHORIZATION["Authorization"] = token assert HTTP_AUTHORIZATION["Authorization"] == token password_reset_response = client.post( f"{BASE_URL}/auth/password/reset/", { "phone": user_info["phone"], "code": otp.code, "new_password": "HardPass@2022..", "fcm_token": user_sub_info["fcm_token"], }, **HTTP_AUTHORIZATION, content_type="application/json", ) assert password_reset_response.status_code == 200 assert password_reset_response.headers["Authorization"] @pytest.mark.django_db def test_transaction_pin(client, HTTP_AUTHORIZATION, BASE_URL, codes): check_pin_response = client.get( f"{BASE_URL}/auth/pin/check/", **HTTP_AUTHORIZATION, content_type="application/json", ) assert check_pin_response.status_code == 200 create_pin_response … -
beginner to django and need to know how to start off
Basically i started learning Django 2 weeks ago and went to a learning institute for that environment but the teacher for Django isn't sure himself how to explain since he is new to teaching and explaining to other people so i want your guys opinion on how to start off, to get some simple ideas on it. Like i have tried couple of videos on YouTube some tutorials asked CHATGPT couple of questions and "ETC" but none of them are close to that teachers teaching manner so it started to cause some confusion within me on what to find or what to do. -
502 Gateway Error AWS Elastic Beanstalk Django
I am trying to deploy a Django app to Elastic Beanstalk. I used AWS CodePipeline as my CI/CD process. The instance is able to successfully deploy, but when I click on the domain it gives me a 502 gateway error. I suspect this is from the Gunicorn server not running. My environment platform is Python 3.11 Linux 2023. I suspect that the Gunicorn is not running since it cannot find my WSGIPath because of the way my AWS CodePipeline is setup. AWS CodePipeline reads from my repository which has a 'node' folder (containing my frontend) and a 'python' folder (containing my Django app). My 'python/.ebextensions/django.config' contains the following configuration: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application I am guessing that my path is not set correctly since 'myproject' isn't at the root level. And so, I tried the following configuration as well: option_settings: aws:elasticbeanstalk:application:environment: PYTHONPATH: "/opt/python/current/app/python:$PYTHONPATH" DJANGO_SETTINGS_MODULE: myproject.settings aws:elasticbeanstalk:container:python: WSGIPath: myproject.wsgi:application This still gives me a 502 error so I am not sure where to proceed from here. I am confused as to how to properly set my PYTHONPATH so that 'myproject' is found. I cannot find the documentation as to what path the application files are stored. '/opt/python/current/' and '/var/app/current' come up … -
Django Site + Model Translation
I am working on a Django website and I want to have multiple languages for the website. The project has a model called Product. Product has 3 fields ( name, description and info ) that I would like to be translated for all of the Product Objects. I would also like to translate the static parts of the website ( navbar, footer, etc ). What would be the best approach to do that?