Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: redirect the user from the login page if he has already logged in
I want to redirect the user from the login page if he is already logged in; this means that the user who logged in will no longer have access to the login page. the login page looks something like this: example.com/login this is my code in view.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: logIn(request, user) return redirect('/') else: messages.info(request, 'username or password is wrong') context = {} return render(request, 'account/login.html', context) -
Django authentication with firebase?
How can I override default Django authentication with firebase authentication with Phone, Google, Facebook, Email? I planned to build a mobile application where I used firebase for authentication ( why firebase because with this I can easily access cloud databases, more control over ads, analytics, testing, and distribution ) But the rest of the things I planned to used Postgres / MongoDB and Django ( why Django it's easy to build pre-build admin panel and manage ) But the problem is that how can I control my Django authentication because 90 to 95 % of databases are stored in Django so I also need that authentication so we can get more control over data with security Like we have a comment, like, a poll system in my application, and the data are stored in Django. So if we have a users model in Django so we can easily map the data in Django otherwise it's taken a lot of effort and it also compromises the security. Note: there might be one solution is there but I don't want to use that because it makes an application is more complex and it also has security issues. The solution is to create … -
run haversine formula on MariaDB server using annotate() in django orm
Hii I trying to run the Haversine formula on the MariaDB base on my model the model is class MeteorologicalSite(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) class Site(models.Model): lat = models.DecimalField("Latitude", max_digits=17, decimal_places=15) lon = models.DecimalField("Longitude", max_digits=17, decimal_places=15) and this is the Haversine function def Haversine_formula(self, site): from django.db.models.functions import Cos, Sin, ASin, Sqrt, Radians lat1 = Radians(site.lat) lon1 = Radians(site.lon) lat2 = Radians(F("lat")) lon2 = Radians(F("lon")) r = 6372.8 sql_haversine_formula = 2 * r * ASin( Sqrt( Sqrt( Sin((lat1-lat2)/2)**2+ Cos(lat1)* Cos(lat2)* Sin((lon1 - lon2)/2)**2 ) ) MeteorologicalSite.objects.filter(radiation=True)\ .annotate(mycolumn=sql_haversine_formula) and it doesn't run it return <django.db.models.query.QuerySet object at 0xffff57b99ca0> I tried to use lat and lon for 1 and 2 as Decimal directly and it still doesn't work so I understand that my problem is in the way I use annotate or in me sql_haversine_formula Does anyone have an idea why this does not work? sorry for my English -
How to update value when i used only request.POST method for save data into database.? i did not use any form class
enter image description here model for database. enter image description here data save method. -
Make models in admin site appear only in debug mode otherwise display one model
I want to make my models appear in admin site only when debug variable is set to True, when debug is set to False I only want to display one model I am looking for an elegant way to implement this I thought I could do something like this: if not DEBUG: admin.site._registry = {} admin.site.register(Model 1) But where does this code should live? I want it to execute after execution of all admin.py modules from all applications where models registration takes place. To sum it up DEBUG = TRUE Admin site shows: Model 1 Model 2 Model 3 DEBUG = FALSE Admin site shows: Model 1 -
XLWT || IndexError at /XLS tuple index out of range Request Method : GET
I am currently running into the above-mentioned error when running the below code that is supposed to print to pdf when the button is clicked. The following is how the code is called on html <a href="{% url 'printToXLS' %}" class="btn btn-primary">Print To Excel</a> Please see the error message and views.py below Views.py: def printToXLS(request): response = HttpResponse(content_type= 'application/ms-excel') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.xls' wb=xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('TrialBalance') row_num = 0 font_style = xlwt.XFStyle() columns = ('Account' , 'Description' , 'Debit' , 'Credit') all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) for col_num in range(len(xAll_l)): ws.write(row_num , col_num , columns[col_num] , font_style ) font_style = xlwt.XFStyle() for row in xAll_l: row_num += 1 for col_num in range(len(row)): ws.write(row_num , col_num , str(row[col_num]) , font_style) wb.save(response) return response Error : IndexError at /XLS tuple index … -
Login user from different application into Django application
I have a use-case where I have to login a user from different application in my django application. The user will click a button in the primary application where the user data like username, firstname, lastname and userid is sent to me as jwt token. In my application I am decrypting the jwttoken and fetching the user data json and then using django.contrib.auth import login method to login the user and then sending the response user = User.objects.get(user_name=user_name) login(request, user) response = HttpResponse(json.dumps({'message': "you are successfully logined in"}), content_type='application/json') response.status_code = 200 return response where in the primary application then the user is redirected to dashboard of my application whose view is @login_required(login_url='/testserver/user/login/') def dashboard(request): user = User.objects.get(user_name=request.user) return render(request, 'home.html', {'user':user}) the problem is that the user is redirected to /testserver/user/login/ url and if i remove it @login_required(login_url='/testserver/user/login/') then i see that request.user is AnonymousUser how can i fix this to make it end to end working -
DJANGO, returning from AJAX call does not update html
I am updating a db entry through a click on a select dropdown. After confirming the selection I send an AJAX POST to another view that applies required changes on the db and reverse to the previous page. The problem is that the destination page does not reflect the new values unless I refresh. select html (project.html) <select id="update_status_outreach" name="{{outreach.id}}_____{{project.id}}"> {% for outreach_status in outreach_statuses %} {% if outreach_status.0 == outreach.outreach_status %} <option value="{{ outreach.outreach_status }}" selected>{{ outreach.outreach_status }}</option> {%else%} <option value="{{ outreach_status.0}}">{{outreach_status.0}}</option> {% endif %} {%endfor%} </select> Javascript (project.html) document.getElementById("update_status_outreach").onchange = changeListener; function changeListener() { var name = this.name.split("_____"); var project_id = name[1]; var outreach_id = name[0]; var new_status = this.value; if(confirm("Placejpòdore")) { $.ajax({ type: "POST", url: "{% url 'action:update_status_outreach' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", 'project_id': project_id, 'outreach_id': outreach_id, 'new_status': new_status }, }); } } update_status_outreach view in outreach.py @login_required(login_url='action:login') def update_status_outreach(request): project_id = request.POST['project_id'] outreach_id = request.POST['outreach_id'] new_status = request.POST['new_status'] jobproject = get_object_or_404(JobProject, id=project_id) if jobproject.owner != request.user: raise HttpResponse(status=500) else: outreach_to_be_updated = Outreach.objects.get(id=outreach_id) outreach_to_be_updated.outreach_status=new_status outreach_to_be_updated.save() return HttpResponseRedirect(reverse('action:project', args=(project_id,))) project view in project.py @login_required(login_url='action:login') def project(request, project_id): if request.method == 'POST': outreach_id = request.POST.get('outreach_id') new_rank = request.POST.get('new_ranking') update_rank(outreach_id=outreach_id, new_rank=new_rank) project_referred = get_object_or_404(JobProject, id=project_id) jobpositions_referred = JobPosition.objects.filter(jobproject=project_referred) … -
how to format large numbers using spaces instead fo comma?
I am using django.contrib.humanize intcomma tag to format large numbers like this $18,162,711,641 but what I want spaces instead of comma, like this $18 162 711 641 How can I achieve this? Thank you. -
python / django log in issue
Currently I have usertypes in this python/django project and I was able to log in as admin but I am not being able to login as student or staff I am using postgres as data base can anyone please help me ? my models.py file models.py class CustomUser(AbstractUser): user_type_data = ((1,"HOD"), (2,"Staff"), (3,"student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Admin(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Staff(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Students(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=255) profile_picture = models.FileField() address = models.TextField() course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING) session_start_year = models.DateField(blank=True, null=True) session_end_year = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type==1: Admin.objects.create(admin=instance) if instance.user_type==2: Staff.objects.create(admin=instance) if instance.user_type==3: Students.objects.create(admin=instance, course_id = Courses.objects.get(id=1), session_start_year="2020-04-02", session_end_year="2022-01-01", profile_picture="", gender="") @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): if instance.user_type==1: instance.admin.save() if instance.user_type==2: instance.staff.save() if instance.user_type==3: instance.students.save() here are my views.py file views.py def DoLogin(request): if request.method != "POST": return HttpResponse("<h2> Do log in first </h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get("email"),password=request.POST.get("password")) … -
How to pass context dictionary in django rest framework? Help me and make my life simple and easy
First of all, I want to pass multiple queryset in the same view or you can say same url path or route. In django we pass this context dictionary like this qs = Qs.objects.all() ps = Ps.objects.all() context = { 'qs' : qs, 'ps' : ps } return render(request, 'some.html', context) and in the frontend we just call them via qs or ps and we get the object. I want to do the same in django rest framework and react frontend. @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) related = Product.objects.filter(category=product.category).exclude(_id=pk).order_by('?')[:4] print(related) serializer = ProductSerializer(product, many=False) return Response(serializer.data) I have two queryset here product and related. I want to pass both of them in the same serializer or response. I don't know actually how to pass multiple queryset. In the react frontend const productDetails = useSelector(state => state.productDetails) const {loading, error, product} = productDetails useEffect(() => { dispatch(listProductDetails(match.params.id)) }, [dispatch, match]) const addToCartHandler = () => { history.push(`/cart/${match.params.id}?qty=${qty}`) } when I call this <h3>{product.name}</h3> I get the name from product queryset. I want the same process for my related queryset. Suppose if I call {related.name} then it should show me the name of the related product. In the backend if … -
Why does print show SRID 3847 in Geodjango?
I'm developing an app using Geodjango and PostGIS. In the admin area of my site, all polygons are displayed correctly with the (default) SRID of 4326 e.g. SRID=4326;POLYGON ((0.6564331054687499 52.13854550670472, 0.6289672851562499 52.08456959594681, 0.7553100585937497 52.08456959594681, 0.6564331054687499 52.13854550670472)) Why, when I print to the web server/console does the SRID show in 3857? The above admin area polygon is printed as: SRID=3857;POLYGON ((73073.79904062848 6825215.129639958, 70016.31790922143 6815431.190019455, 84080.73111369385 6815431.190019455, 73073.79904062848 6825215.129639958)) I don't know whether I can continue manipulating polygons as I can't, at present, be sure of their projection. -
Raising an issue after upgrading Django version
I upgraded my Django version from 3.1.2 to 3.2. But it gives me this error. django.core.exceptions.ImproperlyConfigured: Cannot import 'api'. Check that 'apps.api.apps.ApiConfig.name' is correct. Please give a suggestion. Thank you. -
Django, Javascript: passing data disables functions inside app
I'm aware that a lot of people asked a similiar question, but none of these helped me with my problem!? Inside my view I'm passing the name of the active user... views.py def index(request): user = User.objects.get(username=request.user) user_name = f"{user.first_name} {user.last_name}" json_data = json.dumps(user_name) return render(request, 'index.html', {"user_name": json_data}) script.js let user_name = {{user_name|safe}}; But when trying to attach the data to my variable inside javascript, I'm getting the following error and all of my other functions inside js stop working! SyntaxError: Unexpected token '{' Does someone know what I'm doing wrong here? Thanks for your help and have a great day! -
How to iterate on dict which contains another dict in Django?
i have some issue with my application. Here's my code : view.py dict_test = {} for result in myMongoDbRequest: dict_in_dict = {} for otherResult in result["myList"]: dict_in_dict[otherResult["1"]] = [otherResult["2"], otherResult["3"]] dict_test[result["name"]] = [result["value1"], dict_in_dict] template_filter.py @register.filter def get_in_list(list, index): return list[index] template.html {% for key, values in dico_test.items %} <div id="div{{key}}"> {% for key, value in values|get_in_list:1.items %} <div class="{{ key }}"> {{ value }} </div> {% endfor %} </div> {% endfor %} Obviously, the .items in the template is incorrect, but i wonder how to resolve this problem ? Maybe with another filter ? I try several things but nothing works, like this filter : @register.filter def convert_in_dict(a): return vars(a) {% for key, value in values|get_in_list:5|convert_in_dict.items %} But django raise Could not parse the remainder: '.items' from 'values|get_in_list:1|convert_in_dict.items' -
Having one single generic Viewset that can be resolved through its router basename on Django Rest Framework
My question is more about refactoring, best practices and potential vulnerability while organizing my routes and views in DRF. My app is really a simple one and all the views are to be described in the same fashion. Take my views.py file for example: # views.py class TrackView(viewsets.ModelViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer class AlbumView(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = TrackSerializer class ArtistView(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer class ChartView(viewsets.ModelViewSet): queryset = Chart.objects.all() serializer_class = ChartSerializer And in urls.py I can do: #urls.py router = DefaultRouter() router.register(r'tracks', TrackView) router.register(r'albums', AlbumView) router.register(r'artists', ArtistsView) router.register(r'charts', ChartsView) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] In this scenario every new View is a copied logic of each other only changing the name of the model they use, and for every new model added that needs a view I would basically have to create the same repeated code in urls.py and views.py. Instead of doing like that I refactored it like this: # views.py from rest_framework import viewsets class APIView(viewsets.ModelViewSet): queryset = None def get_queryset(self): return eval(self.basename).objects.all() def get_serializer_class(self): return eval(self.basename+'Serializer') # urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from top_charts.views import * from .routes import ROUTE_NAMES router … -
Why does this work?? Class Meta, model = User
Can someone please explain this?? I'm in the process of trying my first post-tutorial project. I've made a model called Profile with 4 attributes (given_name, surname, bio, image). I've made a form called ProfileForm which inherits from UserCreationForm and i've added the 4 attributes of my model into the form as form attributes. MY Question is: Why does it only work like this class Meta: model = User This is my models.py file class Profile(models.Model): given_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) bio = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return self.given_name class Meta: ordering = ['given_name'] This is my forms.py file class ProfileForm(UserCreationForm): firstName = forms.CharField(max_length=255) lastName = forms.CharField(max_length=255) bio = forms.CharField(widget=forms.Textarea) image = forms.ImageField() class Meta: model = User fields = ['firstName', 'lastName', 'username', 'password1', 'password2', 'bio', 'image'] This is my views.py file def sign_up_view(request): if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): user = form.save() login(request, user) profile = Profile.objects.create( given_name=form.cleaned_data['firstName'], surname = form.cleaned_data['lastName'], bio = form.cleaned_data['bio'], image = form.cleaned_data['image']) return redirect('home') else: form = ProfileForm() return render(request, 'core/sign_up.html', {"form": form}) Note : I'm able to achieve my desired outcome, but I'm having trouble in understanding how its working. **Also if i wanted … -
XLWT TypeError at /XLS 'tuple' object is not callable
I am getting the above-mentioned error when clicking the "export to excel" button on my form. I am using the XLWT module to print the excel sheet, so I think it might have something to do with that. Please see the below code and full error message: Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum import datetime from datetime import datetime from dateutil.relativedelta import relativedelta import xlwt def printToXLS(request): response = HttpResponse(content_type= 'application/ms-excel') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.xls' wb=xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('TrialBalance') row_num = 0 font_style = xlwt.XFStyle() columns = ('Account' , 'Description' , 'Debit' , 'Credit') all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = … -
celery logging not showing in django application inside docker shell
from logging import error @app.task def partial_bid_created_event(event): event_time = get_event_time() print('wrong function') a = getWrongfunc() # here it should throw error because that function is not exist. error showing in my docker django shell . antiquely | Starting development server at http://0.0.0.0:8000/ antiquely | Quit the server with CONTROL-C. watcher | wrong function watcher exited with code 1 watcher | Monitoring 1 contracts using %s rinkeby.infura.io watcher | subscription id: %s 0x1feed3405f0f0680df9c9684957ad03d It is just showing exited with code 1 but i am expecting exact error for logging Is it because of celery async task ? How to get exception on this error . Please take a look -
Add and remove items in ManyToMany relation in Django
I have model as follows: class BusinessUnitGroup(models.Model): name = models.CharField(max_length=255) business_units = models.ManyToManyField(to=BusinessUnit, blank=True, null=True) capacity = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.name Now in an view I have fields with group id's where the business unit needs to be added. From the other one it needs to be remove if it exists. I do it as follows: business_unit = get_or_none(BusinessUnit, id=business_unit_id) # Groups old_groups = BusinessUnitGroup.objects.exclude(id__in=form_data['groups']) for group in old_groups: group.business_units.remove(business_unit) new_groups = BusinessUnitGroup.objects.filter(id__in=form_data['groups']) for group in new_groups: group.business_units.add(business_unit) Where form_data['groups'] is an param and it's just a list of ids [1, 2, 3] That works fine, but is there any better way to do it? -
Instantiating URLS , Views and Models in Django
Is there a way to instantiate SQLite models, views and URLs in Django? I have tried to research it but couldn't find anything on the automatic creation of views, URLs and templates etc. I have thought of maybe creating models that have key values which tell the program what to instantiate, however, this doesn't seem to be the most efficient and user-friendly way of doing this -
Django tries to return the file (which was previously generated by Celery) and cannot find it
i deployed two docker files to Heroku (Celery, Django), but due to the fact that the volume is not scrapped as in docker-compose, Django tries to return the file (which was previously generated by Celery) and cannot find it. How can I solve the problem? -
In Dajango How import a function from another view?
I have this folder hierarchy: |---- ksy |---- shop |---- views.py |---- over_time |---- views.py On my shop/views.py, I have this functions: def check_consumed_hour(request, job_no, booked_hour): estimate_hour, consumed_hour = 0.0, 0.0 obj_job = JobNumbers.objects.get(Q(job_no=job_no)) total_consumed_hour = float(obj_job.consumed_hour) for job in obj_job.estimatedhours_set.all(): if request.user.userinform.section in job.shop_name: estimate_hour = float(job.man_hour) else: pass for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: consumed_hour = float(job.man_hour) else: pass balance_hour = estimate_hour - consumed_hour book_hour = float(booked_hour) # if balance_hour >= book_hour: # ESTIMATED HOUR EXCEED MSG SHOW. for job in obj_job.consumedhours_set.all(): if request.user.userinform.section in job.shop_name: man_hour = float(job.man_hour) man_hour += book_hour job.man_hour = str(man_hour) job.save() total_consumed_hour += book_hour obj_job.consumed_hour = str(total_consumed_hour) obj_job.save() return True else: pass On my core/views.py, I need the day_studies() function, so I'm importing like this: from plater_shop.views import check_consumed_hour But I'm getting the error: from shop.views import check_consumed_hour ImportError: cannot import name 'check_consumed_hour' How can I make this importation? I don't want to reply all code. -
How i access my django project on browser after deploye on aws ec2 used by container?
containers are working good but I'm trying to access it on browser ,but fail to access -
is there any way to send webrtc frame to python script?
I created first web app(python and django) which shows client's webcam frames This is my video.js 'use strict'; // On this codelab, you will be streaming only video (video: true). const mediaStreamConstraints = { video: true, }; // Video element where stream will be placed. const localVideo = document.querySelector('video'); // Local stream that will be reproduced on the video. let localStream; // Handles success by adding the MediaStream to the video element. function gotLocalMediaStream(mediaStream) { localStream = mediaStream; localVideo.srcObject = mediaStream; } // Handles error by logging a message to the console with the error message. function handleLocalMediaStreamError(error) { console.log('navigator.getUserMedia error: ', error); } // Initializes media stream. navigator.mediaDevices.getUserMedia(mediaStreamConstraints) .then(gotLocalMediaStream).catch(handleLocalMediaStreamError); However, I want to use client's webcam frame as an input to my machine learning script(python .py) file. In local, it was easily done via opencv and numpy. But in web, I cannot feed frames to ML model. Any suggestions?