Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
QUERYSET: How can I filter by field in a list (case insensitive)
I want to filter field using __in but i also want it to be case insensitive when i pass it to the query This is something Ive tried: fields = ['Banana','Water Melon','grapes'] MyModel.objects.filter(field__icontains__in=fields).values() and returned an error (of course). I want it to be something like that. Any help/enlightenment would be appreciated, Thank you in advance for the help -
How can I solve the "Cookie csrftoken will be soon rejected because it has the sameSite attribute set to none" warning on my Django 2.0 application?
I am using version 2.0 and I just noticed on my firefox developer tools this message: Cookie “csrftoken” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value. It seems that django 2.0 does not store SameSite attribute along with this cookie. (for example something like this: Set-Cookie: CookieName=CookieValue; SameSite=Lax;) Is there a workaround for this? Or am I doing something wrong? -
Jquery UI autocomplete with pictures in Django
I have ab autocomplete enabled in my Django project. It works fine. But I would like to add pictures to the suggestions. I tried the official docs but information is parsed: https://jqueryui.com/autocomplete/#custom-data My JS: $(function() { $(".prod").autocomplete({ source: "/finder/search_auto", maxShowItems: 5, open: function() { $('.ui-menu') .width(250); } , select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } My view: def search_auto(request): if request.is_ajax(): q = request.GET.get('term', '') products = Product.objects.filter(real_name__icontains=q) results = [] for pr in products: product_json = {} product_json = pr.real_name results.append(product_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) I can't figure out how to pass my product picture url into my dataan how to display it. -
DOCKER does not run manage.py
somebody can explain why docker does not wanna run Django server Thats my structure of project: app bankproject env docker-compose.yml Dockerfile manage.py requirements.txt There is my file Docker: # pull official base image FROM python:3.8.0-alpine # set work directory WORKDIR .app/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt requirements.txt RUN pip install -r requirements.txt # copy project COPY . /app CMD["python", "manage.py", "runserver", "0.0.0.0:8000"] and my docker-compose.yml version: '3.7' services: web: build: ./ command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/app ports: - 8000:8000 env_file: - ./.env.dev Actually in folder env I have file .env.dev and it is consist : DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] The mistake I got : web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory app_web_1 exited with code 2 -
How to change the storage default location in Scorm xblock
I am using hawthorn version open edX, Also using scorm xblock https://github.com/overhangio/openedx-scorm-xblock for upload the scorm. by default, it is using /edx/var/edxapp/media/scorm/ path. I want to change the storage location. For this, I have tried two solutions. First solution:- In the lms.env.json and cms.env.json change the path. MEDIA_ROOT = /my/new/path/media/ MEDIA_URL = /media/ Also, added below the line in url.py urlpatterns = patterns('',# ... the rest of your URLconf goes here ...) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It is uploaded successfully in this path /my/new/path/media/, but when I try to get in the LMS, it is showing a 404 error. Second solution:- As par scorm xblock, We can change to default location by give the path in below code. XBLOCK_SETTINGS["ScormXBlock"] = { "LOCATION": "/my/new/path/media/",} I have added the code in comman.py and scormxblock.py, But it is not working. Or, Please correct me if I am adding the code in the wrong place. -
Django: TemplateDoesNotExist at /
I am using Django 3.0.7 and have a project named starling and an app named piggybank. I placed my index.html inside templates/starling inside the piggybank directory The following urls.py is inside piggybank: from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path("", views.index, name="index"), ] The urls.py in starling (project) is: """starling URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("piggybank.urls")), path('admin/', admin.site.urls), ] My full settings.py: """ Django settings for starling project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Hosting multiple sub domains on the same windows 10 server running django application
I need to host multiple sites with subdomains all pointing to the same windows10 server. virtual hosts for different sub-domains points to different WSGI files. Venv activation is added in wsgi file. The issue happening is first Django settings file which is invoked is applied to all sub-domains. eg. company1.example.com -> /company1_wsgi.py -> company1_settings.py company2.example.com -> /company2_wsgi.py -> company2_settings.py Now, company1_settings is applied for both company1.example.com and company2.example.com. I see right WSGI files are called based on the sub-domain but for some reason os.environ['DJANGO_SETTINGS_MODULE'] is not being updated dynamically based on the subdomains and always uses the first value wsgi file python_home= 'E:/app/demo/env' activate_this = 'E:/app/demo/env/Scripts/activate_this.py' exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys from django.core.wsgi import get_wsgi_application import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('E:/app/demo/env/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('E:/app/demo/crm') sys.path.append('E:/app/demo/crm/appointment_scheduler') os.environ['DJANGO_SETTINGS_MODULE'] = 'appointment_scheduler.settings.preprod' application = get_wsgi_application() <VirtualHost *:443> ServerName demo.crmbaylyn.com WSGIScriptAlias / "E:/app/demo/crm/appointment_scheduler/wsgi_win.py" WSGIPassAuthorization On WSGIScriptReloading On <Directory "E:/app/demo/crm/appointment_scheduler"> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> Order allow,deny Allow from all Require all granted </Directory> Alias /static "E:/app/demo/crm/static" <Directory "E:/app/demo/crm/static"> Require all granted </Directory> SSLEngine on SSLCertificateFile "C:/Apache24/conf/crmbaylyn.cert" SSLCertificateKeyFile "C:/Apache24/conf/crmbaylyn.key" </VirtualHost> <VirtualHost *:80> RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} … -
AttributeError no attribute 'delete'
i am working on a website where users can send friend request, accept request, cancel request. I have an error AttributeError object has no attribute 'delete'. This happens when i cancel friend request. This my code i tried: Model: class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') date = models.DateTimeField(auto_now_add=True, null= True) class Meta: verbose_name = 'Friend request' verbose_name_plural = 'Friend requests' ordering = ['-date'] def __str__(self): return "from {}, to {}".format(self.from_user.username, self.to_user.username) Views.py: @login_required def cancel_friend_request_view(request, id): user = get_object_or_404(User, id=id) frequest = FriendRequest.objects.filter(from_user=request.user, to_user=user).first() frequest.delete() print(frequest) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Django ORM extract weekday as string from queryset
What I'm trying to do is annotate a queryset with the weekday strings ("monday", "tuesday" etc). I understand how to get the int values: queryset = queryset.annotate( weekday_int=ExtractWeekDay("date"), ) But I'm having trouble getting the string values themselves. I've tried using an ExpressionWrapper, but F objects don't seem to play well with Date objects. I'm using postgres as my underlying database but can't find a related lookup_name for the generic Extract. -
How to show total number of selected object on template after selecting object on field which have OneToMany relations with other table
I am new in web app development, so not being able to do so. Please help me. My models.py contains: class Entexaminfo(models.Model): entexamses = ( ("June Session", "June Session"), ("December Session", "December Session"), ) approve_choice = ( ("Pending", "Pending"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) ename = models.CharField(max_length=16, choices=entexamses) enrollno = models.OneToOneField(Student, on_delete=models.CASCADE) #programs = models.ManyToManyField(Programs, related_name='proNames', default=0) program = models.ManyToManyField(Programs, default=0) center = models.ForeignKey(Excenter, on_delete=models.CASCADE) remarks = models.CharField(validators=[max_len_check], max_length=256, default="-") #status = models.BooleanField() status = models.CharField(max_length=8, choices=approve_choice, default="Pending") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.ename def get_absolute_url(self): return reverse('show', kwargs={'pk': self.pk}) EntexaminfoForm class contains: class EntexaminfoForm(forms.ModelForm): class Meta: model = Entexaminfo fields = ['enrollno', 'ename', 'program', 'center'] widgets = { 'program': forms.CheckboxSelectMultiple(attrs={'class': 'list-unstyled list-unline'}), } help_texts = { 'ename': '[Select Exam Session]', 'enrollno': '[Select Your Enroll Number]', 'program': '[Put Tick Mark on Program you want to join. {More than one program can be choosen.}]', 'center': '[Select Center]', } error_messages = {} labels={ 'ename': 'Exam Name:', 'enrollno': 'Enroll No.', 'program': 'Program:', 'center': 'Center:', 'remarks': 'Remarks:' } My views.py where I have created FormView, View, CreateView, I have not created manual form. I want to show total number … -
the data from view function is not passed to the html file in django
The data from the view function was not passed to the HTML file in Django. I am new to Django. To add a new page: I created an HTML page. I added a function to process in data in the view function I have added a URL to urls.py Let me know if I am missing something. Please find my code below View.py def approval_user(request): msg = "Pending User Request" print(msg) approval = [] if request.method == "POST": users = User.objects.all() for user in users: if user.groups.exists(): approval.append(user) return render(request, "approval.html", {"approval":approval,"msg" : msg}) aproval.html {% extends 'layouts/base.html' %} {% block title %} Approval {% endblock title %} {% block stylesheets %}{% endblock stylesheets %} {% block content %} <!-- (Almost) A blank page --> <div class="row gap-20 masonry pos-r"> <div class="masonry-sizer col-md-6"></div> <div class="masonry-item w-100"> <div class="row gap-20"> <!-- Pending Approvals ==================== --> <div class="col-md-12"> <div class="layers bd bgc-white p-20"> <div class="layer w-100 mB-10"> {% if msg %} <h5 class="lh-1">{{ msg }}</h5> {% endif %} </div> {% for user in approval %} <div class="layer w-100"> <div class="peers ai-sb fxw-nw"> <div class="peer peer-greed"> <h6 class="lh-1">{{ user.name }}</h6> </div> <div class="peer peer-greed"> <h6 class="lh-1">{{ user.mailid }}</h6> </div> <div class="peer"> <button class="d-ib … -
After adding media to AWS S3, Django gives me a weird error whenever I access a page with a media file
The error is like this: ValueError at /postview/24 Required parameter name not set Request Method: GET Request URL: http://127.0.0.1:8000/postview/24 Django Version: 3.0.6 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Users\Lenovo\Desktop\src\env\lib\site-packages\boto3\resources\base.py in __init__, line 118 Python Executable: C:\Users\Lenovo\Desktop\src\env\scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\Lenovo\\Desktop\\src', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Lenovo\\Desktop\\src\\env', 'C:\\Users\\Lenovo\\Desktop\\src\\env\\lib\\site-packages'] Server time: Thu, 4 Jun 2020 11:16:39 +0300 Wich has no real correlation with S3 because the error is intercepted on line 34 for some reason. This worked well until I added the S3 settings and permissions from the boto3 docs and django-storages docs. <!-- HELL --> 33 {% if user.is_authenticated %} 34 {% if user.is_superuser %} 35 <ul class="nav navbar-nav navbar-right"> 36 <li><a href="{%url 'comments'%}"><span class="glyphicon glyphicon-comment"></span> Comments</a></li> 37 <li><a href="{%url 'inbox'%}"><span class="glyphicon glyphicon-envelope"></span> Inbox</a></li> 38 <li><a href="{%url 'createpost'%}"><span class="glyphicon glyphicon-list-alt"></span> Create Post</a></li> 39 <li><a href="{%url 'logout'%}"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li> 40 </ul> 41 {% else %} My setting.py file looks like this: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = r"*********************************************" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'personal', 'users', 'contact', 'Tasks', 'storages' … -
django not cleaning up previous data
I have a django setup which does not include any models or data base. It is just simple HTML, JAVAscript and python. It seems like django is not cleaning up the previous run data. How to cleanup data from forms after every run? I am not making use of sessions also. I am new to django and don;t have much time to learn sessions and implement things. Can any one give a solution on how to cleanup data after every run? -
Django ORM bulk read query
I have a model called User which has a property called is_free() which runs a query like this @property def is_free(self): return User.objects.free_user().filter(id=self.id).exists() When i try to get multiple users and populate them using a for loop there are many SQL queries executed based on the number of users i am populating which is affecting the API timings. For Example - for user in selected_users: user_list.append({"id": job.id, "name": job.name, "is_free": job.is_free, "title_display": job.title_display}) Is there a better way to do this without changing the model? I am using Django 1.8 and Python 2.7 -
django makemigrations override to create migration files with custom names
I have a python2.7 django project (I know, I am in 20th century!) that has some models in it. I need to override makemigrations so that the migration filenames are of the form 0001.py, 0002.py and so on, and not like 0001_initial.py, 0002_model1.py and so on which is by default what happens. I already looked at how to create custom manage.py commands and I am able to override makemigrations command. Presently my code for the custom command (python2.7) looks like this: from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand class Command(CoreMakeMigrationsCommand): def handle(self, *args, **options): super(Command, self).handle(*args, **options) It is doing nothing more than calling the original makemigrations at the moment. I need to be able to modify the behaviour of how autodetector.py(which is part of the makemigrations flow) decides the naming of the files. In this file, there's method suggest_name as shown below: @classmethod def suggest_name(cls, ops): """ Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible. """ if len(ops) == 1: if isinstance(ops[0], operations.CreateModel): return ops[0].name_lower elif isinstance(ops[0], operations.DeleteModel): return "delete_%s" % ops[0].name_lower elif … -
New tags are created automatically when I edit my Django Post with django-taggit
Everytime I try to edit my post, django-taggit creates a new url for the existing tags. What is the reason behind it and how to fix it? Here is my edit post view. note = get_object_or_404(Note, pk=pk) if note.user != request.user: messages.error(request, 'You are not authenticated to perform this action') return redirect('notes') if request.method == 'POST': form = AddNoteForm(request.POST, instance=note) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user form_data.save() form.save_m2m() return redirect('note_detail', slug=note.slug) else: form = AddNoteForm(initial={ 'note_title': note.note_title, 'note_content': note.note_content, 'tags': ','.join([i.slug for i in note.tags.all()]), }, instance=note) return render(request, 'modals/edit_note_modal.html', {'form': form} -
Upload an Image to Django Rest Framework using Requests Library
I am trying to make an api endpoint for creating a post, the user can choose whether they want to upload a text(tweet) or an image alone or both, I have a validate method in my serializer for if no image nor text is sent, but it's raising the error on every try regardless if what I sent it. Am not entirely sure if this is a serializer class error or the script I wrote for sending the POST request Here is the script: import os import requests from PIL import Image ENDPOINT = "http://0.0.0.0:8000/" IMG = os.path.join(os.getcwd(), "img/img.jpg") def send_request(method="GET", path="/", data=None, img_path=None): if data is None: data = {} if img_path is not None: with open(img_path, 'rb') as image: img_file = {"image": image} req = requests.request(method, ENDPOINT + path, data=data, files=img_file) else: req = requests.request(method, ENDPOINT + path, data=data) return req.text res = send_request(method="POST", path="api/posts/create/", data={"user": 1, "content": ""}, img_path=IMG) print(res) Here's the model class: from django.db import models from django.conf import settings import uuid import os class PostQuerySet(models.QuerySet): pass class PostManager(models.Manager): def get_queryset(self): return PostQuerySet(self.model, using=self._db) def upload_post_image(instance, filename): file_extension = filename.split('.')[-1] filename = f"{uuid.uuid4()}.{file_extension}" print(os.path.join()) return os.path.join('post_image/', filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = … -
How can i write better Code for the views.py
Good Morning, i have a Question. I worked on my First Web-Application and now i finished the stuff and want to make the code a bit better. This Projekt is my Thesis Projekt too so they look into my Code and if thats too bad, ill get a bad Grade. So there are only two Points on my list, for now, which are pretty important. At first, the Projekt is for Automate some Office Stuff like Create Google or Git Repos. So we have many API Calls and we have many Buttons on this Page. To delete the User, add him or whatever. We have more than user ofc, but i dont have to listen everything. The Point now is, that i have a Tempplate where i have like 8 Buttons. Its a Management Panel where we can do tons of Actions. The Code for that is just ugly. Here is a small Example: if 'delete' in request.POST: todel = Employee.objects.get(id=id) deleteUser(request, todel, deleteOrArchive=0) if 'deactivate' in request.POST: todel = Employee.objects.get(id=id) deleteUser(request, todel, deleteOrArchive=1) So there are many Ifs like that. I use Function Based Views everywhere because i thought its not that good to use Class Based Views here. … -
How to juggle between a null value for a field in sql query
I have a sql query. It first gets all the songs from the playlists. These songs could have an entry in Block Song Table and possibly some songs may not have an entry in the block song model. So, for those songs who have an entry they will have an unblock_flag which is a boolean field and will carry either true or false. But, the concern is that those songs which will not have an entry in the block song model table, will have null values for unblock_flag. I studied nvl in SQL, but it didn't work properly. The field to be changed is core_blocksong.unblock_flag in the below query. So, if anyone can suggest any other ways to make this scenario work? select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested, core_blocksong.unblock_flag from (select id, name, artist, album, albumart, "albumartThumbnail" from (select song_id from core_plsongassociation where playlist_id in (1477)) as sinpl left join songs on sinpl.song_id=id) as songs left join (select` song_id, votes, bool_or(user_id=null) as is_requested from (select * from core_priorityrequests where client_id=2876 and is_played=False) as clpr left join core_priorityrequests_requested_by on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes) as cpr on songs.id=cpr.song_id left join core_blocksong on songs.id = core_blocksong.song_id where core_blocksong.unblock_flag='f'and … -
Cookies is not set in request header
I have a client-server application build with Angular 9 and Django and I am facing the following situation: After login, I receive the session-id in Response Header. Even if the browser sets this cookie and I am able to see it in Dev Tools > Application > Cookie, this cookie is not used in the subsequent requests. More exactly, if I make a request after login, my Django server shows that there is no session and the user is not logged in. I searched this problem on the Internet and I found out that I have to set {withCredentials: true} in request headers in my Angular project. I make an Interceptor to set {withCredentials: true} in every request header, but this is not working for me. I put this interceptor in Providers in AppModule in this way: providers: [[{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}]] Here is my code for the interceptor: @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(public auth: AuthService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { request = request.clone({ withCredentials: true }); return next.handle(request); } } This is my login in Angular: login() { // stop here if form is invalid if (!this.loginForm.valid) { return; } this.authService.login(this.loginForm.value) … -
how can add number to integerField in django models?
i have a django model like this : class Post(models.Model): pub_date = models.DateTimeField(auto_now_add=True) featured = models.booleanField(default=False) num = models.IntegerField(defualt = 0, null=True,blank=True) def save(self,*args,**kwargs): if self.featured is not None: self.pub_date = timezone.now() self.featured = False self.num = ++1 super (Post,self).save(*args,**kwargs) infact i want add number in my num field when the timezone is updated but this line self.num = ++1 isnt working -
how to values from foreignkey Fiels of a model in django?
i have three models like :Event,Device,Nodes class Device(BaseModel): """ Store device information """ did = models.CharField(_("DID"), max_length=255, unique=True, db_index=True) active = models.BooleanField(default=False) class Event(BaseModel): """ Store events info """ title = models.CharField(_("Title"), max_length=255) location = models.ForeignKey(to=Location, on_delete=models.PROTECT, null=True, blank=True) status = models.CharField( _("Status"), choices=EVENT_STATUS, max_length=255, default="notstarted") def __str__(self): return self.title class Node(BaseModel): """ Store info of Nodes """ label = models.CharField(_("Label"), max_length=255) parent_node = models.ForeignKey( to="self", on_delete=models.CASCADE, null=True, blank=True) device = models.ForeignKey( to=Device, on_delete=models.CASCADE, null=True, blank=True) event = models.ForeignKey(to=Event, on_delete=models.CASCADE) level = models.IntegerField(_("Level"), null=True, blank=True) is_active = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.label, self.level) def clean_fields(self, exclude=None): if self.parent_node == self: raise ValidationError(message={ "parent_node": "Node cannot be its own Parent Node." }) return super().clean_fields(exclude=exclude) I have doubt in query to fetch json data.In this i want to get json data values like: All Event objects fields with other fields 1)'total nodes with (not null) devices in it' as field 2)'total nodes with active devices in it' as field 3)'nodes having level 1 devices' 4)'nodes having level 2 devices' I tried using Event Models :butstauck with this queryat this : events = Event.objects.node_set.all() ####serializer as this one class EventSerializer(serializers.ModelSerializer): node = NodeSerializer() class Meta: model = Event fields = "__all__" def to_representation(self, … -
Handling 404 status with SPA using Create React App and Django API backend
Sorry if this is a duplicate! I have a SPA created with CRA and React Router and a separate (not in the same project) backend with Django to handle all APIs. I would like to know what's the best approach to handle 404 page not found url's, but having it return 404 status. Because as we know, using the <Switch /> and having a router <Route component={NoMatch} key="404_not_found" /> will display the 404 page but not return the 404 status. Now there are some topics online regarding this but I don't seem to understand what would be the best approach for my scenario. 1st suggested solution Is using express - but if I use express do I need to have it as a separate project and have it act like a proxy? if yes then that would be tedious having 3 separate projects for one platform! Or would it be possible to add express on top of my CRA in the same project? I could not find anyway of doing this! Please advise if I should follow this approach. 2nd suggested solution Would be to serve the 404 from Django backend. This would be more ideal but I did not … -
What type of authentication should I use for Django with Flutter?
I was creating FLutter project with Django + Django Rest framework as backend. What I wanted to add to the app is the user authentication and I found some ways to achieve that such as Session authentication or token authentication. According to this article https://hackernoon.com/auth-headers-vs-jwt-vs-sessions-how-to-choose-the-right-auth-technique-for-apis-57e15edd053, if we want to add user authentication for mobile api, it is best to use token authentication since session authentication is not suited for mobile phones. Thus, what I want to ask is that Is it really best to use token authentication for mobile apis instead of session authentication? -
social-auth-app-django: Refresh access_token
I use social-auth-app-django for my django website. Login all works, but after the token expires. I cant access the google's user data anymore. I found how to refresh the token, but it gives File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 17, in handle new_token = self.get_token(user=booking_user, provider='google-oauth2') File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 28, in get_token social.refresh_token(strategy) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/storage.py", line 58, in refresh_token response = backend.refresh_token(token, *args, **kwargs) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/oauth.py", line 438, in refresh_token request = self.request(url, **request_args) File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/social_core/backends/base.py", line 234, in request response.raise_for_status() File "/home/sander/.local/share/virtualenvs/app-YMrBBUv3/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token Here is some of my code def get_token(self, user, provider): social = user.social_auth.get(provider=provider) print('This is social of user: ', social) if (social.extra_data['auth_time'] + social.extra_data['expires']) <= int(time.time()): print('\n Token is out of date \n') strategy = load_strategy() social.refresh_token(strategy) return social.extra_data['access_token'] in my settings file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') # Paste CLient Key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('DJANGO_SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') # Paste Secret Key SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar.events' ]