Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access GAID in Django
Is it possible to retrieve GAID in a Django server? Here is my scenario: I want to create a unique link in my Django project and send it to a user (it's a referral link). When the user click the link it will redirect to my server so then I can log its click and then user will redirect to an app store to download my app. Is it possible for me to get its GAID before installing the app, right after clicking the link? If yes so, then how? I searched already couldn't find anything helpful. I appreciate if anyone can offer me a documentation or something like that. -
Not getting a django's right capture group when url has a "."
I have a url http://localhost/fault/docs/testing/pipelines/dot.filetesting which should return a default html page ie index.html urls.py looks like- re_path(r'(?P<resource>.*)$', csrf_exempt(views.get_docs_from_s3), name='read_docs') view.py - ` @require_GET def get_docs_from_s3(request, resource): mime_type, _ = mimetypes.guess_type(resource) # if not Path(resource).suffix: # resource = resource.rstrip("/") + "/index.html" try: page = get_page_from_s3(resource) return HttpResponse(page, content_type=mime_type or "text/html") except Exception as e: return HttpResponse("Not found", content_type=mime_type or "text/html")` nginx conf - ` location /fault { add_header X-Cache $upstream_cache_status; rewrite ^([^.]*[^/])$ $1 permanent; proxy_set_header Host localhost:8000; proxy_pass http://localhost:8000/bug; proxy_connect_timeout 30s; proxy_read_timeout 86400s; proxy_send_timeout 30s; proxy_http_version 1.1; }` Question for a url like http://localhost/fault/docs/testing/pipelines/normal I am able to render html page since the resource in my views = docs/testing/pipelines/normal/index.html but for urls that have "." in them like mentioned above I don't get index.html appended. Note-> In the code I do not want to add /index.html in my views.py for that doesn't have, if its able to be resolved at nginx and django urls leveel -
Need advice. Forbidden (403) CSRF verification failed. Request aborted. Django error
I am making a website with django and when i login and go back then try to login again i get this error message. Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token from POST incorrect. When i login first it works okay, and after i get the error i go back and the login is successful again. I was just wondering what the problem is with my code. This is the views.py `@csrf_protect def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password ) if user is not None: auth_login(request, user) return redirect('homepage') else: messages.error(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context)` This is my settings.py `MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ` This is my login.html `<form method="POST" action=" " > {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="text" name="username" class="form-control input_user" value="" placeholder="Username"> </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" name="password" class="form-control input_pass" value="" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> </div> </div> <div> {% for message in messages %} <p id="messages">{{message}}</p> {%endfor%} … -
Heroku Django remote: Is the server running locally and accepting connections on that socket? heroku django
So Ive been trying to run my django application on heroku, it works locally fine with the database, so its some issue within my base.py that I havent been yet able to identify. If anyone has encountered a similar problem and have a solution, Ive been looking around for a while no hints :( error message: remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection remote: self.connect() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect remote: self.connection = self.get_new_connection(conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner remote: return func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection remote: connection = self.Database.connect(**conn_params) remote: File "/app/.heroku/python/lib/python3.10/site-packages/psycopg2/init.py", line 122, in connect remote: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) remote: psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory remote: Is the server running locally and accepting connections on that socket? base.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the … -
datetime field in django is being displayed differently in the template and not like the saved one in database
The following is a part of my ajax request in my django template <span class='time-left'>${response.chats[key].date}</span></div>`; This is the model field it is refering to... date = models.DateTimeField(auto_now_add=True, null=True, blank=True) Now this is the problem. The datetime is saved correctly in the database to my current timezone. However, when I display it in the template like above, I get a different time for some reason. the USE_TZ=True in my settings, and I don't want to change it. Do you know how I could show the saved value in the database in the template as well? -
Getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'" when trying to update a model object
In my django project, I'm trying to update a Profile object using patch request. When the code gets to ".save()" method, I'm getting "AttributeError: 'ProfileSerializer' object has no attribute '_meta'". Please try to explain the problem to me rather than only giving me the solution. This is my Model: class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, related_name='profile') avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.user.name This is my ProfileSerializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' This is my view: @api_view(['PATCH']) @permission_classes([IsAuthenticated]) def edit_profile(request, user_id): user = request.user if not user.id == user_id: return Response({"message": "You can't edit other's profiles."}, status=status.HTTP_401_UNAUTHORIZED) profile = Profile.objects.get(user=user) serializered_prof = ProfileSerializer(profile) update_prof = ProfileSerializer(serializered_prof, request.data, partial=True) update_prof.is_valid(raise_exception=True) update_prof.save() return Response({'message': 'profile Updated.'}) I dont know why this error is raised. -
Django redirect with corrected optional url params
I am trying to implement stackoverflow's url redirection using django / django rest framework, for example. Say this url - https://stackoverflow.com/questions/3209906/django-return-redirect-with-parameters As long as the question pk (3209906) is correct, stackov will automatically correct the slug (django-return-redirect-with-parameters), even if you pass an incorrect slug. My current code views.py from django.db import models class ArticleBody(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField() def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) return super().save(*args, **kwargs) serializers.py from rest_framework import serializers class ArticleSerializer(serializers.ModelSerializer): class Meta: model = ArticleBody read_only_fields = ( "id", "title" "slug" ) fields = read_only_fields views.py from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .models import ArticleBody from .serializers import ArticleSerializer class ArticleView(APIView): def get(self, request, pk, slug=None): article_obj = ArticleBody.objects.filter(id=pk).last() article = ArticleSerializer(article_obj).data if article: return Response({"article": article}) return Response( {"message": "Article not found"}, status=status.HTTP_404_NOT_FOUND ) urls.py from django.urls import path, re_path from .views import ArticleView app_name = "article" urlpatterns = [ re_path(r"^(?P<pk>\d+)/$", ArticleView.as_view(), name="body"), re_path( r"^(?P<pk>\d+)/(?P<slug>[-\w]+)/$", ArticleView.as_view(), name="body-slug" ), ] Currently this code properly handles valid or invalid slugs. such as http://127.0.0.1:8000/article/1/ http://127.0.0.1:8000/article/1/article-name/ http://127.0.0.1:8000/article/1/artic/ (incorrect slug) Basically I am looking for a way to redirect all of these urls to http://127.0.0.1:8000/article/1/article-name/ -
django-multi-captcha-admin permission denied
I have a Django project up and running. I followed required steps for django-recaptcha and even used captcha v2 in my template. my problem is with the admin site captcha requiring. I tried to use django-multi-captcha-admin package. I followed the documentation steps (this is the documentation) but the problem is when I try to login as admin I see this error: The admin page picture You don’t have permission to view or edit anything. I searched and I didn't find anything on the internet so I asked ChatGPT and this was its answer: Make sure that the middleware of multi_captcha_admin is placed correctly in the MIDDLEWARE list, following the AuthenticationMiddleware: MIDDLEWARE = [ # ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'multi_captcha_admin.middleware.MultiCaptchaAdminMiddleware', # ... ] The new problem with this solution is when I add this part to my MIDDLEWARE I get this error trying to run server: ModuleNotFoundError: No module named 'multi_captcha_admin.middleware' django.core.exceptions.ImproperlyConfigured: WSGI application 'haadijafari.wsgi.application' could not be loaded; Error importing module. -
Trying to find the most efficient way of implementing bingo-guessing game
I'm working on creating a bingo-like quiz game to improve my Django skills. The game begins with a 3x3 grid, with each cell containing a requirement. Some items can fulfill multiple requirements, leading to their placement in multiple cells. Each cell is associated with a list of valid guesses. My goal is to determine the minimum number of guesses needed to fill the entire board. For instance: Cell 1 Cell 2 Cell 3 Cell 4 Cell 5 Cell 6 Alfa Delta Golf Juliett Quebec Sierra Bravo Echo Hotel Kilo Romeo Victor Charlie Foxtrot India Lima Sierra Whiskey Delta November Lima Mike Tango Xray November Whiskey Delta Zulu Bravo Yankee Whiskey Hotel November Oscar Delta Zulu Sierra Sierra Zulu Papa Whiskey Bravo In my initial approach, I aimed to identify the most frequently repeated guesses and then eliminate the associated column. However, I encountered difficulties when dealing with ties, triple ties, and ties for the second most repeated guesses. Although I'm implementing this in Django, I haven't included the model code here as I'm focused on understanding the underlying logic before coding it. I've already experimented with various strategies, including using AI, but the results were either extremely inefficient or failed … -
How to configure nginx to serve multi-tenant django application
I would like to deploy a django application with the django-tenants library. The project works fine locally, I can create tenants and access them via localhost:8000 Now I am trying to deploy the application on DigitalOcean using docker-compose and I have an issue with configuring the nginx server. As the log suggests I am able to start the gunicorn server on 0.0.0.0:8000 but the proxy can only reach the application like this: wget <DOMAIN>:8000 but not like this: wget <CONTAINER_NAME>:8000 (the container name in the docker-compose yml is 'web') The http response is 504 - Gateway Time-out Here is my NGINX config: server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name .<DOMAIN>; set $base /etc/nginx/sites-available/trackeree.com; # SSL ssl_certificate /etc/letsencrypt/live/trackeree.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/trackeree.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/trackeree.com/chain.pem; # security include /etc/nginx/security.conf; # logging access_log /var/log/nginx/access.log combined buffer=512k flush=1m; error_log /var/log/nginx/error.log warn; location / { uwsgi_pass web:8000; include /etc/nginx/uwsgi.conf; } # Django media location /media/ { alias $base/media/; } # Django static location /static/ { alias $base/static/; } # additional config include /etc/nginx/general.conf; } # non-www, subdomains redirect server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.<DOMAIN>; # SSL ssl_certificate /etc/letsencrypt/live/trackeree.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/trackeree.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/trackeree.com/chain.pem; return 301 https://trackeree.com$request_uri; } # … -
Trying to install pip dependencies from a bash script
Trying the create setup.sh script file in my current Django project's root directory. Don't have too much experience with bash scripting , so to be honest from file access to configuration the issue can be anything. So what I'm trying to run looks like this: setupBackend() { echo "--------------------------- Creating virtual environment ----------------------" pip install --upgrade pip pip install virtualenv virtualenv venv source ./venv/Scripts/active echo "----------------------- Installing dependencies ------------------------------" pip install -r requirements.txt echo "----------------------- Running Django server -------------------------" python ./kudelasz/manage.py runserver } And I have this requirements file containing the dependencies asgiref==3.7.2 colorama==0.4.6 distlib==0.3.6 Django==4.2.2 django-tailwind==3.6.0 djangorestframework==3.14.0 djangorestframework-jsonapi==6.0.0 filelock==3.12.2 inflection==0.5.1 mysqlclient==2.2.0 platformdirs==3.7.0 PyMySQL==1.1.0 PyPDF2==3.0.1 pytz==2023.3 sqlparse==0.4.4 termcolor==2.3.0 tzdata==2023.3 virtualenv==20.23.1 The probalem I'm facing is, that when the script runs the pip installation, it seems to be trying to install all these stuffs to the global python environment. At least that's what I'm assuming, because it tell me this: "Requirement already satisfied: asgiref==3.7.2 in c:\users\customer\appdata\local\programs\python\python311\lib\site-packages (from -r requirements.txt (line 1)) (3.7.2)" at each package installation attempt. I can also see in my venv directory that none of those packages get installed, only the default pip dependencies can be seen. In the end the installation fails due dependency conflicts. For now … -
Cant add image and media files from database on production mode Django Cpanel
i have a website based Django mysql and my problem is when i want to add mediafiles(images and etc) from database in django admin panel , idk why but its doesnt work and its doesn`t show me any error! just 10 second wait and after that it whows me this : This site can’t be reached im using Cpanel and my code in setting is : for url : + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) setting : MEDIA_URL = "media/" MEDIA_ROOT = "/home/samaliz1/public_html/media" STATIC_ROOT = "/home/samaliz1/public_html/static" and model: prof_pic = models.ImageField(upload_to="img/prof_pics", null=True, blank=True) i should say that my staticfiles working perfectly but idk why my media doesnt i will be so thankfull if u guys help me <3 -
Change the default route from / to /docuseal/
I don’t know if it’s the good section but my problem is the following one : In my VM, I have a django server running with gunicorn and nginx and I would like to add a docuseal entity running with ruby on rails on the website (docuseal is also running with nginx). In fact, I figure out how to make my nginx configuration. So I can access docuseal by the url mydomaine/docuseal/, all the other are manage by django. However, all the route in my docuseal app start with ‘/’, but as I say, it’s django part. So I would like to “shift” all the docuseal routes from “/…” to “/docuseal/…”. I tried to make change in config/routes.rb but I didn’t succeed. Can somebody help me please. Thanks you ! -
Django template regroup - unable to print unique data
I want to print the data in my template in the following format Date 1-> Event ID 1a --> Table showing data for that date and event Event ID 2b --> Table showing data for that date and event Date 2-> Event ID 2a --> Table showing data for that date and event Event ID 2b --> Table showing data for that date and event Views.py #some code source_metadata=MetadataTable.objects.filter(sync_id=sync_detail.id) synclogs = SyncLog.objects.filter(sync_id=sync_detail.id) logs_by_date = {} sync_logs = SyncLog.objects.filter(sync_id=sync_detail.id).order_by('-date_added') # Replace with your desired ordering for log in sync_logs: date = log.date_added.date() if date not in logs_by_date: logs_by_date[date] = [] logs_by_date[date].append(log) And templates.py div class="container"> {% for date, logs in logs_by_date.items %} <div class="card"> <div class="card-header"> <a href="#" class="date-link" data-toggle="collapse" data-target="#collapse-{{ date|date:'mdy' }}">{{ date |date:"m/d/y" }}</a> </div> <div id="collapse-{{ date|date:'mdy' }}" class="collapse"> <div class="card-body"> {% with last_event_id=None %} {% for log in logs %} {% if forloop.first or log.sync_event_id != last_event_id %} {% with last_event_id=log.sync_event_id %} <div class="card event-card"> <div class="card-header"> <a href="#" class="event-link" data-toggle="collapse" data-target="#event-collapse-{{ date|date:'mdy' }}-{{ log.sync_event_id }}">Event {{ log.sync_event_id }}</a> </div> <div id="event-collapse-{{ date|date:'mdy' }}-{{ log.sync_event_id }}" class="collapse"> <div class="card-body"> <!-- Display the SyncLog records for the selected date and event in a table --> <table class="table table-nowrap … -
No module named 'attachments.wsgi' in render
I am trying to upload my django project to render but I am finding this error No module found on 'attachment.wsgi' enter image description here I tried to publish the site. Tried to change the wsgi page but no success please help me solve this error or how should the wsgi page be like? -
How do i download and uploaded file in django database?
i have three different files on my database and they belong to users, like each user uploads three different files and they all have a "reg no" as a unique number and i want to download those files base on their "reg no". i will appreciate new code snippet my views.py def download_file(request, regno): regno = request.session.get('reg_no_admin') file = CacAdmin.objects.get(regNo=regno) response = FileResponse(open(file.filePath, 'rb')) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = f'attachment; filename="{file.fileName}"' return response urls.py path('private/download-file/<int:regno>/', views.download_file, name="download_file"), html <a href="{% url 'download_file' file.regNo %}">Download File</a> -
How to make jwt check global
I am adding authoraziation with jwt in react for frontend and django for the backend. When an access token expires I refresh it using axios interceptors. If the refresh token expires then the user logs out. I store the tokens in localStorage and to log out the user I just delete them. useAxios.js .... axiosInstance.interceptors.request.use(async req => { const user = jwt_decode(authTokens.access) const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1; console.log(isExpired) if(!isExpired) return req const response = await axios.post(`${baseURL}/token/refresh/`, { refresh: authTokens.refresh }).catch(err=>localStorage.clear()) localStorage.setItem('authTokens', JSON.stringify(response.data)) setAuthTokens(response.data) setUser(jwt_decode(response.data.access)) req.headers.Authorization = `Bearer ${response.data.access}` return req }) I have also a file called AuthContext.js where the function to login the user is and where the tokens are made. Home.js ... let api = useAxios() let getUser = async () => { let response = await api.get('http://127.0.0.1:8000/a/') console.log(response.data) if (response.status === 200) { console.log(response.data) } } useEffect(()=>{ console.log('hey') getUser() },[]) ... So basically when the user enters the home page I am sending a request in django where you need to be authenticated to have access. So if the user's refresh token has expired then I log him out. The problem is that I don't want to write the getUser function for every single page to … -
HI i have two models called Category and item and each item has a category please how can i display all the items that are in the same category [closed]
MY MODELS.PY enter image description here MY VIEWS.PY enter image description here MY URLS.PY enter image description here .............................................................................................................................................................................................. ERROR I AM GETTING enter image description here -
User registration was working fine few days ago. Now i get 401 unauthorized response when i try to register in thunder client. am a beginner
I am making a shopify inspired django project using restframework. in my project, I have two types of users, one is the default User model and another is custom user model 'Seller'. Here is the code for the model class SellerUserManager(BaseUserManager): def create_user(self,email,password=None,**extra_fields): email=self.normalize_email(email) user=self.model(email=email,**extra_fields) user.set_password(password) extra_fields.setdefault('is_staff',True) #is_staff will let the user made here to have some admin accesses user.save() return user def create_superuser(self,email,password=None,**extra_fields): # this is a bit unnecessary as seller wont be allowed to acess the administration extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) # Since sellers would be different types of users they are custom users inherited from abstractbaseuser class Seller(AbstractBaseUser,PermissionsMixin): email=models.EmailField(unique=True,max_length=255,) # i don't have to create a passeord field as it is automatically inherited from abstractuser first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) company_name=models.CharField(max_length=100) seller_desc=models.TextField() seller_image=models.FileField(upload_to='seller/sellerImage',null=True) seller_verification=models.FileField(upload_to='seller/sellerVerification',null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateField(auto_now=True) status=models.BooleanField(default=False,null=True) #verification status objects=SellerUserManager() USERNAME_FIELD='email' #this makes it so that email is used as a unique identifier and not username EMAIL_FIELD='email' REQUIRED_FIELDS=[] # some errors that was solved by chat gpt that said to do these. groups = models.ManyToManyField('auth.Group', related_name='seller_users') user_permissions = models.ManyToManyField('auth.Permission', related_name='seller_users') def __str__(self): return self.email Here is my serializers.py code: class SellerRegistrationSerializer(serializers.ModelSerializer): class Meta: model=Seller fields=['email','password','first_name','last_name','company_name','seller_desc','seller_image','seller_verification'] extra_kwargs={ 'password':{'write_only':True} } #def create should be done since this is a custom User … -
SignatureDoesNotMatch DigitalOcean Spaces Boto3 Django-Storages Django
You got the following error while using your digital ocean spaces for static files: <Error> <Code>SignatureDoesNotMatch</Code> <RequestId>xxxxx-716fe6ea-xxxx</RequestId> <HostId>xxx-nyc3c-xxx-xxxx</HostId> </Error> GET 403 Forbidden -
For looping in Django not worked
Hi I am newbie in django, I have problem with for looping in django, to make a navbar/menu, I use for looping in html like this: <div class="menu"> <a href="/"> <div class="menu-link klik"> <i class="bx bx-home"></i> <div class="contentMenu hidden">HOME</div> </div> </a> for key,value in menu.items %} <a href="{% url 'app_'|add:key|add:':'|add:key %}"> <div class="menu-link klik"> <i class="{{value}}"></i> <div class="contentMenu hidden">{{key|upper}}</div> </div> </a> endfor %} </div> and the views: from django.shortcuts import render from .forms import ProjectForm def index(request): projectForm = ProjectForm() context = { 'title': 'Achmad Irfan Afandi', 'tile': 'Home', 'subtitle': 'Data Analyst', 'social_media': {'linkedin':'https://www.linkedin.com/in/achmad-irfan-afandi-9661131a6/', 'github':'https://www.github.com/achmadirfana', 'facebook':'https://www.facebook.com/achmad.irfan.754', 'twitter':'https://www.facebook.com/achmad.irfan.754', 'instagram':'https://www.facebook.com/achmad.irfan.754'}, 'menu': {'about': 'bi bi-file-earmark-person', 'education': 'bx bxs-graduation', 'skill': 'bx bx-wrench', 'projects': 'bx bx-building', 'services': 'bx bx-support', 'contact': 'bx bxs-contact'}, 'projectForm': projectForm } return render(request, 'index.html', context) that code above is in main app projec, all the menus are displayed properly like picture above: enter image description here But in another app (btw I use extends tag for all app) , the for looping is not displayed , it just show 'HOME' menu that not include in for looping like picture below: enter image description here Do you know why? or I have to write the menu one by one not use foor … -
Checking if there are security issues with my django form
I hope you can help me clarify some things regarding my django form, which is used for a chat app. Honestly, I don't know a lot about security against hackers, so my concern is mainly related to form security. My questions are simply put... Did I do django form backend validation correctly? I read that backend validation prevents hackers from injecting malicious codes into the database. Are there any other security issues in my code? I hope you can point out even very basic things I might be missing out. Here is my template <form id="post-form"> {% csrf_token %} <input type="hidden" name="user_id" id="user_id" value="{{user_id}}"/> <input type="text" name="var1" id="var1" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/submit/', data:{ user_id:$('#user_id').val(), var1:$('#var1').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ alert(data) } }); document.getElementById('var1').value = '' }); </script> </html> Here is my views.py for the ajax: @login_required def submit(request): if request.method == 'POST': user_id = int(request.POST['user_id']) form = ChatForm(request.POST) if isinstance(user_id, int) and form.is_valid(): chat_instance = form.save(commit=False) user = User.objects.get(id=user_id) chat_instance.var2 = form.cleaned_data['var1']+"edited" chat_instance.user = user if request.user.is_admin: chat_instance.admin = True else: chat_instance.admin= False chat_instance.save() return HttpResponse('Message sent successfully') else: return HttpResponse('Error') return HttpResponse('Not a valid request method') Here is … -
Got an error while running a django project in docker
This site can’t be reached The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID I want the correct starting page of first page of project.I tried multiple times, but the error is same. -
how can I stop django-elasticsearch-dsl search_index command from taking input?
In order for django-elastic-dsl to index the documents we have to run python manage.py search_index --rebuild on every deploy. so I faced an issue having docker-compose executing my django project and that is: File "/root/.local/share/virtualenvs/django-lHo0u5mj/lib/python3.11/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 172, in _delete 2023-08-20T13:58:47.033526087Z response = input( 2023-08-20T13:58:47.033533712Z ^^^^^^ 2023-08-20T13:58:47.033537712Z EOFError: EOF when reading a line apparently this command is prompting an input from the user and it's called on every docker-compose build command, here is my start.sh file: #!/usr/bin/env bash pipenv run python manage.py makemigrations pipenv run python manage.py migrate pipenv run python manage.py search_index --rebuild #pipenv run python manage.py collectstatic --no-input pipenv run gunicorn --reload --bind 0.0.0.0:8000 service_monitoring.wsgi:application what is the workaround of not running the command mannually everytime I start the container? -
Wagtail fields not showing up in pages list response
Im using Wagtail with django and I'm following the tutorial. I've got a BlogPage like so: class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) # Add this: authors = ParentalManyToManyField("blog.Author", blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) api_fields: list[APIField] = [ APIField("tags"), APIField("date"), APIField("authors", serializer=AuthorSerializer(many=True)), APIField("intro"), APIField("body"), ] and when I go to a detail view, I'm able to see the fields e.g.http://127.0.0.1:8000/api/v2/pages/5/ { "id": 5, "meta": { "type": "blog.BlogPage", "detail_url": "http://localhost/api/v2/pages/5/", "html_url": "http://localhost/blog/first-blog-post/", "slug": "first-blog-post", "show_in_menus": false, "seo_title": "", "search_description": "", "first_published_at": "2023-08-20T04:37:17.102729Z", "alias_of": null, "parent": { "id": 4, "meta": { "type": "blog.BlogIndexPage", "detail_url": "http://localhost/api/v2/pages/4/", "html_url": "http://localhost/blog/" }, "title": "Our blog" } }, "title": "First blog post", "tags": [ "react" ], "date": "2023-08-20", "authors": [ { "name": "Brad", "author_image": "/media/original_images/71UHg51kgKL._AC_SY679_.jpg" } ], "intro": "This is a blog post intro", "body": "<p data-block-key=\"q28xv\">Hello World</p>" } However, in the list view, this same page does not contain those fields. I have tried using the fields=* parameter in the url and still, all that shows up is the title e.g http://127.0.0.1:8000/api/v2/pages/ { "meta": { "total_count": 3 }, "items": [ { "id": 3, "meta": { "type": "home.HomePage", "detail_url": "http://localhost/api/v2/pages/3/", "html_url": "http://localhost/", "slug": "home", "first_published_at": "2023-08-20T04:23:02.114917Z" }, "title": "Home" }, { "id": …