Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
download file from url in django
I want to download a file from a URL. Actually, I want to get the file from a URL and return it when the user requests to get that file for download. I am using this codes: def download(request): file = 'example.com/video.mp4'' name = 'file name' response = HttpResponse(file) response['Content-Disposition'] = f'attachment; filename={name}' return response but it cant return file for download. These codes return a file, but the file is not in the URL. how can I fix it? -
Handle file downloads in Flutter and InAppWebView?
I have a Django server with an endpoint to generate a PDF with some information entered by the user which returns a FileResponse (everything with a buffer, no file is created in the server, it is generated on demand), so the PDF is returned as attachment in the response. The endpoint is called in a HTML form submit button (in a Django template) and it works perfectly in all browsers. On the other hand, I did an app with Flutter (Android and iOS) using the InAppWebView library which opens my webpage. The problem comes when I try to download the PDF using the app. I have not found any way of handling the download file when it is returned as an attachment, for all methods I found I need the URL (which I can not call as I need the form information and the file is generated on demand). Summarizing: I have a Django server and a template with a basic form. On the form submit, it calls a python function that generates and returns a FileResponse with a PDF as an attachment and doesn't save any file in the server. On the other hand I have a Flutter WebView … -
Django authentication problem with mysql database
I am working on a Django project which uses Mysql database to manage user authentication and I also developed a custom user model with the AbstractBaseUser class I can migrate the table in the database and insert a user to the database by using the createsuperuser function and everything is ok but when I try to authenticate the mentioned user, the authenticate function returns None. The strange thing is that when I use default Myadmin db.sqlite3 database service of Django, authenticate function works correctly and returns the user username = 'p' password = 'p' user = authenticate(request , username=username, password=password) if user is not None: return HttpResponse('the user exist') else: return HttpResponse('the user does not exist in database') i also checked the charset of the columns in the database and it was utf8mb4_general_ci -
Pycairo build failed as I tried upload django project to Railway
I have been trying to upload my django project to Railway but whenever i try to upload fro my github repo this is the stack error i get #10 27.27 copying cairo/__init__.py -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 copying cairo/__init__.pyi -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 copying cairo/py.typed -> build/lib.linux-x86_64-cpython-310/cairo #10 27.27 running build_ext #10 27.27 Package cairo was not found in the pkg-config search path. #10 27.27 Perhaps you should add the directory containing `cairo.pc' #10 27.27 to the PKG_CONFIG_PATH environment variable #10 27.27 No package 'cairo' found #10 27.27 Command '['pkg-config', '--print-errors', '--exists', 'cairo >= 1.15.10']' returned non-zero exit status 1. #10 27.27 [end of output] #10 27.27 #10 27.27 note: This error originates from a subprocess, and is likely not a problem with pip. #10 27.27 ERROR: Failed building wheel for pycairo #10 27.27 Failed to build pycairo #10 27.27 ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects #10 27.27 #10 27.27 [notice] A new release of pip available: 22.3.1 -> 23.2.1 #10 27.27 [notice] To update, run: pip install --upgrade pip #10 27.27 [end of output] #10 27.27 #10 27.27 note: This error originates from a subprocess, and is likely not a problem with … -
Login Redirection Issue
When I log into my web application, it doesn’t redirect to the custom redirect page created instead it redirects to the default accounts/profile url in Django. Below are my codes: urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='myapp/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('phase1/', views.phase1_view, name='phase1'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.conf import settings #Phases Details View @login_required def phase1_view(request): settings.LOGIN_REDIRECT_URL = '/myapp/phase1/' return render(request, 'myapp/phase1.html') #Logout View def logout_view(request): logout(request) return redirect('login') #Login View def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('phase1') else: return render(request, 'myapp/login.html', {'error_message': 'Invalid login credentials'}) else: return render(request, 'myapp/login.html') settings.py LOGIN_URL = 'login' login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div> <label>Username</label> <input type="text" id="username" name="username" class="text-input" required> </div> <div> <label>Password</label> <input type="password" id="password" name="password" class="text-input" required> </div> <button type="submit" id="submit" value="Login" class="primary-btn">Sign In</button> </form> I tried to add LOGIN_REDIRECT_URL = '/myapp/phase1/' in settings.py but it not worked. -
djongo(django + mongo) trouble with inspectdb, unable to inspectdb and import model
I am newbie to python and django, Using Django version: 4.1.10 and python version : 3.11.4 I have existing mongodb database so I am trying to import models in djongo (django + mongo) with inspectdb. But I keep getting following err which is mentioned here as well PS C:\Users\del\Downloads\splc\jango\splc1> python manage.py inspectdb Traceback (most recent call last): File "C:\Users\del\Downloads\splc\jango\splc1\manage.py", line 22, in <module> main() File "C:\Users\del\Downloads\splc\jango\splc1\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\del\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 936, in exec_module File "<frozen importlib._bootstrap_external>", line 1074, in get_code File "<frozen importlib._bootstrap_external>", line 1004, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed SyntaxError: source code string cannot contain null bytes What am I missing here, any help is really appriciated. -
How to perform AES on username and password in REACT and DJANGO Python
I have followed to encrypt username and password AES in React based on the below link https://www.code-sample.com/2019/12/react-encryption-decryption-data-text.html using crypto-js const encryptedUsername = CryptoJS.AES.encrypt(usernameWithoutSpaces, SECRET_KEY).toString(); const encryptedPassword = CryptoJS.AES.encrypt(values.password, SECRET_KEY).toString(); I have used the SECRET_KEY as 16byte code which I randomly generated. And used this key for both encrypt and decrypt. I have followed the decryption based on https://devrescue.com/python-aes-cbc-decrypt-example/ from Crypto.Cipher import AES from Crypto.Util.Padding import unpad import base64 def decrypt_view(request): encrypted_username = request.data['username'] # Replace with your encrypted username encrypted_password =request.data['password'] # Replace with your encrypted password print("22222222222222",encrypted_username) # secret_key = b'\xd4\xa5?\xa5\xcd\x95\xees_\t\xa5\x9eI\x9d\x81\x95' # Convert your secret key to bytes secret_key =b'53d7311e6f8f88c0bbc4a08bccd7e254' decrypted_username = decrypt_data(encrypted_username, secret_key) decrypted_password = decrypt_data(encrypted_password, secret_key) print('Decrypted Username:', decrypted_username) print('Decrypted Password:', decrypted_password) def decrypt_data(encrypted_data, key): try: cipher = AES.new(key, AES.MODE_CBC, iv=b'1234567890123456') decrypted_data = unpad(cipher.decrypt(base64.b64decode(encrypted_data)), AES.block_size) # print("&&&&&&&&&&&&&&",decrypted_data) return decrypted_data.decode('utf-8') except Exception as e: print("DDDDDDDDDDDDDDD",e) with this encryption done at frontend and at backend couldn't decrypt as Error which i got as Padding is incorrect. Padding is incorrect. I have also used cryptography module and fernet which is in python to perform decryption. hence it doesnt suite with crypto-js. -
New Django Developer unable to get "Hello World" to display on website instead of the default installed successfully page
I am following along with a Django tutorial to create my first website. Everything was working according to plan until I reached the step that involved the URL Patterns. Specifically it is the include() function that made this project come off the rails. When I reach this point in the tutorial I run the server on my localhost. The default Django installed successfully homepage is displayed instead of the "Hello World" text that is my tutorial index page. I have double checked that my code matches both the tutorial that I am following as well as the official Django tutorial but my results do not change. I have checked several solutions from stackoverflow but have been unable to resolve this problem. /first_project/first_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include('first_app.urls')), path("admin/", admin.site.urls), ] first_project/first_project/settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "first_app", ] /first_project/first_app/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name = "index"), ] first_project/first_app/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello World") One of the suggestions on stack overflow was under first_project/first_project/urls.py to change … -
Background image in css is not found in Django using scss, webpack
I setup SCSS with webpack in Django. The only problem that I encounter in the setup is that background images in generated css file is not found by Django. This is the webpack.config.js const path = require('path'); const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { VueLoaderPlugin } = require("vue-loader"); module.exports = { entry: { main: './src/main.js', }, output: { path: path.resolve(__dirname, '../../backend/static/'), publicPath: '/', filename: '[name].js' }, devServer: { static: { directory: path.join(__dirname, '../../backend/static/'), }, port: 9000, historyApiFallback: true, }, module: { rules: [ { test:/\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', ] }, { test: /\.vue$/i, exclude: /(node_modules)/, use: { loader: "vue-loader", }, }, { test: /\.(js|jsx)$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ["@babel/preset-env"], }, } }, { test: /\.html$/i, loader: "html-loader", }, { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader", "style-loader"], }, { test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource', }, { test: /\.(woff(2)?|eot|ttf|otf|svg|)$/, type: 'asset/inline', }, ] }, plugins: [ new VueLoaderPlugin(), new MiniCssExtractPlugin(), // new HtmlWebpackPlugin({ // template:"./src/index.html" // }), new webpack.DefinePlugin({ __VUE_OPTIONS_API__: true, __VUE_PROD_DEVTOOLS__: false }) ], resolve: { extensions: ['.js', '.jsx', '.scss', '.vue'], alias: { }, modules: [ path.resolve(__dirname, "../src/images/"), "../node_modules/" ], }, }; This is my Django Settings for static … -
payment integration in django
url = "https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token" headers = { "Content-Type": "application/vnd.ni-identity.v1+json", "Authorization": f"Basic {settings.N_GENIUS_API_KEY}" } # Include the realmName in the body body = { "realmName": "Fenzacci" } response = requests.post(url, headers=headers, data=json.dumps(body)) print(response.text) if response.status_code == 200: return response.json().get('access_token') else: return None { "message" : "Not Found", "code" : 404, "errors" : [ { "message" : "Unable to find a tenant details.", "localizedMessage" : "Duplicate tenant name", "errorCode" : "realmNameNotAvailable", "domain" : "identity" } ] } I tried a lot of way but did not find a solution for that, I am so thankful for your response and answer to help me with that. -
Django scripts can't access files from docker volume
I add data folder (containing files with meta data) to the .dockerignore file. Because I don't want to weigh down my containers. don't want my containers to be too heavy. Since the datafolder contains huge files that need to bee read by the application. So I decided to mount a volume in my docker compose like below. And when I go inside the webcontainer I can see the file. And inside the container when I type /sigma/data/imports/dbm.csv I got the data. But when trying to read the file I goot this error : [Errno 2] No such file or directory: '/sigma/data/imports/dbm.csv' Am I missing ou misunderstood something? Docker compose file (an extract) web: container_name: web # image: aba2s/sigma build: context: . dockerfile: ./Dockerfile entrypoint: /sigma/docker-entrypoint.sh restart: unless-stopped env_file: - .env ports: - "8000:8000" depends_on: - db volumes: - ./data:/sigma/data View that read the file In settings.py file, I have this : IMPORTS_PATH = '/sigma/data/imports/' file_path = settings.IMPORTS_PATH + 'dbm.csv' df_import = pd.read_csv( file_path, sep=';', header=0, usecols=cols, index_col=False, on_bad_lines='skip', ) -
JS Appended Array in FomData not accessable in Django backend
In a django template i have this js script: const formData = new FormData(form); formData.append('taglist', JSON.stringify(selectedTagIds)); console.log(JSON.parse(formData.get('taglist'))) console.log(formData.get('title_raw')) form.submit() selectedTagIds is an array. The console logs it correctly. After submitting I can access every standard form field in the django view but not the "taglist". The field doesn't exist in the form. When I try to print it i get "None". What am I doing wrong? -
Django large file upload (.dcm)
After the user starts uploading files of 1-2 gb on a page in Django, I want the user to be able to navigate on other pages while the upload process continues. How can I do it? I can upload the files to the server with the chunk method and merge them in the back. However, this upload process is interrupted when I switch to other pages. I want this to continue without interruption. I tried to create a structure with Django channels and send files with the chunking method of dropzone.js, but I failed. Only string data was sent. I also could not convert the chunk .dcm data to base64. I did not try the celery method. I just searched for its possibility, but I could not find anything clear. autoProcessQueue: false, url: url, maxFiles: 100000000, maxFilesize: 99999, acceptedFiles: '.dcm', timeout: 9999999999, chunking: true, chunkSize: 2000000, clickable: "#dicomDropzone", parallelChunkUploads: false, retryChunks: true, retryChunksLimit: 5, forceChunking: true, init: function() { $('#CBCTUpload').click(function(){ myDropzone2.processQueue(); }) this.on("addedfile", function(file) { totalAddedFiles++; }); this.on("sending", function(file, xhr, formData) { formData.append('slug', parametre); }); } if request.method == 'POST': if 'file' not in request.FILES: return HttpResponse(status=500) file = request.FILES['file'] print("FILE", file.name) current_chunk = int(request.POST['dzchunkindex']) + 1 total_chunks = int(request.POST['dztotalchunkcount']) … -
AttributeError at / 'NoneType' object has no attribute
After running Django python code I receive the error 'AttributeError at / 'NoneType' object has no attribute 'calorie_goal'' What are the reasons and ways to fix this? Models.py class Food(models.Model): name = models.CharField(max_length=200, null=False) quantity = models.PositiveIntegerField(null=False, default=0) calorie = models.FloatField(null=False, default=0) person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Profile(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) calorie_count = models.FloatField(default=0, null=True, blank=True) food_selected = models.ForeignKey(Food, on_delete=models.CASCADE, null=True, blank=True) quantity = models.FloatField(default=0) total_calorie = models.FloatField(default=0, null=True) date = models.DateField(auto_now_add=True) calorie_goal = models.PositiveIntegerField(default=1500, blank=True) all_food_selected_today = models.ManyToManyField(Food, through='PostFood', related_name='inventory') def save(self, *args, **kwargs): # new if self.food_selected != None: self.amount = (self.food_selected.calorie / self.food_selected.quantity) self.calorie_count = self.amount * self.quantity self.total_calorie = self.calorie_count + self.total_calorie calories = Profile.objects.filter(person_of=self.person_of).last() PostFood.objects.create(profile=calories, food=self.food_selected, calorie_amount=self.calorie_count, amount=self.quantity) self.food_selected = None super(Profile, self).save(*args, **kwargs) else: super(Profile, self).save(*args, **kwargs) def __str__(self): return str(self.person_of.username) class PostFood(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) food = models.ForeignKey(Food, on_delete=models.CASCADE) calorie_amount = models.FloatField(default=0, null=True, blank=True) amount = models.FloatField(default=0) views.py @login_required(login_url='login') def HomePageView(request): calories = Profile.objects.filter(person_of=request.user).last() calorie_goal = calories.calorie_goal if date.today() > calories.date: profile = Profile.objects.create(person_of=request.user) profile.save() calories = Profile.objects.filter(person_of=request.user).last() all_food_today = PostFood.objects.filter(profile=calories) calorie_goal_status = calorie_goal - calories.total_calorie over_calorie = 0 if calorie_goal_status < 0: over_calorie = abs(calorie_goal_status) context = { 'total_calorie': calories.total_calorie, 'calorie_goal': calorie_goal, 'calorie_goal_status': calorie_goal_status, … -
How do i setup scheduling task on Django?
I've create a reporting module using Django for a project i have. Essentially what it does it has a list of reports where you can select a start date and end for the reports and run it. Then the report view runs a cursor query and fetches results. All of this works. But now i want to implement a queuing feature. Where you set a start date and end date then set a date time for the report to be automatically run (Which will be stored in a database) and keep the result. The user then can come back anytime to revisit the report without it being rerun What is the best way to achieve this? Thanks I've tried to use a cron job which run daily to check for reports and run them to achieve this but this fails to fulfill time scheduling -
Sum of two Count in one query
Files and folders can be "inside" folders. I need to get the count of files and folders in each folder in queryset. models.py class Folder(models.Model): id = ShortUUIDField(primary_key=True, default=ShortUUIDField.random, editable=False) user = models.ForeignKey(Profile, on_delete=models.PROTECT) parent = models.ForeignKey("self", null=True, blank=True, related_name="children", on_delete=models.PROTECT) description = models.JSONField() class File(models.Model): id = ShortUUIDField(primary_key=True, default=ShortUUIDField.random, editable=False) user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.PROTECT) folder = models.ForeignKey(Folder, null=True, blank=True, on_delete=models.PROTECT) description = models.JSONField(default=default_file_description) show_in_catalog = models.BooleanField(default=False) serializers.py class FolderSerializer(serializers.ModelSerializer): title = serializers.CharField(source='description.title') element_count = serializers.IntegerField() class Meta: model = Folder fields = ['id', 'title', 'element_count'] I tried to count it like that: views.py def retrieve(self, request, *args, **kwargs): folder = self.get_object() return Response( dict( parent=folder.parent_id, folders=CatalogFolderSerializer( Folder.objects.filter( parent=folder, user__user__username=CONTENT_USER ).alias( file_count=Count("file", filter=Q(file__show_in_catalog=True)) ).alias( folder_count=Count("children") ).annotate( element_count=F('material_count') + F('folder_count') # This count i need ), many=True, ).data ) ) But it works incorrect :( I need to count it in views.py not in serializer, using SerializerMethodField and smth like that. -
is there a reason why I run the command to create superuser but it throws an error that 'email is not a valid UUID field'?
I am not new to Django, but I am gaining experience, by working on this project. I use Django 4.2. I created a model for users and ran migrations. I tried to create a superuser, but got an error that 'email is not a valid UUID field'. I understand that 'email' is being passed to the 'UUID' field but I specified that for ID field, so there is a problem with the operation but I can't seem to understand where. This is my models.py file import uuid from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.exceptions import FieldError class UserManager(BaseUserManager): def create_user(self, email, username, password, **kwargs): if not email: raise ValueError('Email must be given!') kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', False) email = self.normalize_email(email) user = self.model(email, username, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): if not email: raise ValueError('Email must be given!') kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', True) email = self.normalize_email(email) superuser = self.model(email, **kwargs) superuser.set_password(password) superuser.save(using=self._db) return superuser class UserAccount(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) email = models.CharField(max_length=250, unique=True, null=False) username = models.CharField(max_length=250, unique=True, null=False) password = models.CharField(max_length=200, null=False) is_active = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_time = models.DateTimeField(auto_now_add=True, null=False) last_login = models.DateTimeField(auto_now=True) … -
connect to PostgreSQL server: FATAL: no pg_hba.conf entry for host "" with external database azure
I have a django docker container running. And I try to connect with the azure postgres db. But when I log in in the admin panel from django, I get this error: OperationalError at /admin/login/ FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "0.0.145.0", user "welzijn", database "welzijn", no encryption And I thought that I had the solution. Because a lot of resources suggest that you have to edit the pg_hba file and the postgresql file. So I did that: pgb_hba: host all all 0.0.0.0/0 scram-sha-256 And postgresql: listen_addresses = '*' I rebooted the machine. But it seems that it didn't solve the issue. I still get this error: OperationalError at /admin/login/ FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "0.0.145.0", user "welzijn", database "welzijn", no encryption Request Method: POST Request URL: http://localhost/admin/login/?next=/admin/ Django Version: 4.2.4 Exception Type: OperationalError Exception Value: FATAL: password authentication failed for user "welzijn" FATAL: no pg_hba.conf entry for host "85.148.145.211", user "welzijn", database "welzijn", no encryption Exception Location: /py/lib/python3.9/site-packages/psycopg2/__init__.py, line 122, in connect Raised during: django.contrib.admin.sites.login Python Executable: /py/bin/python Python Version: 3.9.9 Python Path: ['/usr/src/app', '/py/bin', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/py/lib/python3.9/site-packages'] Server time: Wed, 23 Aug … -
login page is not redirecting to index page even after entering correcting login information
I am trying to buid a django application with login form, my code looks like login.html <form class="container my-5" action="/" method="post"> {% csrf_token %} <div class="row mb-3"> <label for="name" class="col-sm-2 col-form-label">name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" name="username"> </div> </div> <div class="row mb-3"> <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="password" name="password"> </div> </div> <button type="submit" class="btn btn-primary">Sign in</button> </form> Views.py from django.shortcuts import render,redirect from django.contrib.auth import authenticate from django.contrib.auth import logout,login from django.contrib.auth.models import User def index(request): if request.user.is_anonymous: return redirect("/login") return render(request,'index.html') def loginuser(request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') print(username,password) user = authenticate(username=username, password=password) if user is not None: login(request,user) return redirect("/") else: return render(request,'login.html') # No backend authenticated the credentials return render(request,'login.html') def logoutuser(request): logout(request) return redirect('/login') urls.py from django.contrib import admin from django.urls import path,include from home import views urlpatterns = [ `your text` path('', views.index, name="index"), path('login', views.loginuser, name="login"), path('logout', views.logoutuser, name="logout"), ] I tried to print username and password but it is not coming in the terminal Can anyone please help me with that? -
Hotwire Turbo Frame in Django application stops django-bootstrap-datepicker-plus from showing
In my Django App I use a Turbo Frame in a DetailView. The Turbo Frame loads a form into the DetailView. This form has a datefield for which I use a Datepicker (django-bootstrap-datepicker-plus). If I call the form directly the Datepicker works just fine, but when the form is called into the DetailView via Turbo Frame the Datepicker does not show. Any suggestions on how to solve this and whats the underlying issue is? Best I tried to use Stimulus to initialize the Datepicker but so far I have no success and I also couldnt find any Q&A in the Internet. -
How can I know on what date and time the user has clicked on a button and then print it in another Django template?
I have these two buttons found in my Django .html: <div class="d-flex justify-content-center" style="margin: 1em;"> <a id="btn-aceptar" href="{% url 'cambiar_estado_factura' factura.id_factura 2 %}" class="btn btn-success btn-lg mx-2" style="width: 150px;">Aceptar</a> <a id="btn-rechazar" href="{% url 'cambiar_estado_factura' factura.id_factura 3 %}" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Rechazar</a> </div> I have those two buttons in the d_facturaspendientes.html and what I want to know is how can I get the date and time when the user clicks on one of the buttons. That date and time, I want to print it in facturasvalidadas.html, but I don't know how to do it. Can someone give me a hand? Below I attach the table and the commented line where the date and time should go: <table class="table" style="padding: 1em;"> <thead> <tr> <th>ID</th> <th>Proveedor</th> <th>Fecha de emisión</th> <th>Fecha de validación</th> <th>Importe</th> <th>Estado</th> </tr> </thead> <tbody> {% for factura in facturas %} <tr class="factura-row-link" onclick="window.location='{% url 'v_facturasvalidadas_details' factura.id_factura %}'"> <td>{{ factura.id_factura }}</td> <td>{{ factura.id_proveedor.nombre }}</td> <td>{{ factura.fecha_factura_recibida }}</td> <td>HERE SHOULD BE THE DATE AND TIME THAT WE HAVE HEARD WHEN THE USER HAS CLICKED ON THE BUTTONS</td> <td>{{ factura.importe }} €</td> <td>{{ factura.id_estado.value }}</td> </tr> {% endfor %} </tbody> </table> I want to know the day and time when the … -
Request Taking too long in Django
I have been trying to build a chemotherapy drug dose scheduling (mathematical model) as part of my thesis. Firstly I did the logic MATLAB and then implemented it in python. Then I tried using Django. While the app runs fine in localhost, but fails when I host it. Mainly because of the time it takes to calculate the whole process. In my localhost it takes around 40 seconds to 1 min to calculate but I get the result. When I host it in railway it gives up after first iteration. It is based on Fuzzy Logic. Also I didn't follow software development principle when creating this, so the code is a mess. I do not know what should I include for reference. I am adding the github link- FES Tool The error I get from railway is Application failed to respond. Any suggestion is apprecated. I tried to host a django project that takes a lot of time calculating in the backend and I failed. -
Is in django way save some data from database in RAM and after fixed time update it
For example I have some data that is fixed for all user. Now for each request I get the same data from DB. Is there way to optimize it. I tryed make a class which stores my needed data and init time by datetime; and it has method which gets current time, compare it with init time, and if difference more than 12 hours it makes new request to database, update value in class and returns it; else it returns old value. It works but i think that it isn't right way. Are some ideas? -
Implementing configurable feature-based roles and permissions in django rest framework
I have a scenerio where I am creating custom roles and assigning permissions to them for each fetaure. The process is fully customized and generic and it works for CRUD operations(like create user, read user, update user and delete user) perfectly. Now there is a little change in requirements where I have multiple operations for one feature like create order, accept order, split order, refer order. Now I want to create a roles and permissions so that it covers this part of my problem as well. Inititally I had four models i.e. Role, Permission, Feature, RoleFeatureAssociation(fields: role, feature, list(permissions)). I was checking permissions upon each request and if the particular user had that particular permission available for that feature then request was processed. Keeping this procedure in view as well how should I manage new requirements since I have multiple operations for feature instead of just create, read, update and delete. -
How can I make the user click on a button in a Django .html to modify one of the database values?
I have these two buttons found in my Django .html: <div class="d-flex justify-content-center" style="margin: 1em;"> <button type="button" class="btn btn-success btn-lg mx-2" style="width: 150px;">Accept</button> <button type="button" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Reject</button> </div> What I need, is that when the user clicks on the button, that it changes a value, in this case of an invoice of my database. That is to say, now the invoice is in factura.id_estado=1; so, if the user clicks on Accept, factura.id_estado must change to 2 (factura.id_estado=2). The same happens when the user clicks on Reject, factura.id_estado will change to 3 (factura.id_estado=3). I don't know if it is necessary or not, but my database is the Django database which is hosted in my Docker.