Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using external API for token based authentication in Django (DRF)
Context My API accepts a jwt-token that I can pass to an external endpoint which will return 401 if invalid/expired or user information if still valid. Based on this I will either return 401 or filtered data belonging to the user. Also, POST request's need to involve writing who this resource belongs to for the GET to work. I tried to do this by overriding the get_queryset and perform_create methods. My viewset looks something like this: class ReportViewSet(AuthorizedUserBasedFilteredViewset): queryset = Report.objects.all() serializer_class = ReportSerializer def perform_create(self, serializer): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) serializer.save(creatd_by=username) def get_queryset(self): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) return Report.objects.filter(created_by=username) This doesn't work because get_queryset expects a queryset as response. Questions How do I bubble up the authorize exception in get_queryset? Is there some other method I should be overriding to the authentication entirely? I still need to pass the username recieved to get_queryset for the authentication to be successful Is there a better way to do this? I looked at the RemoteUserAuthenticationBackend but that still involved creation of a User object but for this use case the … -
Python issues with form.cleaned_data.get('username')
When I submit my form, if valid, it should redirect me to my home page but it doesn't due to this line username = form.cleaned_data.get('username'), when I remove it works fine but then again I need that line to get the form data. Here's my code views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') #Where the problem lies messages.success(request, 'Account created!') return redirect('home-page') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) I honestly can't figure out what's wrong with that line of code. I'm using Django v 3.0.4 btw -
Problem loading images from static in a .js file
scripts.js code: $(document).ready(function(){ $('#user').hover(function() { $('#user img').attr('src', "{% static 'images/user_selected.png' %}"); }, function() { $('#user img').attr('src', "{% static 'images/user.png' %}"); }); }); It works fine when I write it directly in my base.html file, but when I place it in an external .js file it fails to load images. Scripts.js file loads but images do not. base.html code: <head> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'js/scripts.js' %}"></script> ... </head> <body> ... <a href="{%url 'logout' %}">LOG OUT</a> <a id="user" href="#"><img src="{% static 'images/user.png' %}" height="14px" width="14px" id="user-icon" /><span id="user-name"> {{request.user.username}}</span></a> ... </body> -
Celery beat sends task regularly, but celery only processes them from time to time in production
I have a django project with celery integrated using redis. My celery worker works perfectly in local development, and now I'm deploying in production. Before daemonizing the process I want to see how celery behaves in the server. The thing is, celery beat sends the tasks correctly every minute (as I scheduled) but the worker seems not to receive it every time. Sometimes it requires 4/5 minutes until the task is received and processed. How is that possible? I have tried debugging, but there is very few information. see my setup: settings.py CELERY_TIMEZONE = 'Europe/Warsaw' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' # Other Celery settings CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'predict_assistance.alerts.tasks.check_measures', 'schedule': crontab(minute='*/1'), }, } tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task() def check_measures(): print('doing something') celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('predict_assistance') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() hereby my logs in production: [2020-03-11 16:09:00,028: INFO/Beat] Scheduler: Sending due task task-number-one (predict_assistance.alerts.tasks.check_measures) [2020-03-11 16:09:00,038: INFO/MainProcess] Received task: predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] [2020-03-11 16:09:00,046: WARNING/ForkPoolWorker-3] doing something [2020-03-11 16:09:00,047: INFO/ForkPoolWorker-3] predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e]: doing something logger [2020-03-11 16:09:00,204: INFO/ForkPoolWorker-3] Task predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] succeeded in 0.16194193065166473s: … -
Django Form Select Function
I have 2 class views Account And Transaction What I want is whenever I click add transaction and enter the amount type as debit it should Account.Balance = Account.Balance - TransactionAmount and whenever amount type is credit it should Account.Balance = Account.Balance + TransactionAmount. My Template {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Order Management</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <div class="container"> <ol class="breadcrumb"> <li><a href="/home">Home</a></li> <li> &nbsp; / &nbsp; </li> <li class="active">Add Transaction </li> </ol> </div> {% block title %}{% endblock title %} {% block content %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if submitted %} <p class="success"> Your message was submitted successfully. Thank you. </p> {% else %} <form action="" method="post"> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} Views def AddAccount(request, fk): if request.method == 'POST': form = AccountModelForm(request.POST) form.customer_id = 5 if form.is_valid(): cd = … -
Form adding new user missing 1 required positional argument in Django
I created a form to add a new user, but it throws an error _wrapped_view() missing 1 required positional argument: 'request'. This is the form: class NewEmployee(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name', 'last_name') And this is my view: @login_required(login_url='./accounts/login/') def NewEmployee(request): if request.method == 'POST': form = NewEmployee(request.POST) if form.is_valid(): form.save() return redirect('backend') else: form = NewEmployee() return render(request, 'backend/new_employee.html', {'form': form}) -
Import Django settings from several files
There are lots of hints, why one cannot pull settings from multiple files easily, like so: import base import app1 import app2 import local neither of them sees the settings from the files before and cannot modify them. One solution is to import all the file in chain: local.py: import app2 app2.py: import app1 app1.py: import base It's clumsy. ==== Another solution was to merge all the files into a single one. I actually like this one. I would like to search multiple directories (OK, at least one) for *.py files, sort them by filename and import/merge them, so: base.py -> 000_base.py local.py -> zzz_local.py ensure that base is first, local is last, the order of the other ones do not matter. Is there some Django tool / framework / model, that implements this already or, at least, helps? Thanks -
How to redirect to a different page in Django when I receive an input from a barcode scanner?
The whole project is as follows: I'm trying to build a Django based web-app for my college library. This app when idle will be showing a slideshow of pictures on the screen. However when an input is received from the barcode scanner, it is supposed to redirect it to a different age containing information related to that barcode. I'm not able to figure out how to get an input from the scanner and only then redirect it to the page for 3 seconds containing the relevant information, after the interval, it should redirect back to the page containing the slideshow. -
I am having problem : loading static files in HTML code in a Django Project . As I know for a href link we use "{% static 'addressOfFile' %}"
'How to use django template language to load these images in data-zs-src attribute . if it was data-zs-src="images/b1.jpg" then it would be easy like data-zs-source="{% static 'images/b1.jpg' %}" . but I have double quatation inside single quatation . so it is not working . plz help me with right code -
How can I save cloned form elements as Json strings in Django forms?
I have a django project. In one of my forms, I have an attribute which its name is "count" and I have a combobox which its name is "type". I want to show the "type" combobox as many as the number entered in the "count" field. So I cloned the "type" combobox by using jquery clone() function. For ex; If I enter "5" to count field, my view saves only one of the value of combobox values. How can I send these combobox values as a Json string to backend view for saving in only one charField? Here is my jquery code: $(function(){ $("#id_form-0-baglama_sayi").on('change', function(){ var count = parseInt(this.value); for(var i = 0; i < count; i++){ $( "#id_form-0-baglama_sekil" ).clone().appendTo( "#div_id_form-0-baglama_sekil"); } }); }); Here is my view: if form.is_valid(): data_list = form.cleaned_data data_dict = data_list[0] label = list(data_dict.keys()) data = list(data_dict.values()) new_data = Data(author_id = user.id) for i in range(0, len(label)): setattr(new_data, label[i], data[i]) new_data.save() Thank you! -
Styles are missing in angular build while deploying Django
I was developed angular application and take build ng build --prod command before that, I added the "deployUrl": "/static/" inside the angular.json file. after that I copied dist folder files and paste it inside the django static folder. index.html files also changed based on the requirement, pages are working fine but "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/font-awesome/css/font-awesome.css" ], this styles are missing. what can i do for this. any one help me. -
Setting up a dockerized python server on local machine gives Session data corrupted
I'm trying to set up a dockerized Python server named Bullet Train on my local machine: It has 3 components: A Postgres database A Python server A React frontend All of these 3 need to work together to get the server up and running, so this is the docker-compose file which sits at the top level of both the frontend and api-server: version: '3' services: db: image: postgres environment: POSTGRES_PASSWORD: password POSTGRES_DB: bullettrain ports: - "5432:5432" api: build: context: ./bullet-train-api dockerfile: docker/Dockerfile command: bash -c "pipenv run python manage.py migrate --noinput && pipenv run python manage.py collectstatic --noinput && pipenv run gunicorn --bind 0.0.0.0:8000 -w 3 app.wsgi && pipenv run python src/manage.py createsuperuser" environment: DJANGO_DB_NAME: bullettrain DJANGO_DB_USER: postgres DJANGO_DB_PASSWORD: password DJANGO_DB_PORT: 5432 DJANGO_ALLOWED_HOSTS: localhost ports: - "8000:8000" depends_on: - db links: - db:db frontend: build: context: ./bullet-train-frontend dockerfile: Dockerfile ports: - "8080:8080" This way, all the 3 components run in parallel. So far so good! Now to initialize it, I run the createsuperuser as stated here by following these steps: docker exec -it research_api_1 bash ## go to the context of the API server terminal run python manage.py createsuperuser ## run the createsuperuser command The command runs successfully and I … -
Django REST Framework pagination: Not found: GET /api/blog/list HTTP/1.1" 404 0
I am trying to implement simple pagination using Django rest frame work. But I am getting Status 404 Not Found in Postman. Custom urls.py included from base urls.py from django.urls import path from item.api.views import ( api_detail_item_view, api_create_item_view, ApiBlogListView ) app_name = 'item' urlpatterns = [ path('<slug_from_api_url>', api_detail_item_view, name="item_detail_api"), path('create_api/', api_create_item_view, name="item_create_api"), path('list', ApiBlogListView.as_view(), name="list"), ] serializers.py file: from rest_framework import serializers from item.models import ItemMaint class ItemMaintSerializer(serializers.ModelSerializer): class Meta: model = ItemMaint fields = ['name', 'itemDescription', 'active', 'slug'] views.py file: class ApiBlogListView(GenericAPIView): queryset = ItemMaint.objects.all() serializer_class = ItemMaintSerializer pagination_class = PageNumberPagination Settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, } Thanks in advance. -
How to set a custom manager class parameter to required=False
I am writing an API to accept and save the user profile information. In total I want to accept 5 parameters from the user which are mentioned below. { "first_name":"", "last_name":"", "email":"", "password":"", "profile_picture":"" } Out of these 5 parameters first_name, last_name, email and password are mandatory and profile_picture is optional. In models.py I have mentioned profile_picture as an ImageField. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_picture/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defining a custom user manager class for the custom user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' In serializers.py I have mentioned profile_picture as an ImageField with required=False. serializers.py class UserSerializer(serializers.Serializer): """ This is a serializer class to validate create user request object. """ class Meta: models = 'Users' email = serializers.EmailField(allow_blank=False) first_name = serializers.CharField(max_length=255, allow_blank=False) last_name = serializers.CharField(max_length=255, allow_blank=False) profile_picture = serializers.ImageField(max_length=None, allow_empty_file=True, use_url= False, required=False) … -
django environment pyhon manage.py runserver
trying to start a project with django. I downloaded django and virtualenv package and everything went well ( I followed the installing instructions ) but, when I trued ti run in the command line : python manage.py runserver it displays an error and says that django does not exist and something about PYHONPATH. does anybody know a wat to get it installed and start a project easily? some how no matter what I do nothing works. thanks -
AttributeError: type object 'Product' has no attribute 'Objects'
from django.db import models class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name =models.CharField(max_length=60) price =models.CharField(max_length=60) category =models.CharField(max_length=60, choices=CATEGORY) description =models.CharField(max_length=100) date_created =models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name from .models import * def products(request): products = Product.Objects.all() return render(request, 'Accounts/products.html', {'Products ': products}) -
how can i implement django oscar "categories" functionality(Parent, childs) in the Django oscar RESTFUL API?
In the oscar dashboard, I can make any root category, I can make children under a category. This functionality I am able to explore in the oscar Restful API. But I want to inherit the dashboard functionality, where we can make any category relative to another category. for example- I have 2 categories. 1) cat 1 a)subcat1 2)cat 2 now if I have to make subcat1 as a child of cat2 I can easily select from the dropdown and set 'subcat1' to cat2, in the oscar dashboard. But how can I do the same using Django oscar restful API? Please let me know. I have checked and found out that "category" model uses the Materialized Path trees, to achieve this functionality, how can I use this to achieve the treebeard functionality for adding the root nodes, adding children, and updating the categories under different categories etc? this is the request data I receive from the client side. { "id": 104, "url": "http://localhost:8000/api/admin/categories/104/", "breadcrumbs": "Cat1 > subcat1", "name": "subcat1", "description": "My new one test Desc", "slug": "subcat1", "parent": "Cat1", "children": "http://localhost:8000/api/admin/categories/Cat1/subcat1/", #here parent slug will be the name of parent category this category belongs to, if it is a parent category, … -
Django: Best way to extend auth_views.LoginView to do an extra check before allowing login to pass, only for login view
I've been trying to figure out the best way to add a single if statement to the baked in contrib.auth.LoginView from Django, to check if the login process should continue. I have in urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ... url(r'^login/$', auth_views.LoginView.as_view(), name='account_login'), ... ] My task at this point is to check whether a user can log in, by checking their license, using a function that receives a License model instance: def check_license(lic_obj): file_contents = lic_obj.decrypt_license() expiry_date = file_contents['expiry_date'] expiry_date = dateutil.parser.parse(expiry_date) time_now = utc.localize(datetime.datetime.utcnow()) if expiry_date < time_now: users = User.objects.all() for user in users: user.remove_all_sessions() # If license is invalid, redirect to License page return HttpResponseRedirect(reverse('get_license')) # Otherwise, keep going with login, not sure how to go about this either, # depends on how extending LoginView works pass For clarity, a license is just an encrypted bit of JSON with some license related properties, one of which is the license's expiration date. That whole part of the code works, I'm just not sure how to have that check_license() function be run on login, before returning whether the login is successful or not. I was toying with adding a custom middleware class, but that … -
request.user.id is null in ModelViewSet
getInstructor is my repository method, which gets instructor related with user id. @action(methods=['get'], detail=False) def instructor_detail(self, request): response_data = {} instructor = InstructorRepository.getInstructor(request.user.id) response_data["data"] = {"user_id": request.user.id, "detail": instructor.get("detail")} When I test that method with an id, it works. The problem is, request.user.id is always null, even there's no login problem related with JWT based auth. What should I check? -
How to check value getting none in modelserializer
I am having one issue I am having two serializers class PetSerializer(ModelSerializer): pet = AnimalSerilaizer (read_only = True) fields = ('id', 'pet') class Meta: model = Pet class AnimalSerializer(ModelSerializer): name = SerializerMethodField() color = SerializerMethodField() category = SerializerMethodField() photo = SerializerMethodField() class Meta: model = Animal fields = ('id', 'name', 'color', 'category', 'photo') def get_name(self, animal): return '{} {}'.format(animal.first_name, animal.last_name) def get_color(self, animal): return animal.color def get_category(self, animal): return animal.category def get_photo(self, animal): return animal.photo My Issue is When I am calling Pet Serializer if there is any object I am getting values..... If there is no objects I am getting none I need to change the response the "none" in string format . -
How to provide different pages to user accounts after login (Django Project)?
I am currently working on a django web app for an email broadcast service and was wondering how I would provide the different outboxes for the different users, so I can display which messages each user has sent in their outbox.I am working with an html template by Ra-themes. -
How to search for a field in django model which is present in another model
I have a model question , submissions , users submissions has many to many relationship with users and questions So basically submissions has the following fields: questions users time score is_solved When displaying questions to the user I am also displaying whether that particular question has been solved by the user or not. So, if is_solved is true I will display "solved" I am returning all questions to my html page as well as all the submissions user has made and I'm using a loop for question in questions // check if solved // display solved // else do nothing end for My question is how do I check for submissions.solved for each question in the loop -
How to aggreagte Django data model and render them in a table
My model contains a daily campaigns data. A campaign equal to an insertion_order(variable in the models) I would like to aggregate data from my mdel (like summing columns by insertion_order. from django.db import models class TabSource(models.Model): date=models.DateField() dsp=models.CharField(max_length=30) advertiser=models.CharField(max_length=100) insertion_order=models.CharField(max_length=300) insertion_order_id models.IntegerField() strategy_name=models.CharField(max_length=300) creative_name=models.CharField(max_length=400) spent_budget=models.DecimalField(null=True, max_digits=2) impressions=models.IntegerField() clics=models.IntegerField() conversions=models.IntegerField() post_clics_conversions=models.IntegerField() post_view_conversions=models.IntegerField() def __unicode__(self): return "{} {}".format(self.dsp, self.insertion_order) -
django shell freezes when running client.get(reverse)
So I was trying to learn django and going through the tutorials when something weird happened. On the testing views part of the tutorial, I was asked to run a client in shell and I tried it but at some point my console freezes. Here is the code I've been running on the console: PS D:\Users\rrocha\OneDrive\Documents\Material de Estudo\Django\mysite> python manage.py shell Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') Not Found: / >>> response.status_code 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) The console stops responding when I run the last line. Does anyone have any idea of what I might be doing wrong? -
Gunicorn service fails to start
Gunicorn not starting Hi, I expect this is not the right subreddit for this unfortunately, but becuse it is a django application I've come here as a starting point. But for some reason, gunicorn service will not start on one of my servers. The gunicorn.service and the gunicorn.socket files are identical and in identical locations (I am building a staging server so it must be as close to the other one as possible, the other one is running fine). Can anyone see what might be the issue gunicorn.service: #!/bin/sh [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pcc Group=nginx WorkingDirectory=/home/rob/myproject ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn status: (django_env) [rob@pcc-home-page run]$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Wed 2020-03-11 12:45:25 UTC; 13s ago Process: 1466 ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application (code=exited, status=203/EXEC) Main PID: 1466 (code=exited, status=203/EXEC) Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Started gunicorn daemon. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service: main process exited, code=exited, status=203/EXEC Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Unit gunicorn.service entered failed state. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service failed. Some extra info: Server is running CentOS, Django is purely running …