Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add multiple routers with different router class to the same endpoints in FastAPI
I have a /users route in my app which is initialized with a default router like this : (Note that responses and dependencies have been removed from the snippet to protect proprietary code) api_router = APIRouter( responses={}, route_class=LocalizationRoute, dependencies=[], ) Localization Route is being used directly from fastapi-localizationpackage for translation purpose. Now I want to add another router to the same route for the purpose of logging . This router is based on the following router class def log_info(req_body, res_body): print(req_body) print(res_body) class LoggingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Response: req_body = await request.body() response = await original_route_handler(request) if isinstance(response, StreamingResponse): res_body = b'' async for item in response.body_iterator: res_body += item task = BackgroundTask(log_info, req_body, res_body) return Response(content=res_body, status_code=response.status_code, headers=dict(response.headers), media_type=response.media_type, background=task) else: res_body = response.body response.background = BackgroundTask(log_info, req_body, res_body) return response return custom_route_handler I tried doing this by using includerouter clause like this : api_router.include_router(APIRouter(router_class= LoggingRoute)) But this is not working. I can see the router class is still set to Localization Route and the routerclass argument in include_router statement is ignored. So I was wondering do fast api not support adding multiple routers with different router class to the … -
mysql : The term 'mysql' is not recognized as the name of a cmdlet Of Code with Mosh's Ultimate Django Series
If you had been following The Ultimate Django Series by code with mosh and you got to the video : 4.Setting Up the Database -> 9- Using MySQL in Django and you get the following error in the console on windows : mysql : The term 'mysql' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. -
can't access certain file types in media file in django local server
when i try to acess a file with pdf or mp4 that exsit in the media folder using dirict link to the file `http://127.0.0.1:7500/media/1.pdf` the broswer just load forever with no errors but if i try to acess a jpg file in the same folder it works fine http://127.0.0.1:7500/media/1.jpg this will work and show the image i trid some sloutions like add this to the settings but same problem ALLOWED_FILE_TYPES = ['*'] . this is my confgration of the media folder in the settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIAFILES_DIRS = [os.path.join(BASE_DIR, 'mediafiles')] and i this is from the urls if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i also trid several browsers all gave me the same problem. i tried to run it on another pc that is using linux it works fine on the other pc but not on mine i'm using Windows DJANGO VERSION 4.2.2 -
Tailwind CSS classes not rendering on Nginx server but working on Gunicorn
I am facing an issue with my Django web application where the Tailwind CSS classes are not rendering when accessing the site through the Nginx server. Strangely, the Tailwind CSS classes are applied correctly when running the application using Gunicorn. I have carefully checked my static file configuration and confirmed that Nginx is properly serving other static files, such as images and JavaScript files. However, the Tailwind CSS classes seem to be the only ones not functioning as expected. Here is my current Nginx server block configuration: server { listen 80; server_name localhost; access_log /Users/curtwheeler/Documents/Django/Business/cookiecutters/base/base/var/log/nginx/access.log; error_log /Users/curtwheeler/Documents/Django/Business/cookiecutters/base/base/var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /static { root /Users/curtrosenblad/Documents/Django/Business/cookiecutters/base/base/base; } location /media { root /Users/curtrosenblad/Documents/Django/Business/cookiecutters/base/base/base; } } I have already checked the file permissions and ownership of the static files, and they appear to be set correctly. Additionally, during the collectstatic process, the Tailwind CSS files are being correctly copied to the static files directory. I suspect that there might be a misconfiguration or missing directive in my Nginx server block that is causing the issue. I would appreciate any guidance or suggestions on how to properly configure Nginx … -
'cross-env' is not recognized as an internal or external command, operable program or batch file
I'm working on a team in a django project with tailwind following by this set up tutorial https://django-tailwind.readthedocs.io/en/latest/installation.html. everything works find but when i'm starting tailwind py manage.py tailwind start. theme@3.5.0 start npm run dev theme@3.5.0 dev cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w 'cross-env' is not recognized as an internal or external command, operable program or batch file. here is package.json { "name": "theme", "version": "3.5.0", "description": "", "scripts": { "start": "npm run dev", "build": "npm run build:clean && npm run build:tailwind", "build:clean": "rimraf ../static/css/dist", "build:tailwind": "cross-env NODE_ENV=production tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css --minify", "dev": "cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w", "tailwindcss": "node ./node_modules/tailwindcss/lib/cli.js" }, "keywords": [], "author": "", "license": "MIT", "devDependencies": { "@tailwindcss/aspect-ratio": "^0.4.2", "@tailwindcss/forms": "^0.5.3", "@tailwindcss/line-clamp": "^0.4.2", "@tailwindcss/typography": "^0.5.2", "cross-env": "^7.0.3", "postcss": "^8.4.14", "postcss-import": "^15.1.0", "postcss-nested": "^6.0.0", "postcss-simple-vars": "^7.0.1", "rimraf": "^4.1.2", "tailwindcss": "^3.2.7" } } do i need to install cross-env? should i install it using npm or pip? in my venv or locally? -
Can you deploy sqlite db to pythonanywhere? if so how do you configure it for deployment?
Deploying sqlite database to python anywhere -
Why is my attempt to clone this django repository failing?
I am trying to clone a django repository, but I keep running into problems. I am trying to do this through a virtualenv. When I run python3 manage.py runserver I am met with the following error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", … -
Securing Endpoint in Django including Generic Relationship
In a simplified version i have 3 classes in the first app (named: appBasic): class ClassA(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) class ClassB(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() specific_B = GenericForeignKey('content_type', 'object_id') in another app (appSpec) class ClassBSpec(models.Model): class_b = GenericRelation(ClassB, related_name='class_b') class_a = ForeignKey(ClassA, on_delete=models.CASCADE) using these classes i build the endpoints using NestedRouters form the rest_framework_nested to get to: /appSpec/class_b_spec/ /appSpec/class_b_spec/<pk>/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ my goal is to protect these endpoints and allow post,get,put,patch request only for instances, which belong (via class_a) to the current user. To secure the first two endpoints i add the following method in the ClassBSpecSerializer: def validate_class_a(self, class_a): user_id = self.context['user_id'] if classs_a.user.id != user_id: raise serializers.ValidationError('No class_a with given ID found for this user') return class_a However, i cannot do the same for the other two endpoints, /appB/class_b_spec/<class_b_spec_pk>/class_b/ /appB/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ because here i am dealing with a generic relation-ship What i have implemented for now is to override the ViewSet for ClassB in the second app (appSpec) such as: from appBasic.views import classBViewSet as BasicClassBViewSet class ClassBViewSet(BasicClassBViewSet): class_b_spec_queryset = ClassBSpec.objects.filter(classA__user_id=self.request.user.id) class_b_spec = get_object_or_404(class_b_spec_querset=self.kwargs['class_b_spec_pk'] return class_b_spec.class_b.all() like that i can ensure that i get a 404 error when i am at this endpoint: /appB/class_b_spec/<class_b_spec_pk>/class_b/ … -
Having a list of autocomplete options in Django form CharField
I have a Django form with two CharFields. I want users to be able to type but I want autocomplete suggestions based on the values in the database. Here is an example of what I want pulled from another website. This is what I am currently doing. albums = Album.objects.values_list('artist', flat=True).distinct() artists = Album.objects.values_list('name', flat=True).distinct() class MakeGuess(forms.Form): artist = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Artist'})) album = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Album'})) The goal is to have the autocomplete dropdown for the artist field be the artists list and same for the albums. I tried to use a forms.TypedChoice field with choices=artists but it did not do what I thought it would. -
How do I check if a user is in a group or another group
I'm making an API using django and I want to check whether the user is in a group A or a group B using request.user.groups.filter() method but it does not seem to work. I want to be able to pass more than just one group through the name parameter to check if they are indeed in group A or group B. I've tried the following: if request.user.groups.filter(name="A") or request.user.groups.filter(name="B"): do stuff I've also tried: if request.user.groups.filter(name="A" or "B"): do stuff But I seem to be getting no luck and all I'm getting is that I need to be in group A to access the content when I want it to check whether I'm in A or B. -
There is no way to use app password on gmail account trough django app
I have running in production a django app, the webapp has a function in order to send emails with attachment to some guys using a gmail account through app password option . The functionallity worked OK for more than 3 years until a couple of days when show up this error in the errorlog: App 2165051 output: smtplib.SMTPAuthenticationError: (535, b'Incorrect authentication data') Things that i've already checked: 1.- When I checked the app password of gmail account there wasn´t anyone. ( weird, it seems that dissapeared) 2.- I created a new one, replace the new password in my code and still showing 535 error. 3.- I've create trhee app passwords and still no luck. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@adicra.org.ar' EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True views.py #Vista de enviar por mail class pagosMailPdfView(View): def get(self,request,*args,**kwargs): print("Aca en pagosMailPdfView") mailServer = smtplib.SMTP(settings.EMAIL_HOST,settings.EMAIL_PORT) #print(mailServer.ehlo()) mailServer.starttls() #print(mailServer.ehlo()) print(settings.EMAIL_HOST_USER) print(settings.EMAIL_HOST_PASSWORD) mailServer.login(settings.EMAIL_HOST_USER,settings.EMAIL_HOST_PASSWORD) print("conectando...") # averiguo la dirección de email del socio pagoh=PagosHead.objects.get(pk=self.kwargs['pk']) emailsocio=pagoh.numero_socio.email I assume that the problem is related to the google account configuration. Does anybody knows how to check this? Thanks in Adavance, Regards -
Third level HTMX back to original page?
I am using Django & HTMX. I have two sites, lets say site FOO and site BAR They both load HTMX page #1 on load There are links on HTMX page #1 for a modal- HTMX page #2 I am trying to code DRY and need a way for a button on HTMX page #2 to take me back to site FOO or site BAR, depending on where I started. I could add a ? variable in the URL and take it through two levels but I was wondering if there was an easier way. thanks! -
Problem creating django project in Pycharm
When I try to create Django project using Pycharm I receive errors which doesn't allow me to create the project. Now I am only able to create Django project using the terminal. I am able to create a Django project using the terminal but I am currently in python web course where the creation of Django projects happens only with Pycharm so I will be really greatful to solve this problem [[(https://i.stack.imgur.com/0Y33j.png)](https://i.stack.imgur.com/3ecvJ.png)](https://i.stack.imgur.com/opu8j.png) -
aws CLI configured properly but why boto3 not getting the credential?
AWS cli working but boto3 not working. I installed aws CLI on my ubuntu server and the problem is boto3 not getting the credentials from my Ubuntu machine until I hardcode the key in my code like s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, region_name=REGION_NAME ) I also run this command to aws s3 ls to verify does aws CLI working or not and it's returning all of my aws bucket name which means CLI configured properly but why boto3 not getting the credential from my ubuntu machine. I am using boto3 in my django project. -
Django TypeError: str returned non-string (type NoneType) in admin change view
I'm encountering an error when trying to access the admin change view for an order object in my Django application. The error message states: "TypeError: str returned non-string (type NoneType)." This issue occurs when accessing the URL http://127.0.0.1:8000/admin/accounts/order/38/change/. Here are some additional details about the problem: Django version: 4.2 Python version: 3.11.3 Exception location: C:\Users\Brenn Alexander\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\models.py, line 1504 The error seems to be related to the str method defined in one of my models. Here's the relevant code snippet: class Order(models.Model): # ... def __str__(self): if self.product: return str(self.product) return f"No Product (Order #{self.id})" I suspect that there might be an issue with the product field in the Order model, causing the str method to return None. This error is then propagated to the admin change view, resulting in the mentioned error. I'm unsure how to troubleshoot and resolve this issue. I would greatly appreciate any insights or suggestions on how to fix this error and ensure that the str method returns a string value as expected. Thank you in advance for your help! `class Product(models.Model): CATEGORY = ( ('Residential', 'Residential'), ('Commercial', 'Commercial'), ('Auto', 'Auto'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = … -
Django REST Framework NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id
When I try to create a new Job post by posting the following JSON: { "job_title": "Software Developer", "job_category": [ { "id": 1, "name": "Engineering" }, { "id": 2, "name": "IT" } ], "job_skills": [ { "id": 1, "title": "DJ", "category": [ { "id": 1, "name": "Web Development" }, { "id": 2, "name": "Python" } ] }, { "id": 2, "title": "RT", "category": [ { "id": 3, "name": "Frontend Development" }, { "id": 4, "name": "JavaScript" } ] } ], "job_salary_range": 80000, "job_description": "We are looking for a skilled software developer proficient in Django and React...", "job_type": { "id": 1, "job_type_choices": "FT" }, "job_location": [ { "id": 1, "name": "New York" }, { "id": 2, "name": "San Francisco" } ], "job_level": [ { "id": 1, "job_level_choices": "EL" }, { "id": 2, "job_level_choices": "ML" } ], "job_application_link": "https://example.com/apply", "company_name": "ABC Company", "company_hq": "New York", "company_logo": "https://example.com/logo.png", "companys_website": "https://example.com", "company_contact_email": "info@example.com", "company_description": "ABC Company is a leading software development company...", "date_created": "2023-06-09T12:00:00Z", "date_updated": "2023-06-09T14:30:00Z" } I get the following error: IntegrityError at /jobs/create NOT NULL constraint failed: afritechjobsapi_postajob.job_category_id MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True, null=True, blank=True) def __str__(self): return self.name class JobLocations(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class JobType(models.Model): … -
How to successfully set up both the html templace and view for Recaptcha v2 without using forms
I read other related questions about recaptcha and django without forms but I didn't find a complete solution or the posts where too old. My situation is this: I am using the package django-recaptcha. I added the "captcha" app in INSTALLED_APPS and setted up the private and public keys for recaptcha. This is currently my code in views: def verify_recaptcha(response): url = 'https://www.google.com/recaptcha/api/siteverify' params = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': response, } response = requests.post(url, data=params) data = response.json() return data['success'] def contact(request): context = { 'RECAPTCHA_PUBLIC_KEY': settings.RECAPTCHA_PUBLIC_KEY } if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') captcha_response = request.POST.get('recaptcha_response') if name and email and message: if verify_recaptcha(captcha_response): send_mail( subject="Contact Form Submission", message=f""" Name: {name} Email: {email} Message: {message} """, from_email=FROM_EMAIL, recipient_list=[TO_EMAIL], fail_silently=False, ) context['message'] = 'Your message has been sent!' else: context['error'] = 'Invalid reCAPTCHA response.' else: context['error'] = 'Please fill in all required fields.' return render(request, 'contact.html', context) And this is the extract of my html template: <div class="field"> <div class="g-recaptcha" data-sitekey="{{ RECAPTCHA_PUBLIC_KEY }}"></div> <input type="hidden" name="recaptcha_response"> </div> <div class="field has-text-centered"> <button type="submit" class="button is-success has-background-success-dark"> Submit </button> </div> I am using the recaptcha v2. The widget seems to work just fine in the … -
How to log user into Superset UI
I'm using Django and superset. I'm able to login programmatically in one of my views and get an access token and a csrf token with my username and password. However, my end goal is to log the user into an embedded superset dashboard in one of my templates. In my view I'm using request sessions and I can see my cookie session value. In my UI, the cookie that is set is a different value. Is there a way that I can tell Django to use the same request session in my template as what is being used in my view? Or, perhaps there is another way to accomplish the same task of logging a user into the UI automatically. I'm open to that too, it just seems like I'm so close. The code I'm using is below, specifically the programmatic_login function. It all works, I would just like to let my template know that the user has already been authenticated. class SuperSetApi(): csrf_token = '' access_token = '' refresh_token = '' session = None base_url = 'http://superset:8088/' username = '' password = '' guest_token = '' custom_token = '' def url(self, base_url, url_path): return base_url + url_path def add_remote_user_header(self, … -
How to display Comments total on other page using in django using annotate()
any one to help me on how to use annotate() to display the comments total for each object in django model. below is my code. models.py class GameArticle(models.Model): sno=models.AutoField(primary_key=True) status=models.CharField(max_length=10, choices=STATUS, default='Draft') uid= ShortUUIDField(help_text='Place for the Article ID ', unique=True, max_length=10, length=5, prefix='ar',alphabet='aBcDeFgHjKlM12345') title = models.CharField(max_length=200, help_text='Enter The Article Title') class GameArticleComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) article=models.ForeignKey(GameArticle, on_delete=models.CASCADE, related_name='comments') parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp=models.DateTimeField(default=now) class Meta: ordering=['-timestamp'] Views.py def game_article(request): article_list = GameArticle.published.all() #............ def article_detail(request, uid): data = get_object_or_404( GameArticle, slug=uid, status='p') comments = GameArticleComment.objects.filter(article= get_object_or_404(GameArticle, slug=uid), parent=None) any one to direct me on how to use annotate and return the total of the comments for each object -
Django form error using ManyToMany relationship - TypeError: Field 'id' expected a number but got <Profile: user1>
I am making a recommendation app where a user can recommend a movie/show/book to one or more users. The form is set up so that it displays a list of all users and you can check a box next to the users you want to send the recommendation to, but I am getting this error (Field 'id' expected a number but got <Profile: user1>) when I hit "Submit" on my form after checking the box next to the username and I'm not sure where I went wrong. Most of the other questions related to this are using ForeignKey rather than ManyToManyField in their model. models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( 'self', related_name='followed_by', symmetrical=False, blank=True, ) def __str__(self): return self.user.username class Recommendation(models.Model): user = models.ForeignKey( User, related_name="recs", on_delete=models.DO_NOTHING ) recipients = models.ManyToManyField( User, related_name="received_recs", symmetrical=False, blank=True ) title = models.CharField(max_length=300) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return ( f"{self.user} " f"({self.created_at:%y-%m-%d %H:%M}): " f"{self.title}" ) views.py: from django.shortcuts import render, redirect from .models import Profile, Recommendation from .forms import RecForm def dashboard(request): all_recs = Recommendation.objects.all() if request.method == "POST": … -
Is it bad written my custom authentication backend in Django?
I'm trying to implement a custom authentication backend in Django, mi custom Auth model and my custom user creation form works ok, but when I'm try to login using my custom authentication backend, it raise me this excepcion. Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\authentication\views.py", line 12, in login usuario = UsuarioAuthBackend.authenticate(request, email=email, password=password) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: UsuarioAuthBackend.authenticate() missing 1 required positional argument: 'request' [09/Jun/2023 10:47:15] "POST /login/ HTTP/1.1" 500 66119 It tells me that I got 1 missing required positional argument, the request. But that argument was passed in the code, I'll share you my code. The Custom User Model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # choices CALIFICACION_USUARIO_CHOICES = [ (0,0), (1,1), (2,2), (3,3), (4,4) ] # Create your models here. class UsuarioManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('El usuario debe tener un correo electrónico') email = self.normalize_email(email) usuario = self.model(email=email, **extra_fields) usuario.set_password(password) usuario.save(using=self._db) return usuario def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, … -
Why is my django application on cpanel only recognising the root url and not any other url after the root url?
I recently deployed my Django application on a subdomain through Cpanel. However, when I try to access the application, only the root url is working. Any other address is not being sent. In the browser, anything after the / of the root url is grayed out and the logs of the application also suggest they are not receiving the entire address. I have attached screenshots herein for clarity. Any help will be appreciated. -
Django DB issue (Interface error: connection closed)
Calling all Pythonistas! I'm embarrassed to say, but this issue has been plaguing us for 3 weeks! It's intermittent with no rhyme or reason. Ubuntu 22.04 running Docker containers (uses the solid cookiecutter-django) as a base which we've used successfully for many years. django==4.1.9 gunicorn==20.1.0 psycopg2==2.9.6 When submitting a simple registration form, randomly, but very frequently we get the following error: InterfaceError connection already closed This issue is ALWAYS at django/db/backends/postgresql/base.py in create_cursor at line 269 which is cursor = self.connection.cursor() In Sentry it shows as a "System" error, not an "In-App" error (ie - code flaw). The form: class GuestForm(forms.ModelForm): time = forms.ChoiceField(choices=[]) # time = forms.ChoiceField(choices=[("18:30", "6:30 PM")]) class Meta: model = Guest fields = ["first_name", "last_name", "email", "opt_in"] def __init__(self, *args, **kwargs): logger.debug("=> Init GuestForm") super().__init__(*args, **kwargs) self.fields["time"].choices = get_choices() def clean_time(self): """Return a time.""" cleaned_data = super().clean() hours, minutes = cleaned_data["time"].split(":") try: return datetime.time(int(hours), int(minutes)) except ValueError as exc: raise ValidationError( "Invalid value: %(hours)s %(minutes)", code="invalid", params={"hours": hours, "minutes": minutes} ) from exc The view: class RegisterView(FormView): form_class = GuestForm template_name = "tour/register.html" tourgroup = None @transaction.atomic def form_valid(self, form): """While we are creating a Guest, we are ultimately creating a TourGroup.""" # Create or get … -
Django admin _continue and _addanother not working
I have 3 buttons in django admin: save, save and add another, save and continue. They have their input names in html like _save, _addanother and _continue. All of these buttons do the same thing - save model and redirect to the main page (like when I click on the save button) class StudyFormAdmin(admin.ModelAdmin): list_display = ['name'] fields = ['name'] I found out that response_add method contains redirect functionality (https://github.com/django/django/blob/ef62a3a68c9d558486145a42c0d71ea9a76add9e/django/contrib/admin/options.py#L1316). Then I tried to check what in my request.POST. I add these lines to my model: def response_add(self, request, obj): print(request.POST) return super().response_add(request, obj) Output: <QueryDict: {'csrfmiddlewaretoken': ['2IOoriUmt5IzfIKU7MY53hZ9dgupnM3sNU6ltcaKXXzwmDB73xekyXn55Pw197dF'], 'name': ['adfgdfg']}> I have tried all these buttons for each model I have but response always the same -
How to Fill in django form with a json file?
I'm building a django system that will receive a file and will return a json file and some graphics. The graphics is working but now and i need to fill in a django form with a json file. Basically, when the user make the upload a django form will filled and after that the graphics will return. How can i do that ?