Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx returning a 403 instead of proxying to uWSGI
I am currently facing an issue. I have a Flask application set up on a DigitalOcean server with endpoints that will later be called from within a Django project. Hitting these endpoints from Insomnia or Postman works well, but when the endpoints are triggered from within the Django application, Nginx returns a 403. Here's my nginx configuration for the Flask app: server { listen 443 ssl; listen [::]:443 ssl; #listen 80; ssl_certificate /etc/ssl/certs/site.com.pem; ssl_certificate_key /etc/ssl/private/site.com.key; server_name app.site.com; #location = /favicon.ico { access_log off; log_not_found off; } location / { include uwsgi_params; uwsgi_pass unix:/home/site/server/server.sock; } } What could be wrong guys? -
Transfer Django 2D list to Javascript Array
Views.py op=[[19.076, 72.87], [28.557166, 77.163675]] op=simplejson.dumps(op) context={'coord':op} return render(request, 'output.html' , context) Template.html var a = "{{coord |safe}}"; Still, the 'a' variable comes out to be string type and not array type.How to make it a 2d array. -
Django / Heroku Deploying - ModuleNotFoundError: "No module named 'django'"
I get the ModuleNotFoundError: "No module named 'django' if I deploy my Django-Project to Heroku. Does anyone know why that is? the complete log file, which comes after opening, is attached. I've been searching for several hours, but can't solve it.. 2021-04-24T21:54:55.188701+00:00 heroku[web.1]: State changed from crashed to starting 2021-04-24T21:54:59.835950+00:00 heroku[web.1]: Starting process with command `gunicorn MPLoadManagement.wsgi --log-file -` 2021-04-24T21:55:02.907766+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Starting gunicorn 19.9.0 2021-04-24T21:55:02.908183+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Listening at: http://0.0.0.0:3028 (4) 2021-04-24T21:55:02.908277+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [4] [INFO] Using worker: sync 2021-04-24T21:55:02.909677+00:00 app[web.1]: /app/.heroku/python/lib/python3.9/os.py:1023: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used 2021-04-24T21:55:02.909678+00:00 app[web.1]: return io.open(fd, *args, **kwargs) 2021-04-24T21:55:02.912935+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [7] [INFO] Booting worker with pid: 7 2021-04-24T21:55:02.919805+00:00 app[web.1]: [2021-04-24 21:55:02 +0000] [7] [ERROR] Exception in worker process 2021-04-24T21:55:02.919807+00:00 app[web.1]: Traceback (most recent call last): 2021-04-24T21:55:02.919817+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-04-24T21:55:02.919818+00:00 app[web.1]: worker.init_process() 2021-04-24T21:55:02.919818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 129, in init_process 2021-04-24T21:55:02.919818+00:00 app[web.1]: self.load_wsgi() 2021-04-24T21:55:02.919819+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2021-04-24T21:55:02.919819+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-04-24T21:55:02.919820+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-04-24T21:55:02.919820+00:00 app[web.1]: self.callable = self.load() 2021-04-24T21:55:02.919820+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 52, in … -
Upload image file from Angular to Django REST API
I want to select an image and POST that to the Django REST API that I have built but I am getting an error in doing so ""product_image": ["The submitted data was not a file. Check the encoding type on the form."]" I can create and update strings and integers but when I try add the image field I get this error. I can POST images through Postman so I don't think its my API that's at fault. Can anyone help me out here as I have looked around but can't seem to find anything. add-product.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { ApiService } from 'src/app/api.service'; import { Product } from 'src/app/models/Product'; import { Location } from '@angular/common'; import { Shop } from '../../../models/Shop'; @Component({ selector: 'app-add-product', templateUrl: './add-product.component.html', styleUrls: ['./add-product.component.css'] }) export class AddProductComponent implements OnInit { product!: Product; selectedFile!: File; colours = [ 'Red', 'Blue', 'Orange', 'Yellow', 'White', 'Black', 'Navy', 'Brown', 'Purple', 'Pink' ] categories = [ 'Food & Beverages', 'Clothing & Accessories', 'Home & Garden', 'Health & Beauty', 'Sports & Leisure', 'Electronic & Computing' ] stock = [ 'In … -
Can we use filter while defining manytomanyfiled in django?
I have a user table with user type as actor, singer, producer etc. I have another table Movies name = models.CharField(max_length=100) category = models.ManyToManyField(Category, related_name='movies_category') release_date = models.DateField() actors = models.ManyToManyField(User, related_name='movies_actors') producer = models.ManyToManyField(User, related_name='movies_producers') singers = models.ManyToManyField(User, related_name='movies_singers') length = models.TimeField() when I create movie object then for actors fields only those user object should come which has user_type as actor and same for producer and other fields, how can I do that? -
Error trying to create new groups using django Group model
I am creating a role management using django groups, but I am running into a problem and it is that when I want to create new groups through the Group model with a serializer, it generates the following error str object has no attribute _meta: This is my serializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) This is my view: class CreateGroup(APIView): def post(self, request, format=None): serializer = GroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
how to add picture field in forms.py Django-Allauth
how to add picture or image field in forms.py Django-Allauth , i tried do this but when i click signup it don't save my image to user profile why forms.py : class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name') last_name = forms.CharField(required=True,label='Last Name') image = forms.ImageField(required=True,label='your photo') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.image = self.cleaned_data['image'] user.save() return user -
using custom model fo django djoser
i am creating api endpoints for user management using Djoser and i want to use a custom model to create user and login i only want to use email. the user entity given to me does not have a username field below i will share the various settings i have set up for my apps #accounts/model.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) REQUIRED_FIELDS = ['first_name', 'last_name'] USERNAME_FIELD = 'email' def __str__(self): return self.email My serializer file #accounts/serializers.py from djoser.serializers import UserCreateSerializer, UserSerializer from rest_framework import serializers from rest_framework.fields import CurrentUserDefault from .models import CustomUser class UserCreateSerializer(UserCreateSerializer): class Meta: model = CustomUser fields = ['id', 'email', 'first_name', 'last_name'] #settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ) } AUTH_USER_MODEL = 'accounts.CustomUser' DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', # 'current_user': 'accounts.serializers.CurrentUserSerializer' } when i try to register user i get TypeError at /auth/users/ create_user() missing 1 required positional argument: 'username' Request Method: POST Request URL: http://127.0.0.1:8000/auth/users/ Django Version: 3.1 Exception Type: TypeError Exception Value: create_user() missing 1 required positional argument: 'username' Exception Location: /home/femiir/.virtualenvs/codegarage/lib/python3.8/site-packages/djoser/serializers.py, line … -
How to restore postgress db on pythonanywhere
I couldn't find guidelines on how to restore Postgres DB 'pythonanywhere' on their documentation. Any help is appreciated! -
Django ValueError: Cannot use QuerySet for "": Use a QuerySet for "User"
I'm working on a project in CS50w where I have to show the posts of the user I'm following and I'm getting the following error ValueError: Cannot use QuerySet for "Following": Use a QuerySet for "User". models.py: class Post(models.Model): """Tracks all the posts""" text = models.TextField(max_length=256) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) class Following(models.Model): """Tracks the following of a user""" user = models.ForeignKey(User, on_delete=models.CASCADE) following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") And this how I'm trying to retrieve the posts of the users I'm following: views.py # Gets all the posts from the users the current user is following followings_usernames = Following.objects.filter(user=request.user) posts = Post.objects.filter(user=followings_usernames) Any help is appreciated. -
Why "None" is appearing in between Navbar and Body in Django cms
I haven't any thing in between navbar and body but this None is appearing and I am unable to understand why. I am sharing my Home template where it is appearing. Check the code between navbar and placeholder Slider. {% load cms_tags menu_tags sekizai_tags static %} <!--load template libraries of Sekizai and CMS tag --> {% load thumbnail %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> <!-- in case you want other languages --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> {% page_attribute "meta_description" %} <!--should have description of pages--> <meta name="author" content=""> <title>Smart Learn - {% page_attribute "page_title" %} </title> <!--In title page name should come first then website title --> {% render_block "css" %} <!-- loading css here render_block comes with sekizai lib to allow templates to included--> <!-- Bootstrap core CSS --> {% addtoblock "css" %} <!--for sekizai tags --> <link href="{% static "vendor/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> {% endaddtoblock %} <!-- Custom styles for this template --> {% addtoblock "css" %} <link href="{% static "css/smart-learn.css" %}" rel="stylesheet"> {% endaddtoblock %} </head> {% cms_toolbar %} <!-- from cms toobar --> <body> <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="/">Smart … -
Django Shell with autocomplete and colored text
About 6 months ago, I was developing with Django and could do the usual python manage.py shell, and the command line would come up with colored text, and allow me to type in a few characters, press tab, and it would suggest completions. It was a huge help for learners like me, I think. Now, it no longer does this. It's a boring black/gray terminal and tab completion doesn't work. I'm using a Python 3.9 virtual environment, Django 3.2, and Pycharm (April 21). Does the terminal show colored text and do completions for anyone else currently? If so, please share your django/python versions & setup. I would gladly replicate to get this functionality back. -
How do I properly compare two different models based on their field values and output the differences?
I am trying to figure out how to produce the output between two querysets that have similar fields. I have two different models where I keep identical fields, and at times I want to show the differences between these two models. I have researched and successfully used sets and lists in my python code, but I can't quite figure out how to leverage them or determine if I Can. Sets seems to strip out just the field values, and when I try to loop through my sets, it doesn't currently work because it's just the values without the keys. Example: class Team(models.Model): player = models.Charfield coach = models.Charfield class TeamCommittee(models.Model): player = models.Charfield coach = models.Charfield I want to be able to query both models at times and be able to exclude data from one model if it exists in the other. I have spent the afternoon trying to use sets, lists, and loops in my django templates but can't quite work this out. I have also tried various querysets using exclude.... I tried something like.... query1 = TeamCommittee.objects.filter(id=self.object.pk).values('coach','player') query2 = Team.objects.filter(id=self.object.pk).exclude(id__in=query1) When I use the approach above, I get TypeError: Cannot use multi-field values as a filter value. I … -
Django Request.query_parmas issue
Below is the url that i am going to get, i am able to retrieve the specific data with the patientName and patientNRIC. However, how should I make to be variables, using params? like I would like to pass in to values to the function but achieved the same information instead of hard coded. Thank you for your help. test.py import requests def get_patient(): # patientName= {'patientName': patientName} # patientNRIC = {'patientNRIC': patientNRIC} p = {'patientName':'John','PatientNRIC':'S1111111A'} django_url = "https://4cfe2cdde986.ngrok.io/test/?patientName=John&patientNRIC=S1111111A" r = requests.get(django_url) r = r.json() print(r) get_patient() like so -
Why do i get "expected string or bytes-like object" while testing Fashion-mnist model in django with a local image?
I'm trying to deply Fashion-mnist model in a django project and found this error :"expected string or bytes-like object" when trying to test the model using predict function after doing some changes on the image (after loading it )with a local image from my computer . Here is the predict function in Views.py: @csrf_exempt def predict(request): path = "D:/desktop/pullover.jpg" im = Image.open(os.path.join(path)) convertImage(im) x = Image.open(OUTPUT, mode='L') x = np.invert(x) x = Image.resize(x, (28, 28)) x = x.reshape(1, 28, 28, 1) with graph.as_default(): out = model.predict(x) print(out) print(np.argmax(out, axis=1)) response = np.array_str(np.argmax(out, axis=1)) return JsonResponse({"output": response}) other functions i used in predict function in Views.py: def getI420FromBase64(codec): base64_data = re.sub('^data:image/.+;base64,', '', codec) byte_data = base64.b64decode(base64_data) image_data = BytesIO(byte_data) img = Image.open(image_data) img.save(OUTPUT) def convertImage(imgData): getI420FromBase64(imgData) utils.py from keras.models import model_from_json import tensorflow as tf import os JSONpath = os.path.join(os.path.dirname(__file__), 'models', 'model.json') MODELpath = os.path.join(os.path.dirname(__file__), 'models', 'mnist.h5') def init(): json_file = open(JSONpath, 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) loaded_model.load_weights(MODELpath) print("Loaded Model from disk") loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # graph = tf.get_default_graph() graph = tf.compat.v1.get_default_graph() return loaded_model, graph Any kind of help would be appreciated . -
How to check user type and direct them to respective pages in Django?
I am building a Django project where I have two categories of users. I have two models namely StudentUser and Recruiter. However, I provide only one login page and depending on the user type I direct them to either student_hompage or recruiter_homepage. I am not sure how to proceed for the recruiter part. Can you guys help please? Here is my code. models.py class StudentUser(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) region = models.CharField(max_length=50) phone_num = PhoneNumberField() contact_email = models.EmailField() bio = models.TextField() linkedin = models.URLField(max_length=200) user_type = models.CharField(max_length=10) def __str__(self): return self.user.username class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) position = models.CharField(max_length=50) phone_num = PhoneNumberField() company_name = models.CharField(max_length=100) company_country = models.CharField(max_length=60) company_street = models.CharField(max_length=100) company_city = models.CharField(max_length=100) status = models.CharField(max_length=20) user_type = models.CharField(max_length=10) def __str__(self): return self.user.username views.py def user_login(request): error="" if request.method == "POST": username = request.POST['email'] print(username) password = request.POST['password'] #CHECK IN USER TABLE FOR MATCHING UNAME AND PASSWD user = authenticate(username=username, password=password) #CHECKING IF USER IS VALID -->RESOLVES TO TRUE/FALSE if user: try: user1 = StudentUser.objects.get(user=user) if user1.user_type == "Student": login(request,user) messages.success(request, "You are now logged in!") return redirect('home') else: error = True except: error = True else: … -
Django: Reverse not found. 'teachers_detail' is not a valid view function or pattern name
I'm new in django. I am using this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views, but can't get the right work of my application. I created an app "education" in my "edusys" project. I'm trying to get the list of teachers from database and go to every teacher's page, where I'll be able to see their information from database. I get the next error when I use "runserver": Reverse for 'teachers_detail' not found. 'teachers_detail' is not a valid view function or pattern name. What am I doing wrong? I can't solve the problem myself and can't find the right answer in google. My files of this project looks like this: education/models.py : from django.db import models from django.urls import reverse class Teachers(models.Model): tcode = models.CharField(max_length=10, primary_key=True) last_name = models.CharField(max_length=20) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20, null=True, blank=True) department_s = models.ForeignKey('Departments', on_delete=models.SET_NULL, null=True) employee_post = models.CharField(max_length=20) academic_degree = models.CharField(max_length=40) email = models.EmailField(max_length=50) GENDER_UNIT = ( ('m', 'Мужчина'), ('f', 'Женщина'), ) gender = models.CharField(max_length=1, choices=GENDER_UNIT) class Meta: ordering = ['last_name'] def __str__(self): return '%s %s %s' % (self.last_name, self.first_name, self.middle_name) def get_absolute_url(self): return reverse("teachers_detail", args=[str(self.tcode)]) education/urls.py : from django.urls import path from . import views from django.conf.urls import url app_name = 'education' urlpatterns = [ url(r'^$', views.index, … -
How do I install a loader for my Vue project?
I'm trying to create a Vue project and, upon creating a new method in my 'myapi/views.py' file, I get this error message when running npm run serve from 'Django_Repository\DB_Vue_Project\vueproject': > vueproject@0.1.0 serve C:\Users\username\Documents\GitHub Projects\Django_Repository\DB_Vue_Project\vueproject > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin ERROR Failed to compile with 1 error 1:53:38 PM error in C:/Users/username/Documents/GitHub Projects/Django_Repository/myapi/views.py Module parse failed: Unexpected token (2:5) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | import requests > from django.shortcuts import render | from rest_framework import viewsets | from django.db import connection # This is for the my_custom_sql method. @ ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js 5:0-52 139:18 -31 @ ./src/App.vue?vue&type=script&lang=js @ ./src/App.vue @ ./src/main.js @ multi (webpack)-dev-server/client?http://10.5.1.195:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js Here's my views.py file: import requests from django.shortcuts import render from rest_framework import viewsets from django.db import connection # This is for the my_custom_sql method. from .models import Customer, Address, Order, Purchase, State, VideoGameID from .serializers import CustomerSerializer, AddressSerializer, OrderSerializer, PurchaseSerializer, StateSerializer, \ VideoGameIDSerializer def home(request): response = requests.get('http://127.0.0.1:8000/customers/') data = response.json() return render(request, 'test.html', { 'customerId': data['customerID'], 'cusFirstName': data['cusFirstName'] }) def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 … -
Enable download button when Quiz pass
I have these models in my Django Quiz app class Quiz(models.Model): quiz_title = models.CharField(max_length=300) num_questions = models.IntegerField(default=0) subject=models.ForeignKey(Subject,on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.quiz_title class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question_text = models.CharField(max_length=300) question_num = models.IntegerField(default=0) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=300) correct = models.BooleanField(default=False) def __str__(self): return self.choice_text I want when user pass Quiz then download certificate enable else disable I have different no. of Quizes in Different subjects...The main Idea is that I have courses and within courses I have sections And every sections of Course has Quizes so Every course has diffferent no. of sections and Quizes I want when user passes all the included Quiz in the sections like if first section has 3 quizes then if user pass all 3 quizes then certificate enable for download else disable...I have created logic for Quiz attempt and Result as well just problem is how can I get if student pass all the quizes that are included in the sections..Thanks Here is Quiz attempt and result views/logic def single_quiz(request, quiz_id): quiz = get_object_or_404(Quiz, pk=quiz_id) num_questions = len(quiz.question_set.all()) # deletes quiz and returns to home if no questions created if num_questions == 0: quiz.delete() … -
Django Annotate with additional data
I have a model of Courses and Categories for the courses which is a choice field. Ideally I would like to have a single query which counts the number of courses per category and shows the actual name of the course. CATEGORY = ( ('itd', 'IT Development'), ('wd', 'Web Design'), ('iandd', 'Illustration and Drawing'), ('sm', 'Social Media'), ('ps', 'PhotoShop'), ('crypto', 'CryptoCurrencies'), ) category = models.CharField(max_length=100, choices=CATEGORY) My current annotate query context['course_by_category'] = Course.objects.values('category').annotate(count=Count('category')) Returns the following which is correct but I also want the name of the Category, not the abbreviated [{'category': 'crypto', 'count': 6}, {'category': 'iandd', 'count': 5}, {'category': 'itd', 'count': 2}, {'category': 'ps', 'count': 6}, {'category': 'sm', 'count': 3}, {'category': 'wd', 'count': 5}] I end up using this in the HTML as follows: {% for course in course_by_category %} <div class="col-lg-4 col-md-6"> <div class="categorie-item"> <div class="ci-thumb set-bg" data-setbg="{% static 'img/categories/1.jpg' %}"></div> <div class="ci-text"> <h5>{{THIS_IS_WHERE_I_WANT_COURSE_NAME}}</h5> <p>Lorem ipsum dolor sit amet, consectetur</p> <span>{{course.count}} Courses</span> </div> </div> </div> {% endfor %} From what I read here, my request doesn't seem possible the way I'm approaching it: Selecting additional values after annotate in Django From what I read here, it isn't quite what I want but at least I can get the … -
Convert image in ImageField to numpy array
class Image(models.Model): image = models.ImageField(upload_to="uploads/%Y/%m/%d", null=False, blank=True) How convert ImageField to numpy array? -
How to pass a value from anchor tag to a function in views in Django
I have a model object movie and I want to pass movie.mid to addmovie function in views anchor tag in my html - <a href="{% url 'addmovie' %}" style="color:chocolate;">Add to watched</a></div> -
Django RestAPI - only allow access to users data with JWT Authentication
I have the following API: Model: class Todo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20, default="") text = models.TextField(max_length=450, default="") done = models.BooleanField(default=False) View: class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer permission_classes = [IsAuthenticated] def get_queryset(self): id = self.request.query_params.get("id") queryset = Todo.objects.filter(owner__id=id) return queryset Serializer: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ("id", "owner", "name", "text", "done") I use rest_framework_simplejwt for my tokens and the following path to receive my token: path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), This is the token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE5Mjg4ODAwLCJqdGkiOiJhY2E4MjM5ZGMyZjA0NGE5YWE4NzM3NWZjMDc2NWQ0YSIsInVzZXJfaWQiOjF9.xJ4s971XE0c9iX0Ar1HQSE84u_LbDKLL4iMswYsk2U8 When I decode it on the jwt.io I can see that it contains the user id: { "token_type": "access", "exp": 1619288800, "jti": "aca8239dc2f044a9aa87375fc0765d4a", "user_id": 1 } A request on http://localhost:8000/todos/?id=1 without the token in my request header does not work (fine!), but with the token, I also can access http://localhost:8000/todos/?id=2 which is of course undesired. I only want access to http://localhost:8000/todos/?id=1 (the coresponding user_id from the payload) How can I do this? -
ModuleNotFoundError: No module named 'MyApp.urls'
This part of code is admin urls When i try to run this Error Occurs from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from MyApp import views urlpatterns = [ url(r'^first_app/', include('MyApp.urls')), path('', views.index, name="App"), path('admin/', admin.site.urls), ] This part of code is app urls i am trying to pass app urls to admin urls but seems something went wrong from django.conf.urls import url from MyApp import views urlpatterns = [ url('', views.second_index, name="index"), ] -
How to insert data on OneToOne relatiotion model in Django?
I have extended User model. Model name is userextend. I wanted to add two more field. Here is my userextend model. class userextend(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) major = models.CharField(max_length=50) student_id = models.CharField(max_length=20) After user completed the registration, I want to run register function from views.py and want to save major and student_id on userextend model. views.py: def register(request): form = CreateUserForm() if request.method =='POST': form = CreateUserForm(request.POST) major = request.POST.get('major') student_id = request.POST.get('student_id') if form.is_valid(): b = userextend.objects.create(user=form,major=major,student_id=student_id) #I tried this form.save() context = {'form': form} return render(request, 'library_site/register.html',context)