Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PycharmProjects\pythonProject\vencannot be loaded because running scripts is disabled on this system. For more informatio see about_Execution_Policies
I want to install Django on pycharm but when I try to install this massage display: File C:\Users\dell\PycharmProjects\pythonProject\venv\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. + CategoryInfo : SecurityError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnauthorizedAccess -
admin profile view after login instead of displaying user profile in django
I am working on a django project.There are two types of users. One is admin and another one is researcher. So I want to display admin profile when admin logs in using the login page instead of researcher profile. I know django has an admin panel. But I want to build custom admin profile. So when admin logs in using the login page created by myself, admin can see the posts created by users. Also he can add category, approve post, delete post. On the other hand, when researchers logs in, users can see their profile page. blog/models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.urls import reverse from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Post(models.Model): aid = models.AutoField(primary_key=True) image = models.ImageField(default='blog-default.png', upload_to='images/') title = models.CharField(max_length=200) content = RichTextField() created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization') approved = models.BooleanField('Approved', default=False) like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True) def __str__(self): return self.title users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization', … -
Periodically create/update a model based on another model's annotation
I have model Foo that changes periodically (every week for simplicity). The corresponding API endpoint for this model only needs the annotation foo_annotate. I want to be able to backtrack even if the period changes. My current setup works fine but I realized that if new entries are created in the database, I may run out of storage. So instead of doing that, I create a new model based on the computed value from Foo. Here's what I have so far: class FooManager(models.Manager): ... def get_queryset(self): return super(FooManager, self).get_queryset() \ .annotate(foo_annotate=Coalesce(models.Count("bar"), 0)) # Annotation is much more complex class Foo(models.Model): # Periodic model ... period = models.CharField(...) # Name of current period, unsure if DateField is better user = models.ForeignKey(User, ...) objects = FooManager() class Bar(models.Model): # Fields may change ... foo = models.ForeignKey(Foo, ...) class Baz(models.Model): # Model based on annotation period = ... foo_annotate = ??? -
cannot import name 'urlquote' from 'django.utils.http'
I am trying to login to the admin portal, however I am getting the below error. Please help I have been searching for solution but nothing Exception Type: ImportError at /admin/login/ Exception Value: cannot import name 'urlquote' from 'django.utils.http' (C:_project\my-events\env\lib\site-packages\django\utils\http.py) -
Postgresql cannot connect to server
The project is a django web app, packed on docker containers. For some reason, I cannot run the server and launch it. when I run "manage.py runserver", this error occurs: File "C:\Users\andre\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "158.160.17.21", port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? What do you think can be done with it? Thank you. -
django.db.backends.postgresql
I am trying to switch my Django database from SQLite3 to PostgreSQl, so I follow many tutorials to install and setup Postgres with Django project. I do the following: pip install psycopg2, pip install psycopg2-binary and I modify the settings.py like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': BASE_DIR / 'db.postgresql', 'USER': 'muusername', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432' } } Finally I make my database, by running the command python manage.py makemigrations. However, I got this error: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' Please note that I am also seccesufully install the pgAdmin in my OS which is Windows 10. I know that the problem is postgres is not configured in my django project, but I don't know how to add it, also I check my djnago version which is tha latest one, also all needed packages are installed in venv. -
Deploy django/react on the same server, different port?
I have 2 projects for backend and frontend which are written in django and react respectively. I bought one linux server, now I'm wondering is it possible to deploy these two projects in one server? (in different ports), if so, how? To be honest, I can't find any good articles about this. I have an experience deploying only django projects using linux/apache... -
Polygon selection based on marker position in leaflet
On the map, I have an added layer with polygons and one marker on another layer. When I click anywhere, the marker moves to that location and the polygon is selected. The marker has the ability to drag across the map, but just when I drag it, the polygon selection does not appear. How to do this? var osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }); var map = new L.Map('map', { 'center': [51, 17], 'zoom': 6, 'layers': [osm], }); var selected; var marker marker = L.marker([51, 17], { draggable: true }).addTo(map); var geoJsonLayer2 geoJsonLayer2 = L.geoJson( polygons ,{ style: { fillColor: "#1ED100", color: "orange", fillOpacity: 0.0, opacity: 0.0, }, }) .on('click', function (e) { // Check for selected if (selected) { // Reset selected to default style e.target.resetStyle(selected) } // Assign new selected selected = e.layer // Bring selected to front selected.bringToFront() // Style selected selected.setStyle({ 'color': 'red', 'opacity': 1, }) }) .addTo(map); marker.on('dragend', function (e, feature) { updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng); }); map.on('click', function (e) { marker.setLatLng(e.latlng); updateLatLng(marker.getLatLng().lat, marker.getLatLng().lng); }); function updateLatLng(lat, lng, reverse) { if (reverse) { marker.setLatLng([lat, lng]); map.panTo([lat, lng]); } else { document.getElementById('lat').value = marker.getLatLng().lat.toFixed(10); document.getElementById('long').value = marker.getLatLng().lng.toFixed(10); map.panTo([lat, lng]); document.getElementById("lat").value = lat.toFixed(10); document.getElementById("long").value = … -
ModuleNotFoundError: No module named 'application' when deploying Django app to AWS EB
I'm trying to deploy a django project to Elastic Beanstalk. I have the following code in .ebeextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pos.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: pos.settings I see this error all the time in the logs ModuleNotFoundError: No module named 'application' I've tried to write the config file this way, but still the same error option_settings: aws:elasticbeanstalk:container:python: WSGIPath: pos/wsgi.py Here is the platform Python 3.8 running on 64bit Amazon Linux 2/3.4.2 -
Need help about redirecting views in Django (New)
I have posted a question with the same title as this one, everyone can see it from this link Unfortunately, because that was my first time making a question, some format mistakes were made and that question is closed for the moment. I have edited it and resubmitted for opening again but I don't know how long will that take so I might as well make a new one. I'm working on a web application for reading novels and currently I'm stuck at a certain part in directing views using urls. I use Django as the back end with PostgreSQL as the database and HTML with bootsrap as front end. I will post my code below: This is my urls.py (from the project folder): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This is my urls.py (from the app folder): from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.home), path('book/<slug:book_slug>/<slug:chapter_slug>/', views.detail, name='detail'), path('genre/<slug:category_slug>', views.category_detail, name='category_detail'), path('book/<slug:book_slug>', views.book_detail, name='book_detail'), path('register/', views.register, name="register"), path('login/',auth_views.LoginView.as_view(template_name="app/login.html"), … -
Submit Button checks if file doesn't select in Django
Currently working on a Django project where I am stuck in a situation and the scenario is something like that I have two forms in my abc.html page, one is used for input file and second is used to run python script internally. But the issue is even if I don't input the file the submit button "run python script" start's working without submitting a file. Here I want to create a check that submit button "run python script" will run only at one condition when file will submitted otherwise button will disable. It will active only at one condition when user will input the file. I am sharing the details: abc.html: <!--form to input file --> <form method="post" enctype="multipart/form-data" name="myform"> {% csrf_token %} <input type="file" id="file" name="doc" class="inputfile" onchange="document.myform.submit()"> </form> <-- end of input file--> <!-- form to run python script --> <form action = "/results/" method="post" id="subform"> {% csrf_token %} <input type="submit" id="btnSubmit" name="doc" value="run python script" class="btn btn-warning btn-sm" /> </form> <-- end of form running python script --> views.py: def compliance_check(request): //function to upload file global uploaded_file if request.method == 'POST': uploaded_file = request.FILES['doc'] print(uploaded_file.name) print(uploaded_file.size) fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) messages.info(request, 'your file ' + … -
submitting django crispy form with file field and some other text fields using fetch and then
I am trying to submit my crispy form using fetch and then methods to django backend. All my fields are submitting to the server. but files are shown as empty fields in the server. below, is my front end from {{ photo.media }} <form action="" method="post" class="form my-4 px-2" enctype="multipart/form-data" id="photo_form" onsubmit=""> {% csrf_token %} {{photo|crispy}} <input type="submit" value="Add" class="btn btn-primary btn-lg"> </form> Here is the ajax request I made <script> const photoForm = document.querySelector('#photo_form'); console.log(photoForm.values); photoForm.addEventListener('submit', (event) => { event.preventDefault(); const photoFormData = new FormData(photoForm); photoFormData.forEach((value, key) => { console.log(key + ': ' + value); }); fetch("{% url 'add_photo' %}", { method: 'POST', body: photoFormData, contentType: false, processData: false, }) .then((response) => response.json()) .then((data) => { console.log(data); if (data.result == 'success') { $('.modal-body').html('Form submission was successful!'); $('#modal-dialog').modal('show'); photoForm.reset(); } else { $('.modal-body').html('There was an error with the form submission.'); $('#modal-dialog').modal('show'); } }); }); </script> Below, is the model I Made class Photos(models.Model): photo_title = models.CharField(max_length=50, blank=False) photo_description = models.CharField(max_length=50, blank=False) photo_date = models.DateField(blank=False) photo_location = models.CharField(max_length=50, blank=False) photo_file = models.ImageField(upload_to='photos', blank=False) def __str__(self): return self.photo_title Below, is the view function """ ajax add photo event to home wall """ def add_photo(request): if request.method == 'POST': response_data = {} photoForm … -
obj.id printing loop of the ids, need to get only the recent/top one
It's a function inside the class ServiceReportCallbackAdmin(BaseAdmin):, I'm calling save_meta from another function, def save_meta(self,obj, form): print(obj.id) when i'm calling this function, i'm getting: 51 45 34 24 17 10 5 3 1 But i just want to get 51 only for further use, how can i do that? -
How to save or upload an image from LOCAL directory to ImageField of database object in DJANGO
i was trying to create some products in ecommerce project in django and i had the data file ready and just wanted to loop throw the data and save to the database with Product.objects.create(image='', ...) but i couldnt upload the images from local directory to database!!! i tried these ways: 1- first try: with open('IMAGE_PATH', 'rb') as f: image = f.read() Product.objects.create(image=image) didnt work!!! 2- second try: image = open('IMAGE_PATH', 'rb') Product.objects.create(image=image) 3- third try: module_dir = dir_path = os.path.dirname(os.path.realpath(__file__)) for p in products: file_path = os.path.join(module_dir, p['image']) Product.objects.create() product.image.save( file_path, File(open(file_path, 'rb')) ) product.save() -
How can I fix this error? json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
https://youtu.be/0iB5IPoTDts?t=4690 I am currently trying to like a product with my microservice per request. Here is the code from his video: https://github.com/scalablescripts/python-microservices This is my code: from flask import Flask, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from sqlalchemy import UniqueConstraint from dataclasses import dataclass import requests \#from markupsafe import escape \#from jinja2 import escape app = Flask(__name__) app.config\["SQLALCHEMY_DATABASE_URI"\] = 'mysql://root:root@db/main' CORS(app) db = SQLAlchemy(app) @dataclass class Product(db.Model): id: int title: str image: str id = db.Column(db.Integer, primary_key=True, autoincrement=False) title = db.Column(db.String(200)) image = db.Column(db.String(200)) @dataclass class ProductUser(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) product_id = db.Column(db.Integer) UniqueConstraint('user_id', 'product_id', name='user_product_unique') @app.route('/api/products') def index(): return jsonify(Product.query.all()) @app.route('/api/products/\<int:id\>/like', methods=\['POST'\]) def like(id): req = requests.get('http://host.docker.internal:8000/api/user') return jsonify(req.json()) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') The API user is called which creates a random user, see code: from django.contrib import admin from django.urls import path from .views import ProductViewSet, UserAPIView urlpatterns = [ path('products', ProductViewSet.as_view({ 'get': 'list', 'post': 'create' })), path('products/<str:pk>', ProductViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'delete': 'destroy' })), path('user', UserAPIView.as_view()) ] and this is the class that will be executed: class UserAPIView(APIView): def get(self, _): users = User.objects.all() user = random.choice(users) return Response({ 'id': user.id }) I get the following error … -
Javascript: how to get calculate multiple input values in loop using javascript?
I am trying to calculate the the value of some input field in my django template using javascipt (onkeyup=(), the form is in a loop e.g {% for p in prediction %} {% endfor %}. I have this simple line to grab the input values (NOTE: They are in a loop) let stake_amount_input = document.querySelector("#amount").value let shares_amount_input = document.querySelector("#shares").value Based on the fact that i have all these function in a django loop, am i not supposed to get all the input fields values when i calculate the other objects in the loop. Based on the fact that i have all these function in a django loop, am i not supposed to get all the odds when i console.log(odds) {% for p in prediction.prediction_data.all %} <form action="#" method="POST"> <input type="number" value="" name="amount" id="amount" class="shares" onkeyup="CalculateNewBalance()"> <input type="number" value="" name="shares" id="shares" class="shares" onkeyup="CalculateNewBalance()"> <script> function CalculateNewBalance(){ let stake_amount_input = document.querySelector(".amount").value let shares_amount_input = document.querySelector(".shares").value let potential_win = document.querySelector(".potential-win") let potential_win_value = parseFloat(stake_amount_input) * parseInt(shares_amount_input) potential_win.innerHTML = "$" + potential_win_value // if the potential_win innerHTML shows Nan, then i want to change the innerHTML to $0.00, but this is not working too if (potential_win === isNan) { potential_win.innerHTML = "$0.00" } </script> … -
How to use dumpdata and loaddata for Django Groups with some permissions?
While writing testcases, I required fixtures or we can say json data to pre-populate database. I have a project which is using Django Groups and Permissions models. Now, when I use command for dump data python manage.py dumpdata auth.Groups > fixtures/groups.json It will dump all data in groups.json file as show below. Note: groups are added on the fly means when a specific registration form is triggered, it will create specific group and also add related related permissions in that group which i have defiend in code. But if group is already created, it will not try to create it again just simply assign that group to user. Here, permissions are listed accourding to their id's. Note: Some permissions are defaults and others are custom permissions defiend in models. Now, I recreate database. Then, migrated with python manage.py migrate and created some users so that groups are created dynamically and permissions are assigned to that group which I mentioned above. Then, again used dump data command, this time ids are different. Also when I verified permissions in groups in django admin-panel, its showing different permission assigned to group to that of I coded. From this, I assume that whenever I … -
Django How can I upload a csv file?
I do that : With that whenf i click on Envoyée , i do'nt have modal for choice my csv file . Can you help me please ? forms.py class CSVUploadForm(forms.Form): csv_file = forms.FileField() views.py def upload_csv(request): form = forms.CSVUploadForm(instance=request.user) if request.method == 'POST': form = CSVUploadForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): # do something with the file form.save() csv_file = request.FILES['csv_file'] return render(request, 'password_change_done.html',) else: form = CSVUploadForm() return render(request, 'Paramétres.html', {'form': form}) Paramétres.html <form method="post" enctype="multipart/form-data"> {{ form.as_p }} `your text` {% csrf_token %} {# \<input type="submit" value="Upload"\>#} \<button class="btn btn-primary btnSendPP" type="submit" \>Envoyé\</button\> \</form\> -
My html isn't connecting to my css only when running trought server
I am making a django app and when I try to run the different pages the html is loading but not the css, when i open the files normaly(not from server) it all works fine, but when i run them trought the server it searches for the css at the url page. Here is an example: at url:http://127.0.0.1:8000/profile/create/ the html is all working but css isn't and I get this in the terminal: [21/Dec/2022 10:11:54] "GET /profile/create/ HTTP/1.1" 200 1374 Not Found: /profile/create/style.css [21/Dec/2022 10:11:54] "GET /profile/create/style.css HTTP/1.1" 404 2993 The html and css are in the same directory and here is my connection from my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="style.css"> <title>MyPlantApp</title> </head> -
Django rest api csv to json
I would like to create a django rest api that receives a csv file and then response the file in a json format. How do I achieve this without using models and anything related with databases? I don't want to use a database because it's assumed that the csv files will have different structure every time This is my first django project and I've seen lots of tutorials, even I did the first tutorial from django website but I can't understand how to do this task without the database. Thanks! -
How to set the Current user_id in the Django-Rest-Framework?
Alsomt all the answers are talking about how to set current user in the class with paraemter generics.ListCreateAPIView. But I'm just using APIView and I'm using function "post" to post the data. Can someone tell me how can I set a current user_id in this file. And do I need to add something in the serializers.py too? views.py class CreateVideo(APIView): permissions_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = VideoSerializer(data=request.data) user=self.request.user.id if serializer.is_valid(): serializer.save(user) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I created a variable "user" with self.request.user.id in it and then I passed it to the serializer.save(user). And when I created new video on the frontend side. It me gave a Bad Reuest Error. -
How can i load all fixtures inside particular directory While writing TestCases in Djnago using Pytest
I have multiple fixtures(json files) inside admin folder and i need to load all the fixtures of that directory without mannuallly writing all fixtures location. I have tried below code but but it's not working @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/*.json' ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) I need to give each and every fixture's location like shown below: @pytest.fixture(scope='session') def load_admin_data(django_db_setup, django_db_blocker): fixtures = [ 'fixtures_for_tests/admin/data1.json', 'fixtures_for_tests/admin/data2.json', ] with django_db_blocker.unblock(): call_command('loaddata', *fixtures) Note: One approch which i figure out is get all fixture location using some script is there any other way to give fixture location using some regex pattern while loaddata? I'm expecting that i'm able to give dyanamic path or regex pattern of fixture location -
Uncaught TypeError: $.ajax is not a function in Django
I have a function that works in the following manner: function ajax_display_schema_helper(schema_name){ $.ajax({ ... ... ... }); }; ajax_display_schema_helper('example schema'); But when I call the function above as following: $('.dropdown-item').click(function() { ajax_display_schema_helper(schema_name); }); I get the "$.ajax is not a function" error. What is the reason that it doesn't work when the function is called in the second way? -
Django allauth google login with Google identity
The google sign in javascript library is being deprecated: Warning: The Google Sign-In JavaScript platform library for Web is deprecated, and unavailable for download after March 31, 2023. The solutions in this guide are based on this library and therefore also deprecated. Use instead the new Google Identity Services for Web solution to quickly and easily sign users into your app using their Google accounts. By default, new client IDs are now blocked from using the older platform library; existing client IDs are unaffected. New client IDs created before July 29th, 2022 may set the plugin_name to enable use of the legacy Google platform library. The existing oauth implementation from django-allauth requires the users to either use server-based redirect with the Oauth2.0 code or send in both the access_token and id_token for processing the login, The implementation by google now only gives us the id_token and all the required data like name, profile picture etc. is included in the JWT token. Thus, the login fails as I am unable to send in both the access token and the id token. There are two approaches that come to my mind for solving this: I either override the social login view and … -
Why getting g++ not recognized as a command while running subprocess in python?
I have an online ide which takes code and language from the user and upon submitting the server has to execute the file. I have g++ installed on my system still upon execution I get the following error in subprocess module: 'g++' is not recognized as an internal or external command, operable program or batch file. '.' is not recognized as an internal or external command, operable program or batch file. The function for file execution is : def execute_file(file_name,language): if(language=="cpp"): #g++ xyz.cpp subprocess.call(["g++","code/" + file_name],shell=True) #this only compiles the code subprocess.call(["./a.out"],shell=True) #this executes the compiled file. my code file is there in the /code directory. The directory structure is :