Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
comments are being saved in database to related post but not accessed in template even variable is correct
comments are being saved in database to related post but not accessed in template even variable is correct on debuging it shows the comment to realted post but not fetching it to the template only commet.count function showing one comment here is template {{ comment.count }} {% for comment in comment5 %} {{comment.user}} {{comment.datetime}} {{comment.content}} {% endfor %} def blogpost1(request, id): post = get_object_or_404(Post, id=id) comment5=Comment.objects.filter(blog=post) print(f"Post: {post}") print(f"Comments: {comment5}") # Debugging statement for comment in comment5: print(comment.id, comment.user, comment.content) print(comment5) if request.method=='POST': user = request.user content=request.POST.get('content') comment=Comment(user=user,content=content,blog=post) comment.save() return render(request,'singlpost.html',{'post':post,'comment':comment5}) -
How to host two django apps on windows using apache and mod_wsgi?
I know how to run 1 django application on windows server using mod_wsgi & apache. Now I want to run more than one django application on the same server. I have the following configurations httpd.conf at the end of the file I added LoadFile "C:/Python312/python312.dll" LoadModule wsgi_module "C:/Python312/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" #WSGIPythonHome "C:/Python312" windows_wsgi.py for application app1 # Activate this path from virtual env activate_this = "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Scripts/activate_this.py" exec(open(activate_this).read(),dict(__file__=activate_this)) import os # import site import sys from decouple import config # Add the site-packages of the selected virtual env to work with # site.addsitedir = "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages" sys.path.append("C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages") sys.path.insert(0, "C:/Users/rahee/.virtualenvs/app1-jCWLzbvP/Lib/site-packages") # Add teh app directory to the PYTHON PATH sys.path.append("C:/Apache24/htdocs/app1") sys.path.append("C:/Apache24/htdocs/app1/app1") os.environ['DJANGO_SETTINGS_MODULE'] = config('DJANGO_SETTINGS_MODULE') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() windows_wsgi.py for app2 # Activate this path from virtual env activate_this = "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Scripts/activate_this.py" exec(open(activate_this).read(),dict(__file__=activate_this)) import os # import site import sys from decouple import config # Add the site-packages of the selected virtual env to work with # site.addsitedir = "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages" sys.path.append("C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages") sys.path.insert(0, "C:/Users/rahee/.virtualenvs/app2-mArRrqZl/Lib/site-packages") # Add the app directory to the PYTHON PATH sys.path.append("C:/Apache24/htdocs/app2") sys.path.append("C:/Apache24/htdocs/app2/app2") os.environ['DJANGO_SETTINGS_MODULE'] = config('DJANGO_SETTINGS_MODULE') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd-vhosts.conf settings <VirtualHost *:92> ServerName app1.localhost WSGIPassAuthorization On ErrorLog "logs/app1.error.log" CustomLog "logs/app1.access.log" combined WSGIScriptAlias / "C:\Apache24\htdocs\app1\app1\wsgi_windows.py" application-group=%{app1} <Directory "C:\Apache24\htdocs\app1\app1"> … -
What is so dofficult for Django to work out about display media images on my template?
Right, what is so difficult for Django to work out in pertinence to displaying an image on a template when DEBUG is set to False? Why is it, when I do literally everything correctly, does it just outright refused to display the bloody image on the page? Why is it, when I have correctly set up my MEDIA_URL and my MEDIA_ROOT in my settings.py, does it still refuse to load the page? Why is it that despite correctly setting up my root urls.py page in the following fasion, does Django refuse to the display the image in the webpage: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Why is is that, despite correctly setting up the upload_to directly in my models.py file, run the makemigrations as well as the migrate command, does Django....you get the idea. Why is that that despite installing whitenoise, and running the py manage.py collectstatic command doesnt Django...oh yes, sorry, we've done this before. Why is is that when I go to "inspect source" in my web browser does it return the correct image directory, yet when I click on the image URL directory from the inspect source page, does it return my beautifully-crafted custom 404 page? I know, shocker … -
Integrity Error - UNIQUE constraint failed. How do i deal with it? Django
I am new to the DRF framework, and am building a small project. I want to create a User instance (the built-in one) and while doing so also make a Seller instance linked to it during a user signup. Whenever i try to do this, Django throws an Integrity Error : UNIQUE constraint failed: seller_seller.user_id. Can you all help me understand this issue and to fix it? Please ask if more information is required. models.py class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) seller_company_name = models.CharField(max_length=200) seller_contact = models.CharField(max_length=14, null=True) seller_email = models.EmailField(max_length=200, null=True) def __str__(self): return f"{self.id} --> {self.user.username}" serializers.py class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) contact = serializers.CharField(max_length=15, required=True) cname = serializers.CharField(max_length=200, required=True) class Meta: model = User fields = ['id', 'username', 'email', 'password', 'contact', 'cname'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): try: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'], ) except IntegrityError: raise serializers.ValidationError("Username or email already exists.") try: seller = Seller.objects.create( user=user, seller_contact=validated_data['contact'], seller_company_name=validated_data['cname'], seller_email=validated_data['email'], ) except IntegrityError as e: user.delete() # Rollback user creation if seller creation fails raise serializers.ValidationError("Failed to create seller.") return user signup view @api_view(['POST']) @permission_classes([AllowAny]) def signup_view(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: return Response(status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) I have … -
Is it possible localhost html file with python http module like django
So i was trying to make localhost with http.server i used some help from docs but i got an error i tried to fix still unable to fix it here is the code: from http.server import BaseHTTPRequestHandler, HTTPServer loop = True def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler): server_address = ('result.html', 5050) httpd = server_class(server_address, handler_class) httpd.serve_forever() if loop == True: httpd.server_close() while loop: run() ex = input("To close the server write 'exit' /n <<< ") if ex.find(f'exit'): loop = False Error: Traceback (most recent call last): File "E:\Python\localhost\main.py", line 36, in <module> run() File "E:\Python\localhost\main.py", line 5, in run httpd = server_class(server_address, handler_class) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\socketserver.py", line 457, in __init__ self.server_bind() File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\http\server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\socketserver.py", line 473, in server_bind self.socket.bind(self.server_address) socket.gaierror: [Errno 11001] getaddrinfo failed Process finished with exit code 1 -
django rest framework LimitOffsetPagination when modifying results
I'm using django rest frame work and want LimitOffsetPagination https://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination to work on the json output of my view class MyList(generics.ListAPIView) which has thousands of records to potentially page through. I can't figure out how to get it working as desired without fetching all the potential records vs only the slice needed for a given page. The problem is introduced by the fact that I have to modify the records before returning from the view, I can't just return a queryset, I return my customized list of records. If I merely do some queryset manipulation and return a queryset, everything works great. SQL to the DB uses LIMIT and OFFSET so it's fast, a page of records is fetched, and json is paged as expected. I need to modify the results of the queryset however and as soon as I evaluate it mylist = list(queryset) SQL does NOT use LIMIT and OFFSET it fetches all the records. If I use slice notation on the queryset queryset[offset:offset+limit] to force it to only get what I want, then modify those results that works up to a point(SQL uses LIMIT and OFFSET etc). The problem is say the slice was 100 records, the … -
TypeError: Group name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not
import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import User, Connection, Message import logging from .serializers import ( MessageSerializer ) from app.serializers import ( UserSerializer, ) logger = logging.getLogger(name) class ChatConsumer(WebsocketConsumer): def connect(self): user = self.scope['user'] self.accept() if not user.is_authenticated: return self.username = user.username # Join user to group async_to_sync(self.channel_layer.group_add)( self.username, self.channel_name ) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.username, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) data_source = data.get('source') self.send(text_data=json.dumps({"message": data.get('message')})) if data_source == 'message.send': user = self.scope['user'] connectionId = data.get('connectionId') message_text = data.get('message') receiver = User.objects.get(username=data.get('user_receiver')) try: connection = Connection.objects.get(id=connectionId) except Connection.DoesNotExist: connection = Connection.objects.create( sender=user, receiver=receiver, ) return message = Message.objects.create( connection=connection, user=user, text=message_text ) # Get recipient friend recipient = connection.sender if connection.sender == user: recipient = connection.receiver messages = Message.objects.filter( connection=connection ).order_by('-created') serialized_messages = MessageSerializer( messages, context={ 'user': user }, many=True ) # Send new message back to sender serialized_message = MessageSerializer( message, context={ 'user': user } ) serialized_friend = UserSerializer(recipient) data = { 'message': serialized_message.data, 'messages': serialized_messages.data, 'friend': serialized_friend.data } self.send_group(user.username, 'message.send', data) # Send new message to receiver serialized_message = MessageSerializer( message, context={ 'user': recipient } ) serialized_friend = UserSerializer(user) data = { 'message': serialized_message.data, 'messages': serialized_messages.data, 'friend': serialized_friend.data } … -
Organizing Django Project: Separating App into Multiple Servers with Shared Database and User Model
In our project, we plan to split one Django app from the monolith into a separate server, while using a single database for both. I don't understand how to correctly utilize the user model, which will be shared between the two servers. Should migrations, both existing and future ones, remain in one repository or should they be split between the two? class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(_("Email address"), unique=True) email_verified = models.BooleanField(default=False) first_name = models.CharField(_("first name"), max_length=100, blank=True, null=True) last_name = models.CharField(_("last name"), max_length=100, blank=True, null=True Explored various architectural options for splitting a Django app into two servers with a shared database. Reviewed Django documentation regarding the use of a shared user model. Expecting to find an optimal way to utilize the user model in this scenario and ensure migration synchronization for both servers -
I want to find a method to avoid complexity and coupling in django models + rest api
I created a model for an API. After that, I planned to add more APIs from different platforms. however, all of the APIs were for the same purpose but the data they required and their methods of accepting the data differ. For example. (it's just an example to explain, not the actual case but 90% similar) I create a model with attributes (name, email, password), but the second API is using (firstname, lastname, email, password). Maybe the third API will ask for (Surname, country, oassword) etc. Then I wanted to create a view to perform CRUD operation. But to know which crud should be done for which API, I created a class with the name CRUD handler in which the class will specify which one to use. I also created another class with the name 'BOT' which had a unique secret key to identify which user wants to use which API. So that every time the credentials are not meant to be sent for safety. Almost all of them use/support the REST framework This is the flow that I want: some_other_WEbsite -> (sends data with secret key) -> djangoview -> BOT ->(uses secret key) to identify the USER, the API … -
I want to show users who selected a particular role, on a dropdown in another form,,
PERSONAL DATA user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) image = models.FileField(_('Profile Image'),upload_to='profiles',default='default.png',blank=True,null=True,help_text='upload image size less than 2.0MB')#work on path username-date/image firstname = models.CharField(_('Firstname'),max_length=125,null=False,blank=False) lastname = models.CharField(_('Lastname'),max_length=125,null=False,blank=False) # linemanager = models.CharField(_('Line manager'),max_length=125,null=False,blank=False,default='mr.....') # birthday = models.DateField(_('Birthday'),blank=False,null=False) phone = models.CharField(_('Phone number'),max_length=12,null=False,blank=False,help_text='enter phone number') department = models.ForeignKey(Department,verbose_name =_('Department'),on_delete=models.SET_NULL,null=True,default=None) role = models.ForeignKey(Role,verbose_name =_('Role'),on_delete=models.SET_NULL,null=True,default=None) this is the employee models.py where i add a staff and select a particular role def dashboard_employees_create(request): if not (request.user.is_authenticated and request.user.is_superuser and request.user.is_staff): return redirect('/') if request.method == 'POST': form = EmployeeCreateForm(request.POST,request.FILES) if form.is_valid(): instance = form.save(commit = False) user = request.POST.get('user') assigned_user = User.objects.get(id = user) instance.user = assigned_user instance.title = request.POST.get('title') instance.image = request.FILES.get('image') instance.firstname = request.POST.get('firstname') instance.lastname = request.POST.get('lastname') instance.phone = request.POST.get('phone') role = request.POST.get('role') role_instance = Role.objects.get(id = role) instance.role = role_instance instance.startdate = request.POST.get('startdate') instance.employeetype = request.POST.get('employeetype') instance.employeeid = request.POST.get('employeeid') # instance.dateissued = request.POST.get('dateissued') instance.save() This is the views class LeaveCreationForm(forms.ModelForm): reason = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 4, 'cols': 40})) class Meta: model = Leave exclude = ['user','defaultdays','hrcomments','status','is_approved','updated','created'] this is what my leave creation form looks like -
Django Static Files Not Loading Correctly in Production with Apache
I've been struggling with serving static files in a Django application deployed on Apache. Despite following numerous guides and suggestions, I'm still encountering 404 errors for my static files. Below are the relevant details of my setup and the issues I'm facing. Environment: Django Version: 3.0 Python Version: 3.8 Web Server: Apache2 OS: Ubuntu Problem Description: In development mode with DEBUG=True, the static files load correctly and I can see my React build. However, in production with DEBUG=False (or even with Debug=True), I encounter the following errors: 404 errors for JavaScript and CSS files MIME type errors stating that the files are being served as text/html instead of their correct types Errors in Browser Console: GET https://www.myapp.com/static/js/main.a14a4a4b.js net::ERR_ABORTED 404 (Not Found) Refused to execute script from 'https://www.myapp.com/static/js/main.a14a4a4b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to apply style from 'https://www.myapp.com/static/css/main.868dfa48.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET https://www.myapp.com/favicon.png 404 (Not Found) GET https://www.myapp.com/manifest.json 404 (Not Found) Manifest: Line: 1, column: 1, Syntax error. Directory Structure: Here's the structure of my staticfiles directory: /var/www/jmyapp/staticfiles: asset-manifest.json css favicon.png index.html js logo192.png logo512.png … -
window.location.href doesn't adding referer header when executed inside html wrapper but running that in console is adding referer header. Why?
I have two subdomains, let's call them x.example.com and y.example.com. When a user requests x.example.com, the server redirects them to y.example.com. On y.example.com, there's a feature that displays specific content if the referer header matches a certain value. However, when the request comes to y.example.com after the redirection, it doesn't have any referer header attached to it. I'm using Django on the backend to handle the redirection with HttpResponseRedirect("y.example.com"). I attempted to include the referer header in the server's response using Django, but it didn't seem to have any effect. response = HttpResponseRedirect("y.example.com") response['referer'] = 'https://x.example.com' Additionally, I tried implementing a redirection in JavaScript by returning HTML with embedded JavaScript code, but that also didn't result in the referer header being passed along. Interestingly, directly executing the JavaScript redirection in the browser console did include the referer header. I'm puzzled as to why it's not working as expected. Can you suggest an alternative approach to achieve the desired behavior? html_content = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Redirecting...</title> </head> <body> <h1>Redirecting...</h1> <script> // JavaScript code for redirection window.location.href = 'https://y.example.com'; }); </script> </body> </html> """ # Return the HTML response with embedded JavaScript return … -
504 Deadline Exceeded while using langchain_google_genai
Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/langchain_google_genai/embeddings.py", line 146, in embed_documents result = self.client.batch_embed_contents( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/ai/generativelanguage_v1beta/services/generative_service/client.py", line 1350, in batch_embed_contents response = rpc( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/gapic_v1/method.py", line 131, in call return wrapped_func(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 293, in retry_wrapped_func return retry_target( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 153, in retry_target _retry_error_helper( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_base.py", line 212, in _retry_error_helper raise final_exc from source_exc File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/retry/retry_unary.py", line 144, in retry_target result = target() File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/google/api_core/timeout.py", line 120, in func_with_timeout return func(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/li b/python/site-packages/google/api_core/grpc_helpers.py", line 78, in error_remapped_callable raise exceptions.from_grpc_error(exc) from exc google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/dhvanipatel/Library/Python/3.9/lib/python/site-packages/django/urls/resolvers.py", line 715, … -
How to deploy front end & backend apps on same machine with same domain but different ports?
I have two apps one for frontend built using ReactJS and one is for backend built using Django. I have server machine where I have deployed both the apps. Now I want to use Nginx (because of SSL) to host both my application on the same machine with same domain name but the ports are different. I know how to do it for different domains or subdomain but I don't have another domain/subdomain with me right now. So I want to aks how I can achive this in Nginx? For example my FE is using port 4173 & BE is using 8000,I am able to configure Nginx to serve my FE but I am getting this error, Blocked loading mixed active content because my FE which is httpstrying to connect to backend on port 8000 which is not https. Here is my nginx config file server { listen 80; server_name camfire.pp.ua; # Перенаправлення HTTP на HTTPS location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name camfire.pp.ua; # Шляхи до сертифікатів SSL ssl_certificate /etc/letsencrypt/live/camfire.pp.ua/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/camfire.pp.ua/privkey.pem; # Проксирування запитів до FrontEnd location / { proxy_pass http://localhost:4173; 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 … -
**404 Error with `drf_with_firebase_auth` Signup Endpoint**
I'm following the tutorial from the GitHub repository [https://github.com/Abiorh001/drf_with_firebase_auth] and have completed the setup steps. However, I'm encountering a 404 error (Not Found) when trying to send a signup request to http://127.0.0.1:8000/api/v1/users/auth/sign-up/ using Postman. I've checked the urls.py file and the URL pattern seems to be defined correctly. I've also set the environment variables for Firebase credentials as instructed in the tutorial. There are no error messages in the console. this is the result when i try to send request in postman For reference, this is urls.py from accounts app: urlpatterns = [ path('auth/sign-up/', AuthCreateNewUserView.as_view(), name='auth-create-user'), path('auth/sign-in/', AuthLoginExisitingUserView.as_view(), name='auth-login-drive-user'), path('<str:pk>/', RetrieveUpdateDestroyExistingUser.as_view(), name='retrieve-update-user'), path('auth/update-email-address/', UpdateUserEmailAddressView.as_view(), name='user-update-email-address'), path('auth/reset-password/', UserPasswordResetView.as_view(), name='user-reset-password'), ] and this is my main projects urls.py api_version = 'v1' urlpatterns = [ path(f'api/{api_version}/admin/', admin.site.urls), path(f'api/{api_version}/users/', include('accounts.urls')), re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path(f'api/{api_version}/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path(f'api/{api_version}/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] What could be causing the 404 error when trying to sign up Thanks in advance for any help! I have looked for solution all over the internet but i found nothing that could help me. -
JWT refresh in Angular 17
My backend is Django restframework. when I give my credentials it gives me tokens which are consist of refresh and access tokens. In my backend my access_tokens expiration time is 2 minutes(just for testing but will increase till 15 minutes). and refresh_tokens expiration time is 15 days. when my access_token expires I send my refresh_token to fetch new access_token(only provides access_token). On front_end (Angular 17), I have implemented to fetch the new access_tokens instead of getting new tokens I am getting logout after 2 minutes. I am new to Angular. I tried to debug but couldn't find the solution. I am posting my service class and interceptor. export const authInterceptor: HttpInterceptorFn = (req, next) => { const auth_service = inject(AuthService); const accessToken = auth_service.getAccessToken(); let authReq = req; if (accessToken) { authReq = req.clone({ setHeaders: { Authorization: `Bearer ${accessToken}` } }); } return next(authReq).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401 && error.error.code === 'token_not_valid') { console.log('Token expired, attempting to refresh...'); // Token expired, attempt to refresh return auth_service.refreshTokenRequest().pipe( switchMap(() => { const newAccessToken = auth_service.getAccessToken(); if (newAccessToken) { console.log('New access token received'); authReq = req.clone({ setHeaders: { Authorization: `Bearer ${newAccessToken}` } }); } return next(authReq); }), catchError((err) => … -
django using template tag from one app to the other
hey guys Im stuck in some problem, as a question, I'm working on a django base website which has 5 pages two apps in it, blog app has posts in it and the other app website is for home_page, so the deal is I have to show the latest posts in home_page with using template tag but with my solution it was never shown. # index_tag.py Post is what I created in blog models and called here for reuse it from django import template from blog.models import Post register = template.Library() @register.inclusion_tag('website/home-latest-posts.html') def latestposts(arg=3): posts = Post.objects.filter(status=1).order_by('published_date')[arg:] return {'posts': posts} <!-- home-latest-posts.html --> {% load static %} {% load index_tags %} <div class="row"> <div class="active-recent-blog-carusel"> {% for post in posts %} <div class="single-recent-blog-post item"> <div class="thumb"> <img class="img-fluid" src="{{post.image.url}}" alt=""> </div> <div class="details"> <div class="tags"> <ul> <li> <a href="#">Travel</a> </li> <li> <a href="#">Life Style</a> </li> </ul> </div> <a href="{% url 'website:index' pid=post.id %}"><h4 class="title">{{post.title}}</h4></a> <p>{{post.content}}</p> <h6 class="date">{{post.published_date|date:'d M Y'}}</h6> </div> </div> {% endfor %} </div> </div> <!-- index.html after many codes this is the template tag that I created --> {% extends "base.html" %} {% load static %} {% load index_tags %} {% block content %} <!-- Start blog Area … -
how to send data with formset empty_form to database Django
i use inlineformset_factory to create dynamic row in django for create or update i don't have a problem but for empty_form i get some issues formset.empty_form.visible_fields they don't send data for database and save it. template code {{formset.management_form}} {% for fields in formset.empty_form.visible_fields %} <td>{{fields}}</td> {% endfor %} view.py if form.is_valid(): save_form = form.save() if formset.is_valid(): formset.save() save_form.save() return redirect("/") form.py ItemFormSet = inlineformset_factory( Invoice, InvoiceItem, form=InvoiceItemForm, extra=1,can_delete=False) i want clicck a button add field and post this field value to database in django -
Django ValueError: dictionary update sequence element #0 has length 653; 2 is required
i am sending request to backend like this const createOrderButton = document.getElementById('createUserCart'); createOrderButton.addEventListener('click', function () { const urlAddress = document.getElementById('cart-wrapper').getAttribute('action'); console.log(JSON.stringify(cart)); if (urlAddress === '/orders/') { let promise = fetch(urlAddress, { method: "POST", headers: { 'Content-Type': 'application/json', "X-CSRFToken": CSRF_TOKEN }, body: JSON.stringify(cart) }); console.log(promise); } }); the cart object is like [{"product_id" : 1, "name" : "item1", "img_src":"https://...", ...}, {}, ...] my views.py class CreateCart(View): template_name = "orders/index.html" def post(self, request): user_cart = json.loads(request.body.decode()) random_id = uuid.uuid4() date_create = now() cart_objects_to_create = [ Cart( user=User.objects.get(id=request.user.id), product=Product.objects.get( id=int(el['product_id']) ), cart_id=random_id, date_create=date_create ) for el in user_cart ] Cart.objects.bulk_create(cart_objects_to_create) return render(request, self.template_name) This code is insert objects into sql table, but dont render template and i see error Internal Server Error: /orders/ Traceback (most recent call last): File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/orders/views.py", line 42, in post return render(request, self.template_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/shortcuts.py", line 25, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/danya/CodeProject/djangoMarketPlace/venv/lib/python3.12/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, … -
paypal subscription payment doesnt open on django
I am trying to make a subscription using django and paypal payment. I'm trying to complete a course. I have made my plans in business sandbox. I've used the code it gives you after making plans and turn them on. I simply copied and pasted the code into my page. It is a local server. When I click on Paypal buttons they open a blank page. I checked my Inspect and it shows these each time I click on links. First error: create_order_error Object { err: 'Create Subscription Api response error:\n\n{\n "name": "RESOURCE_NOT_FOUND",\n "message": "The specified resource does not exist.",\n "debug_id": "f913475242396",\n "details": [\n {\n "issue": "INVALID_RESOURCE_ID",\n "description": "Requested resource ID was not found."\n }\n ],\n "links": [\n {\n "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND",\n "rel": "information_link",\n "method": "GET"\n }\n ]\n}', timestamp: "1717846131222", referer: "www.sandbox.paypal.com", sdkCorrelationID: "0b604ba725142", sessionID: "uid_ffb7a1abe3_mte6mjc6mjk", clientID: "AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R", env: "sandbox", buttonSessionID: "uid_ef868db584_mte6mjg6ndg", buttonCorrelationID: "f3594475ad16f", token: null } Seconf error: Uncaught Error: Create Subscription Api response error: { "name": "RESOURCE_NOT_FOUND", "message": "The specified resource does not exist.", "debug_id": "f693155709fe0", "details": [ { "issue": "INVALID_RESOURCE_ID", "description": "Requested resource ID was not found." } ], "links": [ { "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#RESOURCE_NOT_FOUND", "rel": "information_link", "method": "GET" } ] } Last one is a warning: click_initiate_payment_reject Object … -
How can I solve the no module_found issue in Django?
after creating the venv I have installed the django to the venv.Also I have added the installed apps also but its showing no module named module_name.settings error. Can anyone help ? ModuleNotFoundError: No module named 'chatbot.settings' I were trying to create a chatbot and actually it were working in the begining, because of an issue in git i just changed the folder. Since that happens the same error is showing And also I have tried to create the project from the beginning and the same error is encountering. -
Are name="submit" and name="next" predefined attributes in Django?
I'm reading a book 'Python Crash Course 2nd edition' and currently doing a Django project. And in a form there are button with name="submit" and and hidden input element with name="next". In the book it says that the button with name="submit" is a submit button and a hidden form element with name "next" is the value argument that tells Django where to redirect the user after they’ve logged in successfully. I tried to search up button with name="submit" and input hidden element with name="next" in Django but wasn't able to find any info. How does it work? Are those somewhere predefined or no? <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">Log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> -
Redis aa cache manager in django project
What is the difference between using redis as pip install redis in your django project and keeping redis as a separate instance in another server? Will using redis in a project incur additional costs if I am using in as a package in my ec2 instance. -
Django form to save m2m additional fields (using custom through\assosiation table)
I have a "Recipe" model, which contains multiple "Product" models and the relationship between Recipe and Product holds the quantity of the products. Thus, I need a custom intermediary model. models.py: class Product(models.Model): name = models.CharField(max_length=50, null=False, blank=False) quantity = models.PositiveSmallIntegerField(null=False, blank=False) ... class Recipe(models.Model): name = models.CharField(max_length=50, null=False, blank=False) ingredients = models.ManyToManyField(Product, through='ProductRecipe') ... class ProductRecipe(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.SmallIntegerField(null=True) A Recipe object is created based on a form and the Product objects to be part of the Parent object are selected by checkboxes. My question is, how can we add ProductRecipe.quantity field to my form when Recipe object is being created. Here is my forms.py that I use for Recipe object creation class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name ', ... , 'ingredients'] ingredients = forms.ModelMultipleChoiceField( queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple ) Trying to have additional field 'quantity' while creating Recipe object from django form -
module 'jwt' has no attribute 'PyJWTError'
module 'jwt' has no attribute 'PyJWTError' I'm trying to set up authorization via Google and I get this error. Is it a problem with version incompatibility? Sorry, I'm new to this. Exception Location: /usr/local/lib/python3.11/site-packages/allauth/socialaccount/internal/jwtkit.py, line 85, in verify_and_decode Django Version: 5.0.6 PyJWT Version: 2.8.0