Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error: Pandas requires version '1.4.16' or newer of 'sqlalchemy' (version '0.9.8' currently installed)
I am using sqlalchemy to access my sql database and making changes in sql database, the code for the requirement is: output_db_engine=create_engine( "mssql+pymssql://{user}:{pw}@{ip}/{db}".format( user=PORTAL_DB_USERNAME, pw=urllib.parse.quote_plus(PORTAL_DB_PASSWORD), db=smartsearch_db_name, ip=smartsearch_db_ip ) ) final_df.insert(loc=0, column='Id', value=np.arange(1, len(final_df) + 1)) final_df.to_sql('Smart_Search_Table', con=output_db_engine, chunksize=900, method='multi', if_exists='replace', index=False) # Making Id column as Primary Key in table with output_db_engine.connect() as con: con.execute('ALTER TABLE ' + 'Smart_Search_Table' + ' ALTER COLUMN Id INT NOT NULL') con.execute('ALTER TABLE ' + 'Smart_Search_Table' + ' ADD PRIMARY KEY (Id);') print( f"SUCCESS : Table with name Smart_Search_Table is created and loaded with new data " ) return final_df if __name__ == "__main__": i = making_table() i.making_final_df() But i am getting an error: ImportError: Unable to find a usable engine; tried using: 'sqlalchemy'. A suitable version of sqlalchemy is required for sql I/O support. Trying to import the above resulted in these errors: Pandas requires version '1.4.16' or newer of 'sqlalchemy' (version '0.9.8' currently installed). Can anyone help me to resolve this error? I am also getting a warning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.24.1 warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}". I am new to python, can anyone help me how to resolve … -
NoReverseMatch at /en/dashboard/server-request/
Reverse for 'edit_server_request' with arguments '(2,)' not found. 1 pattern(s) tried: ['en/dashboard/edit-server-request/int:pk'] the edit and delete button on the template below raises the error: <td> <a class="edit-button" href="{% url 'dashboard:edit_server_request' user.server_user.pk %}">{% trans 'Edit' %}</a> <a class="delete-button" href="{% url 'dashboard:delete_server_request' user.server_user.pk %}">{% trans 'Delete' %}</a> </td> views.py def edit_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) if request.method == "POST": form = ServerRequestForm(request.POST, instance=server_request) if form.is_valid(): form.save() return redirect('server_request_list') else: form = ServerRequestForm(instance=server_request) context = {'form': form} return render(request, 'dashboard/school/edit_server_request.html', context) def delete_server_request(request, pk): server_request = get_object_or_404(ServerRequest, pk=pk) server_request.delete() return redirect('server_request_list') urls.py url(r'edit-server-request/<int:pk>', school_views.edit_server_request, name='edit_server_request'), url(r'delete-server-request/<int:pk>', school_views.delete_server_request, name='delete_server_request') edit and delete url raises the error -
Getting user name in the access token response in Django
I have integrated google social auth in my django + react.js project. I am using the access token that I am getting from google to call this url 'http://localhost:8000/auth/convert-token'. This is giving me a json response which contains the access-token and the refresh-token. However I want to add the user name in that json response as well. I tried using request.user.username. But it is not giving me anything. I guess it is because by the time the call is made the for aforementioned URL, the request doesn't have any value for the currently logged in user. Can you suggest me any way to get the username. Following is my code. @api_view(["POST"]) def googleSignIn (request): print(request.headers.get("token")) resposnePayload = {} # token obtained from google token = request.headers.get("token") clientId = "<client-id for django app>" clientSecret = "<client-secret for django app>" url = 'http://localhost:8000/auth/convert-token' header = { "Content-Type": "application/x-www-form-urlencoded" } payload = { "grant_type": 'convert_token', "client_id" : clientId, "client_secret" :clientSecret, "backend":"google-oauth2", "token":token } result = requests.post(url,data=payload,headers = header) resopnsePayload=result.json() print("currently logged in user is ",request.user.username) return Response(resopnsePayload,status=result.status_code) -
Django admin: Geometry Widget not showing up for view permission on the model
The GEO MAP for the geometry field doesn't show up for the user having only View Permission on the model. Instead the geometry field value gets displayed in a text format, something like this: SRID=4326;POLYGON ((82.071... Is there any way workaround for this problem? -
Adding Role option in django.contrib.auth.models.User
As of now, I am storing username, password in User object which I import from "django.contrib.auth.models". Now, I am also sending 'role' attribute in POST request and it should add 'role' in User as well. I have seen multiple posts, but not able to understand role part. Some posts says, use some Groups, not clear how to use them. I just have to store role attribute in User of django.contrib.auth.models. POST body will be something like this: {"username":"name22","password":"$pwd1234","password2":"$pwd1234", "role": "admin" } Using below code: serializers.py: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_username(self, value): if User.objects.filter(username__iexact=value).exists(): raise serializers.ValidationError("A user with this username already exists.") return value def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` Want to understand , if "role" = "Customer" also comes in POST request, then how to store this role in above User object. I checked multiple posts, but all seems to handle complex cases. In my case, … -
Django could not build wheels for backports.zoneinfo error
ModuleNotFoundError: No module named 'backports.zoneinfo not install pip3 install backports.zoneinfo==0.2.1 error Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] /tmp/pip-build-env-mlqbnavt/overlay/lib/python3.10/site-packages/setuptools/config/setupcfg.py:520: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-310 creating build/lib.linux-x86_64-cpython-310/backports copying src/backports/init.py -> build/lib.linux-x86_64-cpython-310/backports creating build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/init.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '.png' under directory 'docs' warning: no files found matching '.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/init.pyi -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-310/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-310 creating build/temp.linux-x86_64-cpython-310/lib x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/var/www/vhosts/arbitrage/myvenv/include -I/usr/include/python3.10 -c lib/zoneinfo_module.c -o … -
Django: how to filter with exact same count?
Let's say I have a group of id's : [1, 2, 87] I want to get all the User who have those exact addresses, not the User that might have those addresses and more. So if I do a request like this, I might have User that have those addresses and more: User.objects.filter(addresses__in=[1, 2, 87]) With this code, I might get a User who has those addresses, for example [1, 2, 87, 724, 725]. This is not what I want! Is there a way to get only those who have exactly the those 3 addresses, no more? -
How to implement PDF file upload feature using django rest framework and MySQL?
I'm making Website using Next.Js(v13.1.6) as frontend and Django REST Framework(v3.14.0, django:v4.1.6) as backend, AWS RDS MySQL as Database. I want to make user upload and download pdf in client. How to implement this feature in backend? I heard that when saving static file(like image file) in django, usally use S3 as storage to be efficient. Is it the same when saving a pdf file? I want to know is it okay saving pdf file just in mysql without s3. I want to make user upload and download pdf in client. How to implement this feature in backend? I want to know is it okay saving pdf file just in mysql without s3 in django. -
Facing error in django-microsoft-authentication
I am facing key error, access_key no found This is the error which I am facing Refering this documentation https://pypi.org/project/django-microsoft-authentication/ These are my configuration: Settings.py DEBUG = True INSTALLED_APPS = [ ... 'microsoft_authentication', ] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' MICROSOFT = { "app_id": "...", "app_secret": "...", "redirect": "http://localhost:8000/microsoft_authentication/callback/", "scopes": ["user.read"], "authority": "https://login.microsoftonline.com/common", "valid_email_domains": ["<list_of_valid_domains>"], "logout_uri": "http://localhost:8000/logout" } MICROSOFT_CREATE_NEW_DJANGO_USER = False urls.py urlpatterns = [ path('admin/', admin.site.urls), ... path('microsoft_authentication/', include('microsoft_authentication.urls')), ] In Azure portal, I created an app, and client secret. and gave correct credentials in settings.py I have sepcified redirect uri's as: http://localhost:8000/microsoft_authentication/callback/ In my login page, I gave correct Url <a href="{% url 'microsoft_authentication:microsoft_authentication_login' %}">Login With Microsoft</a> It is asking to enter email, password. After entering, I am facing the error. Someone help with it. -
How to show a rating of Related Products
Learning Django with tutorial. On the page "Product" is displayed rating for this product. There are also Related Products and I can't understand the logic to show the rating of each Related Products. product-detail.html {% extends 'base.html' %} {% load static %} {% block content %} <main class="container my-4"> <h3 class="my-4 border-bottom pb-1">{{data.title}}</h3> <div class="row"> <!-- Images --> <div class="col-md-4"> <img id="zoom_01" data-zoom-image="/media/{{data.image}}" src="/media/{{data.image}}" class="card-img-top" alt="{{data.title}}"> </div> <div class="col-md-8"> <p>{{data.detail}}</p> <hr/> <table class="table table-bordered"> <tr> <h6>Цена</h6> <h6>$ <span class="product-price-{{data.id}}">{{data.price}}</span></h6> </tr> </table> <hr/> <div class="input-group my-3" style="width:30%;"> <input type="number" value="1" class="form-control product-qty-{{data.id}}" id="productQty" /> <div class="input-group-append"> <input type="hidden" class="product-id-{{data.id}}" value="{{data.id}}" /> <input type="hidden" class="product-title-{{data.id}}" value="{{data.title}}" /> <input type="hidden" class="product-image-{{data.id}}" value="{{data.image}}" /> <button class="btn btn-primary btn-sm add-to-cart" data-index="{{data.id}}" type="button" id="addToCartBtn"><i class="fa fa-shopping-cart"></i> Add to cart</button> </div> </div> </div> </div> <hr /> ..... <!-- Reviews --> <div class="col-md-6"> <h3 class="my-3">Reviews - <span class="avg-rating">{{avg_reviews.avg_rating}}</span>/5 <i class="fa fa-star text-warning"></i> {% if user.is_authenticated %} {% if canAdd %} <button type="button" data-toggle="modal" data-target="#productReview" class="btn btn-warning bt-sm float-right reviewBtn">Add review</button> {% endif %} {% endif %} </h3> <div class="card"> <div class="card-body review-list" style="max-height: 400px; overflow; auto;"> <!-- Detail --> {% if reviews %} {% for review in reviews %} <blockquote class="blockquote text-right"> <small>{{review.review_text}}</small> <footer class="blockquote-footer">{{review.user}} <cite title="Source Title"> … -
create custom audit table using django-auditlog library
So in our project we are already using auditlog library for auditing in silo project. A new requirement has came up where i have store audit of some tables in a different table than created by this library. I am not able to do so. I have tried multiple things but still stuck on this I tried making a Logentry which inherits Logentry and tried to register it but its not working. code: class ModelLogEntry(LogEntry): # objects = LogEntryManager() mymodel = models.ForeignKey(Followers, on_delete=models.CASCADE) class Meta(object): db_table = 'myapp_mymodellogentry' # f = Followers() auditlog.register(Followers,ModelLogEntry)``` In this code, I want to audit every update, create or delete functionality for followers table and that audit will be stored in myapp_mymodellogentry table -
Is there a nice one-liner to provide a default value if the variable is NoneType?
There is a possibility that I am searching under wrong keywords, but I can't find the answer to the question: Is there a nice one-liner to provide a default value if the variable is NoneType? def validate_quantity(self, value): instance = self.instance diff = value - instance.quantity results in error: unsupported operand type(s) for -: 'decimal.Decimal' and 'NoneType' I know get() attribute which works like that: smth.get('quantity', 200) but instance Object does not have this attribute. -
Why does PyCharm highlight the urlpatterns in Django?
pycharm_screenshot The Context Actions menu suggests nothing. I expect it to not highlight the routes "admin/" and "challenges/" -
Django hosted postgresql database requirements
I'm running a postgresql database on digital ocean for my multi-tenant django application and it's running incredibly slow. It's taking a good 5-8 seconds to changed views. I using quite a few requests before page, so I'm unsure on how powerful the postgresql server needs to be but currently the specs are. 2 GB RAM / 1vCPU / 25 GB Disk How much more RAM/CPU power do I need to see a decent increase in request speed? Note: I'm using async on all views that aren't Class Based (3-4) -
How do I Secure a `credential.json` file in a Production Server
I am connecting to a google service via a (downloaded)credential.json file, following is my snippet: from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'credential.json')) this is working perfectly, however I want to to use the file in my production server, but I know it is not a good practice to upload API file/key to a production server, I am using python-decouple package to store my other keys, and using it as environment variables in the production server. My question is how do I use a 'file' and its key contents securely in a production server? I tried using python-decouple package, it works perfectly on individual keys, but on files I cannot managed to make it work. -
How to prevent `bootstrap_field` from wrapping the field in a `div`?
Here's a form field: my_field = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'My field', 'class': 'form-control'} ), label='', ) here's how the template looks like: <form> {% csrf_token %} {% bootstrap_field form.my_field %} </form> which wraps the field in a mb-3 div. Here's how it's rendered: <form> <input type="hidden" name="csrfmiddlewaretoken" value="8SKOXF9pDtfhlTuuMf9NSGxISpakORHHh3sQdNH2Um9havzCUh8gZOKp248eKjRE"> <div class="mb-3"> <input type="text" name="my_field" placeholder="My field" class="form-control" maxlength="255" title="" required="" id="id_question"> </div> </form> This is how I want it to be: <form> <input type="hidden" name="csrfmiddlewaretoken" value="8SKOXF9pDtfhlTuuMf9NSGxISpakORHHh3sQdNH2Um9havzCUh8gZOKp248eKjRE"> <input type="text" name="my_field" placeholder="My field" class="form-control" maxlength="255" title="" required="" id="id_question"> </form> -
Django and SQL Q
What is the meaning of the following? This is a Django project sql = 'select * from tb_music where songlx = "{0}" ORDER BY RAND( ) limit 0,1'.format(key) What is the meaning of the following? This is a Django project -
Django date filter failing to execute right after midnight or 12am
I have a django project that allows a user to only create 8 objects per day and its filtering using __day but it seems between oo:oo and 01:59 the programs is allowing users to create unlimited objects. today = datetime.today() day = today.day task_limit_enabler = False task_limit = MyRate.objects.filter(user = request.user, date_created__day = day).count() if task_limit < 8: task_limit_enabler = True -
Django form is not saving into the db
I'm developing a django project where I need to collect data for a student pass application the view.py is as follows def BusPassForm(request): school = admindb.SchoolDetail.objects.all() place = Place.objects.all() subtime = SubTime.objects.all() if request.method == 'POST': name = request.POST.get("name") age = request.POST.get("age") dob = request.POST.get("dob") mobile = request.POST.get("mobile") adhaar_no = request.POST.get("adhaar_no") address = request.POST.get("address") school_name = request.POST.get("school_name") start_place = request.POST.get("start_place") end_place = request.POST.get("end_place") time_periode = request.POST.get("time_periode") profileimage = request.POST.get("profileimage") idimage = request.POST.get("idimage") adhaar_image = request.POST.get("adhaar_image") try: buspassform = PassForm(name=name, age=age, dob=dob, mobile=mobile, adhaar_no=adhaar_no, address=address, school_name=school_name, start_place=start_place, end_place=end_place, time_periode=time_periode, profileimage=profileimage, idimage=idimage, adhaar_image=adhaar_image) buspassform.save() messages.success(request, 'application submitted') return redirect('dash') except: messages.error(request, 'Error in submitting your appliction') return redirect('buspassform') print(form.error) return render(request, 'buspassform.html', {'school':school, 'place':place, 'subtime':subtime}) the models.py for the same as follows class PassForm(models.Model): name= models.CharField(max_length=100, default=None) time_periode = models.ForeignKey(SubTime, on_delete = models.CASCADE, default=True) school_name = models.ForeignKey(admindb.SchoolDetail, on_delete = models.CASCADE, default=True) start_place = models.ForeignKey(Place, null=True, blank=True, on_delete =models.CASCADE, related_name="pass_start") end_place = models.ForeignKey(Place, null=True, blank = True, on_delete = models.CASCADE, related_name = 'pass_end') age = models.IntegerField(blank=True, null=True, default=True) dob = models.DateField(default=datetime.date.today) address = models.TextField(max_length=100, blank=True, null=True) adhaar_no = models.CharField(max_length=200, null=True, blank=True) mobile = models.CharField(max_length=200, blank=True, default=None) idimage = models.ImageField(upload_to='static/ksrtcimage/idimage', null=True, default=None) adhaar_image = models.ImageField(upload_to='static/ksrtcimage/adhaar', null=True, default=None) profileimage = models.ImageField(upload_to='static/ksrtcimage/profileimage', null=True, default=None) the urls.py … -
Is it possible to add a Push/Refresh view to Browser#1 when order is placed on Browser#2 in Django?
I'm creating a kitchen app/order app. And I'm trying to make the kitchen browser page refresh when an order is placed from another browser. Is this even possible? I know Django can use Signals to track events, but can those events trigger a refresh on another browser? -
DJANGO: Create User in 'core' app when Contact created in 'other' app using Signals
I want to create a User in a separate app called 'core' when a Contact is created in an app called 'bookings'. I'm having trouble configuring the signal to handle this. Currently, using the signal I'm checking if the User exists and either assigning the existing User to the Contact instance OR creating a new User and assigning. I've tried setting the user attribute to allow null, and blank, etc. I keep getting the below warning: IntegrityError at /bookings/contacts/ null value in column "user_id" of relation "bookings_contact" violates not-null constraint DETAIL: Failing row contains (18, tesing@testing.com, 5555555, null). bookings.models.py from django.db import models from django.conf import settings from django.contrib import admin import datetime # Create your models here. class Contact(models.Model): email = models.EmailField(max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, null=False, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' # Pulls "first_name" from User AUTH_USER_MODEL found in core.models.py # Adds ability to sort by first_name in admin panel @admin.display(ordering='user__first_name') def first_name(self): return self.user.first_name # Pulls "last_name" from User AUTH_USER_MODEL found in core.models.py # Adds ability to sort by last_name in admin panel @admin.display(ordering='user__last_name') def last_name(self): return self.user.last_name class Meta: ordering = ['user__first_name', 'user__last_name'] core.models.py from django.contrib.auth.models import AbstractUser … -
Css file is not linked to html in django app when deployed with Hostinger
I am a beginner in Django, I am building a web app that works good in local, but when I deploy to Hostinger with FileZilla, the css "stylee.css" is not well linked to the html. index.html <link rel="stylesheet" type="text/css" href="{% static 'css/stylee.css' %}"> I tried several combinations of paths, but it didn't work. Here is my file architecture : `/templates index.html /static /css stylee.css ` Thank you. I tried adding this to my settings.py file : ` STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static_assets'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', )` I also tried changing the files permissions on Hostinger But it did not work. -
Django ValidationError not being raised, causing clean() to return None
I have the following form fields on a ModelForm subclass: forms.py class ProjectUpdateForm(ModelForm): start_date = DateField(...) due_date = DateField(label="Due Date", required=True, widget=CustomDatePicker(), validators=[validate_not_past]) def clean(self): super().clean() # Problem: this isn't this raising a ValidationError... start_date = self.cleaned_data.get('start_date') due_date = self.cleaned_data.get('due_date') if start_date > due_date: # ...instead getting a TypeError from this line! raise ValidationError("Project Start Date cannot be after Project End Date") validators.py def validate_not_past(value): today = datetime.date.today() if value and value < today: raise ValidationError('This date cannot be in the past.', code='invalid') Anytime that I enter a date in the past, the applications throws a TypeError: '>' not supported between instances of 'datetime.date' and 'NoneType' (see comments above for clarity). After attempting to troubleshoot, the POST data comes in fine from the form. The problem occurs because run_validators() is raising the ValidationError triggered by the validate_not_past, validator (above) as expected. However, rather than raising the ValidationError, the self.cleaned_data dictionary just doesn't get a due_date key. I can't figure out why I'm not getting a ValidationError raised. I can't find code elsewhere that catches it. Thanks in advance. -
How to use selenium on extracting data and adding them to django database?
I'm new to Django and have no idea how it works with all those files. Right now I'm trying to use selenium to extract some data from a website and adding them to the database created on my Django project. I used w3schools tutorial for Django (blame them if I don't understand anything :) ) and right now I'm at this stage: https://www.w3schools.com/django/django_insert_data.php But I want to use selenium and extract data from a website and add them to the database, but I have no idea how to do it. Anything can help. Please save me... -
Swifter error "AppRegistryNotReady: Apps aren't loaded yet." with Django models
I'm trying to populate a database with django models and I've used the Swifter structure to parallelize a pandas apply, like this: df.swifter.force_parallel(enable=True).apply(lambda row: migrate(row), axis = 1) When apply function loaded 1000 objects into database it gave me "AppRegistryNotReady: Apps aren't loaded yet." error.