Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retain a queue of model instances in django to be used accross views (please read description)
I am trying to implement an algorithm as a variation of priority based sorting algorithms used in operating systems. Suppose i have a model Task: class Task(models.Model): priority = 1 name = "task" burst_time = 5 arrival_time = models.DateTimeField(auto_now_add=True) Something like this. And one of my view does something to the task: def my_view(request, pr): instances_queue = Task.objects.filter(priority=pk).order_by(-arrival_time) instance = instance_queue[1] #do something with the instance instance.burst_time = instance.burst_time - 1 instance.save() #if burst_time == 0 dequeue But simply using objects.filter() is not good, so what i ideally need is, to create a class like i have here: class Queue(): def __init__(self, quantum, priority): self.items = [] self.quantum = quantum self.priority = priority def isEmpty(self): return self.items == [] def enqueue(self, item): item.Qtime = self.quantum item.priority = self.priority self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def peek(self): return self.items[-1] as a model, where items are instances of my Task model. I should be able to make multiple queues and interchange tasks based on needs. The way i am implementing this is getting far too complex. Can someone please help with the design of the Queue model so i can use that as a universal queue for my Task … -
Unable to retrieve individual blog in react using axios
I have spent a couple of time trying to figure out why I'm not able to obtain individual blog post detail page using axios. The code does not return any data (It is returning undefined) I have the follow code: import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; export default const blog_detail = (props) => { const [blog, setBlog] = useState({}); useEffect(() => { const slug = props.match.params.id; const fetchData = async () => { try { const res = await axios.get(`https://example.com/blog/${slug}`); setBlog(res.data); } catch (err) { } }; fetchData(); }, [props.match.params.id]); const createBlog = () => { return {__html: blog.body} }; const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; return ( <div> <div dangerouslySetInnerHTML={createBlog()} /> </div> ); }; The code returns data for those I practice with but never works in my case but everything seems to be similar to theirs. -
How do I fix internal server error while executing JQuery?
I was building a quiz app via python and Django.I wrote some jQuery code and it supposed to show result in console.My code is attached below.It shows "Internal Server error" It is written inside quiz.js console.log("Hello") const url=window.location.href console.log(url) const quizBox=document.getElementById('quiz-box') let data $.ajax({ type:'GET', url:`${url}data`, success:function (response){ console.log(response) data=response.data data.forEach(el=>{ for(const [question,answers] of Object.entries(el)){ quizBox.innerHTML+=` <hr> <div class="mb-2"> <b>${question}</b> </div> ` } }) }, error:function (error){ console.log(error) } }) -
Django how to send array to JavaScript for dynamically display pie chart?
I have an array in Django views.py and I want to send it to HTML and display a piechart, but failed, I've tried many other methods and read many tutorials, in most of the case, they have a field in models that store some number, and they display those number. In my case, I need to calculate the subtotal of tasks that are in different states. I'm not sure how to output those data to chart.js with proper labels or any other piechart if there's any recommendation? views.py def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', {"counts_data": counts_data}) html <script> $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: [1,2,3], datasets: [{ label: '# of Votes', data:counts_data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] }, options: { responsive:false } }); }); </script> -
DRF & drf-haystack: How to use prefetched querysets in drf-haystack's serializer
Is there any way to use a prefetched queryset when retrieving information associated with an object in a HaystackSerializer's SerializerMethodField? In a normal DRF view, it is possible to pass prefetched queries to the serializer using prefetch_related or annotate from its own queryset instead of the Search queryset. What should I do in this case? # search_indexes.py class VideoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr="title") published_at = indexes.DateTimeField(model_attr="published_at") def get_model(self): return Video # views.py class VideoSearchView(ListModelMixin, HaystackGenericAPIView): index_models = [Video] serializer_class = VideoSearchSerializer filter_backends = [HaystackFilter, HaystackOrderingFilter] ordering_fields = ["published_at"] def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # serializers.py class VideoSearchSerializer(HaystackSerializer): is_viewed = serializers.SerializerMethodField() is_favorited = serializers.SerializerMethodField() class Meta: index_classes = [VideoIndex] search_fields = ("text",) fields = ( "title", "is_viewed", "is_favorited", "is_wl", ) def get_is_viewed(self, obj): user = self.context["request"].user if user.is_authenticated: try: History.objects.get(user=user, video_id=obj.pk) return True except History.DoesNotExist: pass return False def get_is_favorited(self, obj): user = self.context["request"].user if user.is_authenticated: try: Favorite.objects.get(user=user, video_id=obj.pk) return True except Favorite.DoesNotExist: pass return False -
Converting Form Function to a Class Based View in a Django Project
I am trying to convert my Form which is laid out in a function to be in a class based view: Here is what I have reach out. Function: def add_business_plan(request): info = Info.objects.all() if request.method == 'POST': form = infoForm(request.POST) if form.is_valid(): form.save() business_name = form.cleaned_data.get('businessName') info_id = form.instance.id messages.success(request, f'PDF created for {business_name}!, No.({info_id})') return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': True}) else: form = infoForm() print(form.errors) return render(request, 'businessplan/businessplan.html', { 'form': form, 'successful_submit': False, "Info": info } ) -
Django ValueError The view todo_lists.views.visualisation didn't return an HttpResponse object. It returned None instead
everyone. I have views.py here, I want to calculate different status' tasks and output to chart.js piechart. I have tried many ways but none of them works. I have an error saying my views def didn't return HttpResponse, can anyone tell me what it is, please? I used template tags in html. Thanks. views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.annotate( to_do_count = Count('id', filter=Q(status='to_do')), in_progress_count = Count('id', filter=Q(status='in_progress')), done_count = Count('id', filter=Q(status='done')) ).order_by('-to_do_count') context = {'counts_data', counts_data} return render(request, 'todo_lists/progress.html', context) ''' html ''' data: { labels: [1,2,3], datasets: [{ label: '# of Votes', data:[{% for todo in counts_data %} {{ todo }}, {% endfor %}],, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] }, ''' -
How to troubleshoot a failing Django LDAP connection
I am using Django Rest with active directory authentication. I have built a simple app with the following settings: import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType # Baseline configuration. AUTH_LDAP_SERVER_URI = 'ldap://ad_server.com' AUTH_LDAP_BIND_DN = "CN=binduser,OU=Users,OU=ad_server,DC=ad_server,DC=com" AUTH_LDAP_BIND_PASSWORD = "somepassword" # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=Groups,OU=ad_server,DC=ad_server,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") # Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com" AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=django,ou=groups,dc=example,dc=com" # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", 'username': 'cn', "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", "is_staff": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", "is_superuser": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache distinguished names and group memberships for an hour to minimize # LDAP traffic. AUTH_LDAP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ) Running an LDAP search from the cli works just fine However when I try to authenticate with the http://localhost:8000/admin/ I get the following error. The terminal on the other hand doesn't show anything: There must be a better way to troubleshoot … -
How can I create a database using django then connect that database to my django app?
I am making an app that makes sql queries and display the resulting tables, I have already a database connected to my app and makes the queries correctly but I want to upload a sql file, create the database in my computer and then make queries to that database. Is that possible? Can django create a database from a sql file in mysql server and then use that database? Or do I need to make everything manual like create the database and then change my settings.py? -
Django 3.2.8 custom middleware returns 302 redirect errors
I am looking to use custom middleware to redirect a user to a their profile role if their profile role value is set to '0'. Below is the current code I am using, but is causes a 302 redirect loop. This is based on other examples I found on the internet, but no luck in finding a fix. Any ideas will be greatly valued. from django.shortcuts import redirect from django.utils.deprecation import MiddlewareMixin from django.http import HttpResponseRedirect class UserRoleMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): redirect_url = '/role/' if request.user.is_authenticated and request.user.profile.role == '0': print('user must define a role') return HttpResponseRedirect(redirect_url) return None Response: [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 -
How to make a correct redirection in django app after user delete his message in website?
i am developing a website watching a video course and sometimes i don't agree with mentor decisions about solving some tasks. And while i am trying to figure this out, the problem has already taken really much time and i haven't still found how to solve this. At first i show the necessary source code. urls.py and the the error url: path('delete-message/<str:pk>/', views.delete_message, name='delete-message') views.py and function where error happens: @login_required def delete_message(request, pk): message = Message.objects.get(id=pk) room_id = message.room.id if request.method == 'POST': message.delete() return redirect(f'room/{room_id}') ### WHAT DO I HAVE TO DO ??? return render(request, 'delete-message.html') delete-message.html and error form: <form method="POST"> {% csrf_token %} <h2> <p>Are you sure you want to delete this message ?</p> </h2> <a href="{{request.META.HTTP_REFERER}}">Go Back</a> <input type="submit" value="Confirm"> </form> After redirect() works it sends me to the unexisted url: 127.0.0.1:8000/delete-message/10/room/5but it had to be http://127.0.0.1:8000/room/5... Why is it not as such result as i've expected ? Also i've tried to do this: In the views.py i change function where except of redirect i transfer room_id to the template: @login_required def delete_message(request, pk): message = Message.objects.get(id=pk) room_id = message.room.id if request.method == 'POST': message.delete() return render(request, 'delete-message.html', {'id': room_id}) In the template delete-message.html i … -
Aggregate and condense time-series values using Django Querysets?
I'm currently trying to create a small crypto tracker for fun using CoinMarketCap's API. The API can be called every 5 minutes – each time returning the current exchange value, however I want to plot my graph in 30-minute intervals. How can I condense my exchange value information of 5-minute increments down to 30-minute data points featuring the respective "Open, High, Low, Close" information? (aka first exchange value, max exchange value, min exchange value, last exchange value) Example data: 2021-10-23 10:00:00 – price: 50 2021-10-23 10:05:00 – price: 45 2021-10-23 10:10:00 – price: 43 2021-10-23 10:15:00 – price: 47 2021-10-23 10:20:00 – price: 51 2021-10-23 10:25:00 – price: 70 2021-10-23 10:30:00 – price: 65 2021-10-23 10:35:00 – price: 55 2021-10-23 10:40:00 – price: 47 2021-10-23 10:45:00 – price: 51 2021-10-23 10:50:00 – price: 62 2021-10-23 11:55:00 – price: 50 Desired output: 2021-10-23 10:00 – open: 50, high: 70, low: 45, close: 57 2021-10-23 10:30 – open: 65, high: 62, low: 47, close: 50 Sample model: class Crypto(models.Model): ticker = models.CharField(max_length=10) price = models.DecimalField(max_digits=7, decimal_places=2) percent_change = models.DecimalField(max_digits=5, decimal_places=2) timestamp = models.DateTimeField(auto_add_now=True) -
Ckeditor how to change button text
My django site uses the image upload feature. I want to change the send it to the server button text to upload I have checked what seems like every source file but I cannot filed a reference to button. How would I go about changing it. I found this posts trying to do the same thing but it is very old -
Use params or class method for on_delete.SET()? (How to change ForeignKey field on delete)
Is it possible to use SET() for a ForeignKey's on_delete with params and/or a class method? I essentially want to leverage the model or the ForeignKey model to generate a new field. E.g. def create_new_relationship(obj): return obj.relationships.first() class Item(models.Model): name = CharField() relationships = ManyToMany("self", on_delete=SET_NULL) relationship = ForeignKey("self", on_delete=SET( # method with params or # class method possible here? )) def create_new_relationship(self): return self.relationships.first() The only other option I can think of is to add a pre/post-delete signal to Item. -
python django webapp packaging sdist
When I run python setup.py sdist in my project directory and check the contents with tar --list -f .\dist\my_project_name-1.0.tar.gz I see one important python file (manage.py) and a couple of directories templates, which contains .html files, and static, containing .css files, are missing. I've looked at many questions: Q1 Q2 Q3 Q4 but adding a MANIFEST.in or adding the following lines to my setup.py didn't change anything. And what about my manage.py? Shouldn't python files be included by default with sdist? include_package_data=True, data_files=[('templates','my_app/templates/my_app/*.html']), ('static', ['my_app/static/my_app/static/css/*.css'])] Also, I get the same exact result with python setup.py sdist bdist_wheel (although I'm not sure what's the difference with the two commands). -
flow of code from view to serializer class in django rest framework
I am trying to understand the code flow in Django rest framework from view class to serializer class. Like we know if we create an object of a class, the class gets instantiate with that object. And if there are other functions inside that class, we can call that function using the object we just created followed by dot and that function name. It looks something like this. class Person: def __init__(self, name, address): self.name = name self.address = address def details(self): print (f"My name is {self.name} and I live in {self.address}") obj1 = Person("John","London") obj1.details() For example in the above code, when we run obj1= .... , the person class will instantiate with values name and address. And then we can call the details function using the class object that we just created obj1. Now in Django Rest, class LeadsView(APIView): permission_classes = [IsAuthenticated] def put(self, request, pk=None, *args, **kwargs): id = pk abc = Lead.objects.get(id=id) print("before serializer") serializer = LeadSerializer(abc,data=request.data) if serializer.is_valid(): print("after serializer validation") serializer.save() print("after save") return Response({ "message": "Coupon hase been updated", "data": serializer.data }, status=status.HTTP_200_OK) return Response(serializer.data) class Leadserializer(serializers.ModelSerializer): class Meta: model = Lead fields = 'all' def update(self,instance,validated_data): .......... print("iam inside the serializer class") … -
How to fix "assess has been blocked by CORS policy: No 'Access-Control-Allow-Origin' in react
I have a web application with react frontend and django backend. Some of the APIs from the backend are being blocked by cors policy whereas others are not. For example, The API to fetch blog posts const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/posts`) is returning data but the API for individual posts const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/${slug}`); is blocked. The register and login APIs are blocked too. I have added the domain to the list of allowed url in settings.py but that didn't solve the issue. The error I'm getting in the detail page is: undefined:1 Access to XMLHttpRequest at 'https://.api.example.co/blog/undefined' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. When I use Postman to test the API's everything works properly. But In react app it's only the API that list posts or items that are returning data, others are blocked. Why such behaviour, and how do I fix it? -
gcloud builds submit of Django website results in error "does not have storage.objects.get access"
I'm trying to deploy my Django website with Cloud Run, as described in Google Cloud Platform's documentation, but I get the error Error 403: 934957811880@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden when running the command gcloud builds submit --config cloudmigrate.yaml --substitutions _INSTANCE_NAME=trouwfeestwebsite-db,_REGION=europe-west6. The full output of the command is: (the error is at the bottom) Creating temporary tarball archive of 119 file(s) totalling 23.2 MiB before compression. Some files were not included in the source upload. Check the gcloud log [C:\Users\Sander\AppData\Roaming\gcloud\logs\2021.10.23\20.53.18.638301.log] t o see which files and the contents of the default gcloudignore file used (see `$ gcloud topic gcloudignore` to learn more). Uploading tarball of [.] to [gs://trouwfeestwebsite_cloudbuild/source/1635015198.74424-eca822c138ec 48878f292b9403f99e83.tgz] ERROR: (gcloud.builds.submit) INVALID_ARGUMENT: could not resolve source: googleapi: Error 403: 934957811880@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden On the level of my storage bucket, I granted 934957811880@cloudbuild.gserviceaccount.com the permission Storage Object Viewer, as I see on https://cloud.google.com/storage/docs/access-control/iam-roles that this covers storage.objects.get access. I also tried by granting Storage Object Admin and Storage Admin. I can't add a "Viewer" role too (https://stackoverflow.com/a/68303613/5433896), it's not one of the options in the permissions list. I enabled Cloud run in the Cloud … -
Unable to do migrations using docker.yml file- django+postgres
I get the following error while I try to run my django project on docker. relation "DBTable" does not exist at character 218 I figured out it was because the migrations weren't being applied. So I changed my Dockerfile as follows to make migrations before starting the server: FROM python:3.7 WORKDIR /ServerCode2/ COPY . /ServerCode2/ RUN pip install -r req.txt EXPOSE 8000 CMD ["python", "manage.py", "makemigrations" ] CMD ["python", "manage.py", "migrate" ] CMD ["python", "manage.py", "runserver", "--noreload" ] Below is my docker-compose.yml file version: '3.7' services: server: build: context: ./Appname dockerfile: Dockerfile image: serverimgtest1 container_name: servercontest1 ports: - 8000:8000 links: - db:db depends_on: - db db: image: postgres environment: POSTGRES_DB: "DBname" POSTGRES_HOST_AUTH_METHOD: "trust" ports: - 5432:5432 client: build: context: ./appfrontend dockerfile: Dockerfile image: clientimgtest1 container_name: clientcontest1 depends_on: - server ports: - 3000:3000 However, I still see the error which says the relation does not exist. Is there any way I could achieve migrations through commands in dockerFile? -
I've a problem with django admin login with abstract superuser
I am developing a separate author abstract model for my blog site. The authors in this abstract model connect to my post application, another application of mine, with a foreign key and create the author-post relationship. However, I can't even log in to the django admin panel, it says my password is wrong, but I'm sure it's correct. what is the reason of this? this is my abstract user model code from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,) class CustomAccountManager(BaseUserManager): def create_superuser(self,email,firstName,lastName,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get("is_staff") is not True: raise ValueError("Buraya erişim izniniz bulunmamaktadır. Lütfen yöneticiyle iletişime geçiniz.") if other_fields.get("is_superuser") is not True: raise ValueError("Buraya erişim sadece En üst düzey kullanıcılar içindir. Lütfen yöneticiyle iletişime Geçiniz") return self.create_user(email,firstName,lastName,password, **other_fields) def create_user(self, firstName,lastName,email,password, **other_fields): if not email: raise ValueError(_("Email Adresinizi Doğrulamalısınız!")) email = self.normalize_email(email) user = self.model(email=email,firstName=firstName,lastName=lastName, **other_fields) user.set_password(password) user.save() return user class Author(AbstractBaseUser,PermissionsMixin): id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=100) email = models.EmailField(_("email adresi"),max_length=100,unique=True) lastName = models.CharField(max_length=100) displayName = models.CharField(max_length=300) gender = models.CharField(max_length=50) avatar = models.ImageField(upload_to="avatar") bgImage = models.ImageField(upload_to="background") slug = models.SlugField(editable=False, unique=True) desc = models.TextField() jobName = models.CharField(max_length=50,default="Author Job") … -
ModuleNotFoundError: No module named 'tokenize'
So I tried to start a Django project called 'Tokenize' and it gave me the error - Command Error: 'tokenize' conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name. I then deleted all of my tokenize.py files from my computer and it's now giving me this error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/bin/pip", line 5, in from pip._internal.cli.main import main File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/_internal/cli/main.py", line 4, in import logging File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/logging/init.py", line 26, in import sys, os, time, io, re, traceback, warnings, weakref, collections.abc File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/traceback.py", line 5, in import linecache File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/linecache.py", line 11, in import tokenize ModuleNotFoundError: No module named 'tokenize' I searched everywhere and can't out how to fix this issue. I know I screwed up but any assistance is appreciated. -
(Django) type object 'User' has no attribute 'USERNAME_FIELD'
Down here I'm trying to create a custom user registration form and this is the error I keep getting: That is the result of me using UserCreationForm in place of forms.ModelForm according to many sources. I tried setting USERNAME_FIELD = username but it said The field 'username' clashes with the field 'username' from model 'members.user' Before I switched to UserCreationForm the registration did not even create any new user. I successfully created the login functionality, but failed when it came to the registration. It did not show any response after registration form submission. My code is as followed: members/models.py class User(models.Model): username = models.CharField(max_length=50, error_messages=login_errors_mess) password = models.CharField(max_length=50, error_messages=password_errors_mess) members/forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'password', ] widgets = { 'username': forms.TextInput(attrs={ 'class': 'form-control', 'data-val': 'true', 'data-val-required': 'Please enter your user name'}), 'password': forms.TextInput(attrs={ 'class': 'form-control', 'data-val': 'true', 'data-val-required': 'Please enter your password' }), } members/views.py def register(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('login') # return redirect('login') form = RegisterForm() return render (request, "registration/register.html", context={"form": form}) templates/registration/register.html <form method="POST" action="/register/"> {% csrf_token %} {% comment %} {{ form }} {% endcomment %} <div class="form-group"> <label … -
JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT
I am opening this question as a last resort. I am learning JWT and want to implement it on my django app. I didn't have any issues regarding Basic auth and Token auth, but JWT doesn't authenticate my user... This is my settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'api.permissions.AdminOrTeacherOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } This is my view: class StudentList(APIView): authentication_classes = [] permission_classes = [AdminOrTeacherOnly] def get(self, request, format=None): students = Student.objects.all() serializer = StudentListSerializer(students, many=True) if not serializer.data: return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.data, status=status.HTTP_200_OK) This is my AdminOrTeacherOnly permission class: class AdminOrTeacherOnly(permissions.BasePermission): """ Object-level permission to only allow teachers of a student to edit. Assumes the model instance has an `owner` attribute. """ message = 'Only admin or teacher can edit student detail.' def has_permission(self, request, view): # Only teacher and/or admin user will be able to, # edit and/or list this view. is_staff = bool(request.user and request.user.is_staff) is_teacher_group = str(request.user.groups.all().first()) == 'teacher' return is_staff or is_teacher_group I am able to get refresh and access token successfully: Then, I am adding this to Headers as follows and send a request: On debugger, when it enters the permission class: Here, request.user returns <django.contrib.auth.models.AnonymousUser object at 0x104f5afd0> I don't … -
How can I solve it - Django problem with sql on heroku
I have such a problem with Django and possibly sql on herok. The localhost application works without errors. However, after uploading to the heroku, an error was received. ProgrammingError at / relation "zpiappa_images" does not exist LINE 1: INSERT INTO "zpiappa_images" ("name", "user_id", "images", ".. My code in models looks like this: class Images(models.Model): name = models.CharField(max_length=64) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, ) images = models.ImageField(upload_to='images') editted_images = models.ImageField(upload_to='filters', null=True, blank=True) is_editted = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.name def save(self): self.editted_images.save(self.images.name, self.images, save=False) super(Images, self).save() class Meta: verbose_name = 'Image' verbose_name_plural = 'Images' How can I solve it? -
How to display particular table row in javascript
I want to display the table row based on the checkbox selection where I need to display only the particular row. I'm noob in JavaScript and took this snippet from stackoverflow. I tried to modify the code as per the requirement but I couldn't able to figure out. this is my data which I retrieve from the database In the JS script it matching the td value but I don't mention the table value explicitly all it comes from the db.im trying to figure it out since 2days ur help will be much appreciated <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> </tr> </tbody> <script> // checkbox selection function filter_type(box) { //alert("checked"); var cbs = document.getElementsByTagName('input'); var all_checked_types = []; for(var i=0; i < cbs.length; i++) { if(cbs[i].type == "checkbox") { if(cbs[i].name.match(/^country/)) { if(cbs[i].checked) { all_checked_types.push(cbs[i].value); } } } } if …