Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sleep() not working with stacked query in mysql-connector-python
I am working on creating a security based CTF application in Django. The current exercise I am building is a blind time-based sql injection. As Django does not appear to support stacked queries through Model.raw(), I imported the mysql-connector-python which does support stacked queries using the cursor.execute(query, multi=True). However, when attempting to use sleep(X) in the stacked query, the sleep statement won't execute. The following is one example: view: query = f"select sleep(2); select 1;" mydb = mysql.connector.connect( host="localhost", user="****", password="****", database="****" ) cursor = mydb.cursor() cursor.execute(query, multi=True) return HttpResponse(f"query: {cursor}") sqli script: url = f"http://127.0.0.1:8080/books/book/?q=1" start = time.perf_counter() response = requests.get(f'{url}') end = time.perf_counter() print(response.text) print(f'response time: {end-start}') This will return the following: query: MySQLCursor: select sleep(2); select 1; response time: 0.005476321006426588 However, if dropping multi=True and running a single query, it the sleep will work just fine. view: query = f"select sleep(2);" mydb = mysql.connector.connect( host="localhost", user="****", password="****", database="****" ) cursor = mydb.cursor() cursor.execute(query) return HttpResponse(f"query: {cursor}") sqli script: url = f"http://127.0.0.1:8080/books/book/?q=1" start = time.perf_counter() response = requests.get(f'{url}') end = time.perf_counter() print(response.text) print(f'response time: {end-start}') This will return the following: query: MySQLCursor: select sleep(2); response time: 2.010241993004456 Note that I have tried using do sleep(X) and it also … -
TypeError: EmailVerificationTokenGenerator.make_token() missing 1 required positional argument: 'contact_form'
I am trying to build an email server for my website. I have a contact form and when you pass it, the server sends a verification link to email address specified in the form. Also, a response after submitting the contact form includes a unique link to re-send new verification link. On the surface my implementation looks fine, but now I am stuck on this error: TypeError at /api/contact/ EmailVerificationTokenGenerator.make_token() missing 1 required positional argument: 'contact_form'. "error screenshot views.py: from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ContactFormSerializer from .verification import EmailVerificationTokenGenerator from .models import ContactForm from email_server.permissions import CanResendVerificationLink from rest_framework import status from django.urls import reverse import secrets from django.shortcuts import get_object_or_404 # Base Mixin class EmailVerificationMixin: def _send_email_verification(self, contact_form): subject = 'Verify Your Email' uidb64 = urlsafe_base64_encode(force_bytes(contact_form.pk)) verification_token = EmailVerificationTokenGenerator().make_token(contact_form) verification_link = self._get_verification_link(contact_form, uidb64, verification_token) body = render_to_string( 'email_verification.html', { 'verification_link': verification_link, } ) email = EmailMessage(subject=subject, body=body, to=[contact_form.email]) email.send() def _get_verification_link(self, contact_form, uidb64, token): current_site = get_current_site(self.request) verification_url = reverse('activate', kwargs={'uidb64': uidb64, 'token': token}) verification_link = f'{self.request.scheme}://{current_site.domain}{verification_url}' return verification_link def _get_resend_verification_link(self, … -
Unable to login in custom user model
I have custom user model that works goods for registration and creating superuser. But it fails to login. I have been trying to rectify the problem but couldn't find any potential errors... Login Form is not logging in the user when I submit the form, it just says the user with that username already exists (it is kind of acting like signup page) How to resolve this issue or else i get a 'page not accessible contact owner of the site' #models.py class Organisation(models.Model): organisation_name = models.CharField(max_length = 256) contact_no = models.IntegerField() email = models.EmailField() class Meta(): unique_together = ['organisation_name','email'] def __str__(self): return self.organisation_name class MyUserManager(BaseUserManager): def create_user(self, username, organisation, email, password): if not organisation: raise ValueError("Users must have an organisation") email = self.normalize_email(email) user = self.model(username=username, email=email, organisation=organisation) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, username, email, password): user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.is_superuser = True user.is_staff = True user.save(using=self.db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=256,unique=True) email = models.EmailField(max_length=256) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,null=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = MyUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True #forms.py class MyUserForm(forms.ModelForm): class Meta(): model = models.MyUser fields = … -
How to abort a long request in Django and stop processing?
There might be cases in my API when a single request will take more than 10 seconds, in which case I want to abort the processing and return some error. I've done some research and I know that just aborting the request to the server is not enough, and that won't be pushed to the Django server. I was wondering whether there is a way to do this? -
django formset is not working, like im expecting
I have OrderItemFormSet like class OrderForm(forms.ModelForm): class Meta: model = Order fields = ["total_cost"] class OrderItemForm(forms.ModelForm): class Meta: model = OrderItem fields = ["product", "quantity"] OrderItemFormSet = forms.inlineformset_factory( Order, OrderItem, form=OrderItemForm, extra=1, # Set the number of empty forms to display ) and view class CreateOrderView(View): template_name = "orders/create_order.html" def get(self, request): order_form = OrderForm() order_item_formset = OrderItemFormSet() return render( request, self.template_name, { "order_form": order_form, "order_item_formset": order_item_formset, }, ) def post(self, request): order_form = OrderForm(request.POST) order_item_formset = OrderItemFormSet(request.POST, prefix="order_item") if order_form.is_valid() and order_item_formset.is_valid(): order = order_form.save(commit=False) order.user = request.user # Assign the currently logged-in user order.save() order_item_formset.instance = order if ( order_item_formset.has_changed() ): # Check if there are any additional forms order_item_formset.save() # Save the additional forms # order_item_formset.save() return redirect("dashboard:dashboard") return render( request, self.template_name, { "order_form": order_form, "order_item_formset": order_item_formset, }, ) my template <form method="post" id="order-form"> {% csrf_token %} <fieldset> <legend>{% trans "Order Information" %}</legend> {{ order_form|crispy }} </fieldset> <fieldset> <legend>Order Items</legend> {{ order_item_formset.management_form }} <div id="order-items-container"> {% for form in order_item_formset %} <div class="order-item-form">{{ form|crispy }}</div> {% endfor %} <input type="hidden" name="ORDER_FORMS-TOTAL_FORMS" value="{{ order_item_formset.total_form_count }}"> </div> </fieldset> <div class="col-sm-12 d-flex justify-content-end"> <button class="btn btn-light-secondary me-1 mb-1" type="button" id="add-order-item">{% trans "Add Order Item" %}</button> <button class="btn btn-primary me-1 mb-1" … -
Django df to html show text
I am totally a new bee in Django, it's my 2nd day to learn it. I have already connected to the database and use the pandas.read_sql_query to get the df from database (I know there is ORM but since we use MSSQL, so it need more time for me to figure it out, and I really need to show sth at lease so I use pandas.read_sql_query) I have already got the df and I want it to show in the html. According to some other posts, I use the code below: view.py a_query=""" select * FROM db """ a = pandas.read_sql_query(a_query,connection) a_html = a.to_html(index=False) print(a) print(type(a)) return render(request, 'index.html',{'a_html':a_html}) the type shows: So I think it's all good. <class 'pandas.core.frame.DataFrame'> index.html I put {{a_html}} in the body part, it's the only thing I change after the original format. after I run the manage.py, it shows this in html: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>IT Business Service</th> <th>IT Service Instance</th> </tr> </thead> <tbody> <tr> <td> sth like that. But I want to to show the table, how should I do for it? Any help is really apprecaited! -
How to check the type of user logged in django?
I want to check the type of user logged in and return the template according to the user logged in. How can I check the type of user? This is my django model: class UserProfile(models.Model): user = models.OneToOneField(User , on_delete= models.CASCADE) class Student(models.Model): profile = models.OneToOneField(User, on_delete= models.CASCADE) rollNo = models.CharField(max_length=15) def __str__(self): return (self.rollNo) class Supervisor(models.Model): profile = models.OneToOneField(User, on_delete= models.CASCADE) teacher_ID = models.CharField(max_length=15) def __str__(self): return (self.profile) I have tried the following statements but it gives an error: def homePage(request): if not request.user.is_authenticated: return render(request , 'accounts/login.html') user = request.user is_student = Student.objects.filter(profile__user=user).exists() is_supervisor = Supervisor.objects.filter(profile__user=user).exists() return HttpResponse("Hello") Error: Unsupported lookup 'user' for OneToOneField or join on the field not permitted. -
What's the best way to automatically generate a .env-sample file from a .env file using Python or shell commands?
I've been using python-decouple to read my .env file, and it has been working great. To ensure that sensitive information is not pushed to GitHub, I've been manually creating a .env-sample file with just the variable names and pushing that to the repository instead. However, I sometimes forget to update the .env-sample file when I make changes to the .env file. It's a manual task that can be quite error-prone. I was wondering if there is an automatic way to generate the .env-sample file using Python or any other shell commands. It would be super helpful if there's a more efficient and reliable approach to keeping my sample file up to date. -
How to get username of a user by his email in django (he shold be not loged in) [closed]
my_user=User.objects.create_user(email=Email, password=Password, username=username, first_name=Last_Name) my_user.save() Here is the code for how I registered the user in Django -
Why is the my form not submitting all the fields i filled and how do i fix it?
On my real estate Django web app, I have a form which users fill to list their property or get services. The form to be filled differs depending on the type of property in question(Single or Multiple apartment properties) so I used Tailwindcss to display these forms depending on the user's choice <form class="border-3 border-red-400 p-11 block space-y-4 justify-center w-screen h-screen items-center" action="{% url 'requestservice:req_service' %}" method="POST"> <input type="radio" id="single" value="SINGLE" class="peer/single" name="property_type" checked /> <label for="single" class="peer-checked/single:text-sky-500">Single Unit</label> <input type="radio" id="multiple" value="MULTIPLE" class="peer/multiple" name="property_type" /> <label for="draft" class="peer-checked/multiple:text-sky-500">Multiple D. Unit</label> <div class="hidden peer-checked/multiple:block bg-white px-2 py-1 w-full space-y-2 md:space-y-3 rounded-xl"> <!-- <h3> M.D.U Unit Form </h3> --> <div class="block"> <p class="font-medium text-gray-950 text-sm"> Name of property: </p> <input type='text' class="w-full p-1 focus:border-1 focus:outline-yellow-300 border border-red-100 shadow-md shadow-red-100 rounded-lg " placeholder="Property name"> </div> <div class="font-medium flex space-x-5"> <p class="font-medium text-sm"> Central Server Room Avaliable: </p> <input type="radio"> </div> <div class="block "> <p class="font-medium text-sm"> Number of houses in MDU </p> <input placeholder="Number of houses" class="w-full p-1 focus:border-1 focus:outline-yellow-300 border border-red-100 shadow-md shadow-red-100 rounded-lg" type="number"> </div> </div> <div class="hidden peer-checked/single:block bg-white px-2 py-1 space-y-2 w-full rounded-xl"> <!-- <h3> Single Unit Form </h3> --> <div class="block space-y-1"> <p class="font-medium"> Name of property: … -
django how can i display multiple pictures by id inside multiple items
i have 2 classes in my models.py class Product(models.Model): ext... and class ProductImage(models.Model): product=models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image=models.ImageField views.py def view_property(request, id): photo = get_object_or_404(ProductImage, id=id) product = get_object_or_404(Product, id=id) photos = ProductImage.objects.filter(product=product) context = { 'photo':photo, 'product':product, 'photos': photos } return render(request,'products/view_property.html', context) so to display multiple images in my html page i include int:id or samthing like that in the url.py url.py from django.urls import path from . import views urlpatterns = [ path( '<int:id>/' , views.view_property , name = 'view_property' ), ] Now when I want to fetch data to my view_property.html page, I get the images filtered fine by ID, so it works, but the problem is in my view_property.html page On the page I have items, each item contains the product and pictures in the slider so i want to fetch multiple products each product fetch his images filtred by id view_property.html <div class="box-container"> {% for pro in products %} <div class="box"> <div class="image-container"> {% for img in photos %} <div class="mySlides"><img src="{{img.image.url}}" alt=""></div> {% endfor %} </div> <div class="content"> <div class="location"> <p>apartments</p> </div> </div> </div> {% endfor %} </div> her i get all images of one product same thing with each items because i fetching … -
How to upload screensot if the task is completed in django rest api
Model This is the model i created this model inside the Admin app class AndroidApp(models.Model): name = models.CharField(max_length=100) link = models.URLField() category = models.CharField(max_length=100) subcategory = models.CharField(max_length=100) image = models.ImageField(upload_to='app_images/') completed = models.BooleanField(default=False) points = models.IntegerField() View class UserAppDetailedView(APIView): def get(self,request,id): try: app = AndroidApp.objects.get(id=id) except AndroidApp.DoesNotExist: return Response({'message': 'App not found.'}, status=404) serializer = AndroidAppSerializer(app) return Response(serializer.data) def put(self, request, id): try: app = AndroidApp.objects.get(id=id) except AndroidApp.DoesNotExist: return Response({'message': 'App not found.'}, status=404) if app.completed: return Response({'message': 'App already completed.'}) app.completed = True app.save() serializer = AndroidAppSerializer(app) return Response(serializer.data) def patch(self, request, id): app = AndroidApp.objects.get(id=id) if app: serializer = AndroidAppSerializer(app, data=request.data, partial=True) if serializer.is_valid(): if app.completed: screenshot = serializer.validated_data.get('screenshot', None) if screenshot: app.screenshot = screenshot app.save() return Response(serializer.data) return Response({'message': 'Please provide a screenshot image.'}, status=400) else: return Response({'message': 'App task is not completed.'}, status=400) return Response(serializer.errors, status=400) return Response({'message': 'App not found.'}, status=404) In tis code im trying to do first i check the app(task) is completed or not if the task is not completed the updated the task as true . it is working and after that i ant to upload the screen shot if the task is completed . so in my settings.py file i … -
TypeError at /saml2/ls/post/ Not a logout_response
I am trying to setup django with saml2 for sso with okta. In okta settings I have Single Logout URL: http://localhost:8000/saml2/ls/post/ SP Issuer : http://localhost:8000/saml2/metadata/ as per the documentation. In my settings.py I have the example config shown in the okta example, and have the LOGIN_REDIRECT_URL = '/home' and the 'home' path exists and works. When I login using http://localhost:8000/saml2/login/, I am correctly signed in (the saml_session cookie is created), but I am redirected to http://localhost:8000/saml2/ls/post/ and shown the error: TypeError at /saml2/ls/post/ Not a logout_response. Does anyone have any suggestions? The redirect url is not being accessed and/or the login is triggering a logout and I am not sure how to proceed! Thank you! -
Need to group the apps in the sidebar of django admin using the package jazzmin
As you can see in the image i have managed to group the apps in the landaing page of dashboard but nit in side bar. i need to group the models in the side bar too. i have used the jazzmin package as well as the admin_reorder -
New relic showing Transaction as views.function_name for pyhton services while I want to show API endpoint
I am checking transaction data for one of my APIs on Django and getting new relic Transactions as a.views:function1_name and a.views.function2_name, while I want to show API endpoints in transactions. How can I do this? -
django /admin showing react index.html page wiith when runing behind nginx
I am following this guide React-django-nginx, I am unable to access /admin it shows blank page with react's index.html page code inside it. but when access /admin by hard refreshing the page then it works correctly. all the configurations in conf file are same as this guide -
Pdf file is not displaying on frontend
I have uploaded the pdf file in django admin panel. However, when I try to open the pdf file in html file tag, it is not opening. HTML code: <a href="{{ opinion.tests }}">Your tests</a> </div> views.py: def report(request): if request.method == 'POST': try: name = request.POST['name'] phone1 = request.POST['phone'] print("name:", name, "phone", type(phone1)) analysis = Report.objects.filter(phone=phone1)[0] opinion = {'opinion': analysis} return render(request, "reports.html", opinion) except: return render(request,"not_found.html") models.py: class Report(models.Model): current_date = str(datetime.date.today()) name= models.CharField(max_length=100) email= models.EmailField(max_length=1000) phone = models.IntegerField() previous_history =models.TextField(max_length=5000) current_diagnosis= models.TextField(max_length=5000) doctor = models.CharField(max_length=100) tests = models.FileField(upload_to='ptest/', default="") def __str__(self): return self.name + " | " + "Doctor : "+ self.doctor File is displaying in admin panel. It is also uploading in the backend. The html page also displays without any error. However, when I click to open to see the file , it gives an error. I am uploading a pdf file and i am expecting the file to be displayed in html file in the frontend. -
Django edit_post view not prepopulating form fields with existing data
I'm developing a Django blog application and I have a view to edit a post. However, when I click the Edit button, the form fields do not appear prepopulated with the existing data. Here's my edit_post view code: def edit_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect("main_page") else: form = PostForm(instance=post) context_dict = { "form": form, "post": post, } return render(request, "blog/edit_post.html", context_dict) I have verified that the PostForm is correctly configured with the required fields from the Post model. I also tried using the @never_cache decorator, but it didn't resolve the issue. I'm not sure why the form fields are not prepopulated with the existing data after submitting the form. It only works when I manually reload the page. Any suggestions or insights on how to fix this issue would be greatly appreciated. -
Deadlock with Django and MYSQL
I am getting some deadlocks in my project where I have multiple processes altering the same objects in the database. I have an endpoint whose point is to fetch the most recent unfinished play and then proceed to alter it if one exists, if not then it should create one. I need to make sure that if I receive 2 concurrent requests in this endpoint one of them creates the object and the other one blocks execution until that one is created and then the second one will alter the object created. In my django application I have the following query for that inside transaction.atomic() context: # Use list to force evaluation play = list(Play.objects.select_for_update().filter( game=self.game, user=self.user, discard=False, finished=False, ) ) It used to be .last() but I read that the ORDER BY it performs in the database query would sometimes raise problems with deadlocks so I tried this instead. From my understanding (which is probably flawed) MYSQL should acquire an exclusive record lock on the finished index (I have that as index in my database) which would not allow for an object to be created while this transaction is occurring and any transaction that tries to would be blocked … -
Django WSGI: no module named 'my_app.settings'
I've looked carefully through all similar questions on stackoverflow but found no working solution. I have a problem running wsgi.py file due to the ModuleNotFoundError: No module named 'magic_orb.settings' (I'm creating a magic orb with predictions based on AstroGPT). My wsgi.py file looks like this: import os import sys proj_path = ("../magic_orb") sys.path.append(proj_path) os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "magic_orb.settings") os.chdir(proj_path) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() As you may see, I've already tried changing the path and adding get_wsgi_application. Moreover, I've added django.setup() to the manage.py file as my main problem is with app loading. My project's structure is the following: magic_orb ├── db.sqlite3 ├── frontpage │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_frontpage.py │ │ ├── 0002_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── magic_orb │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── magic_orb_model │ ├── pretrained_model.py │ └── __pycache__ ├── manage.py └── user_data_form ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_user_data_form.py │ ├── __init__.py │ └── __pycache__ ├── models.py ├── __pycache__ ├── … -
DevTools failed to load source map: Could not load content for ..../bootstrap.min.css.map: Unexpected token '<', "<!doctype "... is not valid JSON
i am using react and django for my web app. it works fine on local machine but shows this warning on server. the file it showing in the warning was not here so i copy it from the asset folder but still not working. Permissions are given to the file -
graphene multible queries and mutation
I try to update my schema.py. This is previous code: from graphene import Schema, Field, ObjectType from .basic_objects.queries import BasicQuery from .basic_objects.mutations import BasicMutation schema = Schema(query=BasicQuery, mutation=BasicMutation) Updated code: from graphene import Schema, Field, ObjectType from .basic_objects.queries import BasicQuery from .basic_objects.mutations import BasicMutation class Query(ObjectType): BasicQuery = Field(BasicQuery) #otherQuery class Mutation(ObjectType): BasicMutation = Field(BasicMutation) schema = Schema(query=Query, mutation=Mutation) I will have many Queries and mutations so I want to handle the problem like this. But while I try to send request it look like this: query MyQuery { BasicQueryData { oneNode(id: 1) { comment coordinateY } } } from query oneNode directly working and graphene find the method and it is working. how can I make that this time from query first go to BasicQueryData and then call oneNode method? -
Why email is not shown as a Json response in django rest api
View class UserRegistrationView(APIView): def post(self, request): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() token = Token.objects.create(user=user) response_data = { 'token': token.key, 'message': 'User registration successful.' } return Response(response_data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user def validate_username(self, data): if User.objects.filter(username=data).exists(): raise serializers.ValidationError("Username already exists.") return data def validate_email(self, data): if User.objects.filter(email=data).exists(): raise serializers.ValidationError("Email already exists.") return data url path('reg/',UserRegistrationView.as_view(), name='userreg' ) in my post request i got only { "username": [ "This field is required." ], "password": [ "This field is required." ] } In this serializer i passed the fields such as username password and email.. but i got only email and username as a json response why email is not showing as a json response. -
Page not found (404) django problem!What to do?
My project "mysite" has one app "polls" in it When i run my server i receive 404 error: Here is my code: mysite/settings.py INSTALLED_APPS = [ 'polls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") polls/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] How can I fix this problem? -
Django admin request got values for both 'fields' and 'body' error when trying to save entry with CloudinaryField attribute
I am working on a Django project and suddenly I have found that when user tries to save a new entry with an image there is an exception: request got values for both 'fields' and 'body', can only specify one I am using the Django Admin in conjunction with the Cloudinary library where I am using the CloudinaryField on the specific table. In addition, I have one to many relationship between MainEntity and Picture. The Picture model holds a CloudinaryField. When I am trying to use traceback to get a detailed error I am getting another error related with database: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. The problem arises when I am calling the save method manually after the overridden that I have made in Picture model: def save(self, *args, **kwargs): if not self.order: self.order = self.mainEntity.number_of_pictures() + 1 try: super(Picture, self).save(*args, **kwargs) except BaseException: traceback.print_exc() What I have found is that the exception happens in request_encode_body method that you can find in this url. Although, I cannot understand why this is happening and what causes this issue! Thank you! What I have tried in detail I have …