Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why subclassing AppConfig is required in Django
From Django official docs, it reads: It is important to understand that a Django application is a set of code that interacts with various parts of the framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig instance for each installed application. Above means subclassing AppConfig is for maintaining metadata, which is used for configuration and also for introspection. Q1: Apart from labeling in Django Admin portal, I did not see any other use cases. any other examples for configuration and also for introspection ? Below posts did not help me out. What is the purpose of apps.py in Django 1.9? How is Django apps.py supposed to be used? -
Ajax call not working in django web application, says "Uncaught ReferenceError: ajax is not defined" [closed]
I have tried to implement a dependent dropdown menu which fetches locality based on the city selected. For some reason the ajax call does not work and is giving an error: "Uncaught ReferenceError: ajax is not defined" Javascript Code <script> $(document).ready(function(){ $('select#selectcities').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var city_name = optionSelected.text(); data = {'cnt' : city_name }; ajax('/getdetails',data,function(result){ console.log(result); $("#selectlocalities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectlocalities").append('<option>'+ result[i].name +'</option>'); }; }); }); }); </script> Python code in views.py def getdetails(request): #code for dependent drop down menu in search console city_name = request.GET['cnt'] print("ajax " + str(city_name)) result_set = [] all_cities = [] answer = str(city_name) selected_city = city.objects.get(name=answer) print("selected city name " + str(selected_city)) all_localities = selected_city.locality_set.all() for locality in all_localities: result_set.append({'name': locality.name}) print("locality name " + str(locality.name)) return HttpResponse(simplejson.dumps(result_set), content_type='application/json') -
How to set value of DateTime field automatically in Django REST Framework HTML form?
I have a very basic Django Model and use it in Django REST Framework. When using the browsable API tool and requesting an instance of a ressource, I can set the values of the different attributes using the HTML form at the bottom of the page. All attributes have their current value pre-set except for the DateTime fields. Is there a special setting required such that the form fields for DateTime entries field are prefilled with their current value? -
List loading via ajax and queryset loss
have a list, however, I want it to be called via ajax, I'll take the example, it will be more playful. HTML {%extends 'base/base.html'%} {% load static %} {%block title%}Produtos{% endblock %} {%block content%} <div class="container"> {% include 'base/msg_sucesso.html' %} {% include 'base/form_error_alert.html' %} </div> <section> <form class="form-inline" method="GET"> <div class="row"> <div class="col"> <label for="forncedores">Fornecedor</label> <select id="forncedores" name="forncedores"> <option selected>Todos</option> {% for fornecedor in todos_fornecedores %} <option value="{{ fornecedor }}">{{ fornecedor }}</option> {% endfor %} </select> </div> <div class="col"> <label for="categorias">Categoria</label> <select id="categorias" name="categorias"> <option selected>Todos</option> {% for categoria in todas_categorias %} <option value="{{ categoria }}">{{ categoria }}</option> {% endfor %} </select> </div> <div class="col"> <label for="produtos">Produto</label> <select id="produtos" name="produtos"> <option selected>Todos</option> {% for produto in todos_produtos %} <option value="{{ produto }}">{{ produto }}</option> {% endfor %} </select> </div> <div class="row"> <div class="col"> <input type="checkbox" id="fornecedor_falta" name="fornecedor_falta"> <label for="fornecedor_falta">Fornecedor em falta</label> </div> <div class="col-5"> <input type="checkbox" id="categoria_falta" name="categoria_falta"> <label for="categoria_falta">Categoria em falta</label> </div> <div class="col"> <input type="checkbox" id="produtos_falta" name="produtos_falta"> <label for="produtos_falta">Produto em falta</label> </div> </div> </div> <div class="col"> <button type="submit" class="btn btn-primary">Search</button> <a href="{{add_url}}" class="btn btn-success"><span>Novo Produto</span></a> </div> </form> <table class="table table-striped"> <thead> <tr> <th scope="col">Produto</th> <th scope="col">Quantidade</th> <th scope="col">Categoria</th> <th scope="col">Descrição</th> <th scope="col">Preço</th> <th scope="col">Fornecedor</th> <th scope="col">Disponivel</th> </tr> </thead> … -
Call Method in Model Class Based view
I have method in my model that I want to be callable in the API. model: class Booking(models.Model): PENDING = 'PN' ACCEPTED = 'AC' DENIED = 'DN' BOOKING_STATUS_CHOICES = [ (PENDING, 'Pending'), (ACCEPTED, 'Accepted'), (DENIED, 'Denied') ] createdDate = models.DateTimeField(auto_now_add=True) comments = models.CharField(max_length=120) location = models.TextField() date = models.DateTimeField() operator = models.ForeignKey("Business", on_delete=models.CASCADE) status = models.CharField(max_length=2, choices=BOOKING_STATUS_CHOICES,default=PENDING) def __str__(self): return self.comments def acceptBooking(self): self.status = self.ACCEPTED def denyBooking(self): self.status = self.DENIED serializer: class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = ('createdDate', 'comments', 'location', 'date', 'operator', 'status') views: class BookingView(viewsets.ModelViewSet): serializer_class = BookingSerializer queryset = Booking.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['createdDate', 'comments', 'location', 'date', 'operator'] I would like to call acceptBooking or denyBooking. What's the best practice for achieving this? Thanks! -
Django Forms - Form not submitting to database
I had a perfectly working 'test' form, I followed the exact same format to build a new one and it won't work. Everything is exactly as it was on my test form. view: def save_sim_data(request): if request.method == 'POST': if request.POST.get('sim_concentration_range') and request.POST.get('sim_concentration_range_2') and request.POST.get('sim_concentration_range_unit'): data=Sim() data.sim_concentration_range = request.POST.get('sim_concentration_range') data.sim_concentration_range_2 = request.POST.get('sim_concentration_range_2') data.sim_concentration_range_unit = request.POST.get('sim_concentration_range_unit') data.save() print('check1') #None of the print statements in this function are being triggered return render(request, 'App/simulation.html') else: return render(request,'App/simulation.html') print('check2') return render(request,'App/simulation.html') print('check3') model: class Sim(models.Model): sim_concentration_range = models.DecimalField(max_digits = 100, decimal_places = 5, default=1) sim_concentration_range_2 = models.DecimalField(max_digits = 100, decimal_places = 5, default=1) sim_concentration_range_unit = models.TextChoices('sim_cc_unit', 'ppm notppm') url: urlpatterns = [ path('', views.home, name='home'), path('io/simulation/', views.save_sim_data, name='save_sim_data') ] html: <form action="{% url 'App:save_sim_data' %}" method="POST" id="sim_form" name="sim_form"> {% csrf_token %} <div class="card" style="width: 35rem; position: relative; left: 300px; height: 575px;"> <div class="card-body"> <h4 style="padding-bottom: 10px;">Simulation</h4> <hr class="solid" style="border-top-width: 2px;"> <div> <label for="sim_concentration_range" style="padding-right: 9.73rem;">Concentration Range:</label> <input id="sim_concentration_range" type="text" name="sim_concentration_range" style="width: 50px; position: relative; right: 8.3rem; bottom: 1px; height: 24px;"> <label style="position: relative; left: -8.2rem; bottom: 1px;">-</label> <input id="sim_concentration_range_2" type="text" name="sim_concentration_range_p2" style="width: 50px; position: relative; left: -8rem; bottom: 1px;height: 24px;"> <select name="sim_concentration_range_unit" id="sim_concentration_range_unit" style="width: 4rem; position: relative; left: -7.5rem;"> <option value="ppm">ppm</option> <option value="none"></option> </select> … -
GenericForeignKey( TypeError: __init__() got an unexpected keyword argument 'object_id_fields'
i am buiding a blog and i want to count any users that visit my page and dispplay numbers of users that visit that page. and display content by pupolated. i am using GenericForeignKey to access the model on my hitcount package base on the decumentation of hitcount packages. after i finish creating my models and try to run my sever i got this errors below . File "F:\professional blog in django\BLOG\blog\blogapp\models.py", line 48, in Post site_visitor = GenericForeignKey( TypeError: init() got an unexpected keyword argument 'object_id_fields' is there any thing i am not doing right please help > model.py > > from django.db import models from django.contrib.auth.models import > User from datetime import datetime, date from django.db.models.fields > import related from django.urls import reverse from > django.contrib.contenttypes.fields import GenericForeignKey from > hitcount.models import HitCountMixin, HitCount > # Create your models here. from django.core.exceptions import ValidationError > class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) body = models.TextField() category = models.ForeignKey( Category, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True) image = models.ImageField(upload_to="image", validators=[image_vailid]) likes = models.ManyToManyField(User, related_name="like_post") site_visitor = GenericForeignKey( HitCountMixin, object_id_fields="object_pk", content_type_field="content_type") > def numbers_of_likes(self): > return self.likes.count() > > def __str__(self): > return self.title + '| … -
AttributeError at / in Django
I am learning Django and trying to solve this error please help me. I have used Bootstrap in it because I am learning Django and want some quick results. error: https://i.stack.imgur.com/4UHS5.png App/urls.py: from django.contrib import admin from django.urls import path from mApp import views urlpatterns = [ path("", views.index, name="index") ] Project/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('mApp.urls')) ] views.py: from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'index.html'), models.py: from django.db import models # Create your models here. class Index(models.Model): email = models.models.CharField(max_length=100), massage = models.models.TextField() Form part of HTML: <form method="post" action="/index"> {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label" >Email address</label > <input type="email" class="form-control" id="exampleInputEmail1" name="email" aria-describedby="emailHelp" required /> <div id="emailHelp" class="form-text"> We'll never share your email with anyone else. </div> </div> <div class="form-floating"> <textarea class="form-control" placeholder="Leave a message here" name="message" id="floatingTextarea" required ></textarea> <label for="floatingTextarea">Message</label> </div> <br /> <button type="submit" class="btn btn-primary">Submit</button> </form> If you want any other file, I will upload it. -
Create View unable to find success url to redirect to
I am a Django developer with a quick question. I have the following code in which I have created a model 'Plan', which has several fields and I have also created a view for it. However, when I submit the form for the create view, I get an error saying that it could not find a url to redirect to. I have tried adding the 'get_absolute_url' method to the model and I have also tried adding the 'success_url' attribute to the create view, but I always get the following error: The view work.views.PlansCreateView didn't return an HttpResponse object. It returned None instead Models.py from django.db import models from django.utils import timezone from datetime import timedelta, datetime from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse, reverse_lazy from django.shortcuts import render, redirect date = datetime.today() + timedelta(days=10) class Plan(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=300) date_created = models.DateTimeField(default=timezone.now) date_deadline = models.DateTimeField(default=date) supervisor = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.supervisor.username} {self.title}" Project Urls.py urlpatterns = [ # Core path('admin/', admin.site.urls), path('', HomeView.as_view(), name="core-home"), path('about/', AboutView.as_view(), name="core-about"), # Users path('register/', register, name="users-register"), path('login/', LoginView.as_view(template_name="users/login.html"), name="users-login"), path('logout/', LogoutView.as_view(template_name="users/logout.html"), name="users-logout"), # Work path('plans/', PlansListView.as_view(), name="work-plans"), path('<int:pk>/tasks', TasksListView.as_view(), name="work-tasks"), path('plans/create/', PlansCreateView.as_view(), name="work-plans-create") ] … -
How to send a POST request to my API endpoint
I have that view on my frontend app that takes a POST request and check if a specific room already exists, if exist then will redirect to my API endpoint. def index(request): if request.method == "POST": room = request.POST.get('room') try: room = Room.objects.get(name=room) return redirect('frontend:chat', chat_name = room) except Room.DoesNotExist: print('dont exist') return render(request, 'frontend/index.html') In my api/models.py class Room(models.Model): name = models.CharField(max_length=64, unique=True) host = models.CharField(max_length=64) def __str__(self): return self.name The serializer is just a ModelSerializer In my api/views.py class RoomView(ListCreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer How i can send a POST request to my API, create that instance and get them to redirect my user from the specific room? -
How to send id and slug in django Url?
I am trying to make django urls suitable for the seo. I want to send Id and slug in the same url.I don't want to use slug I only want to show in the url. My model looks like this: class Oyunlar(models.Model): game_id = models.AutoField(primary_key=True) title = models.CharField(max_length=10000) platform = models.CharField(max_length=10) image = models.CharField(max_length=255, blank=True, null=True) release_date = models.DateField(blank=True, null=True) click_count = models.IntegerField() categories=models.ManyToManyField(Kategoriler,through='OyunlarKategoriler') base_price=models.DecimalField(default=0,max_digits=65535, decimal_places=2) big_discount=models.BooleanField(default=False) en_ucuz = models.DecimalField(default=0,max_digits=65535, decimal_places=2) popularite = models.IntegerField(blank=True, null=True,default=0) discount_rate = models.DecimalField(max_digits=65535, decimal_places=2) title_edit = models.CharField(max_length=500, blank=True, null=True) description = models.CharField(max_length=100000, blank=True, null=True) steam_id = models.CharField(max_length=1000, blank=True, null=True) metacritic = models.FloatField(blank=True, null=True) recommendation = models.BigIntegerField(blank=True, null=True) full_game = models.BooleanField(blank=True, null=True) age = models.CharField(max_length=500, blank=True, null=True) minimum = models.CharField(max_length=10000, blank=True, null=True) recommended = models.CharField(max_length=10000, blank=True, null=True) developer = models.CharField(max_length=500, blank=True, null=True) publisher = models.CharField(max_length=500, blank=True, null=True) oyun_foto = ArrayField(models.CharField(max_length=10000, blank=True, null=True)) # This field type is a guess. windows = models.BooleanField(blank=True, null=True) mac = models.BooleanField(blank=True, null=True) linux = models.BooleanField(blank=True, null=True) class Meta: managed = False db_table = 'oyunlar' def __str__(self): return self.title Urls.py path('int:game_id/slug:slug/',views.oyun,name='detail'), views.py def oyun(request,slug,game_id): print(slug) oyun=Oyunlar.objects.get(pk=game_id) comments=Comments.objects.filter(oyunlar=oyun) game_price=GamePrice.objects.filter(game_id=game_id).order_by('price') categories = OyunlarKategoriler.objects.filter(game=oyun).values_list('category_id', flat=True) benzer = Oyunlar.objects.filter(categories__category_id__in=categories, platform=oyun.platform).order_by('-click_count').distinct()[:4] print(request.method) if request.method == 'POST': cf = CommentForm(request.POST or None) print('burda') if cf.is_valid(): print('valid') text = … -
Validating a foreign key field with non-Primary Key in a serializer django rest framework
I'm using the Django Rest framework to create an API. I have the following models: class Currency(models.Model): name = models.CharField(max_length=15) code = models.CharField(max_length=5) exchange_rate = models.DecimalField(max_digits=5, decimal_places=4) and here is the serializer for the API request- class WalletCreditSerializer(serializers.Serializer): wallet = serializers.PrimaryKeyRelatedField(queryset=Wallet.objects.all()) amount = serializers.DecimalField(max_digits=10, decimal_places=4) currency = serializers.PrimaryKeyRelatedField(queryset=Currencies.objects.all()) message = serializers.CharField(max_length=150, allow_null=True) The serializer works well when I am passing currency id in request { "wallet": 1, "amount": 23, "currency": 1, "message": "Test message" } But the requirement is the pass the Currency code { "wallet": 1, "amount": 23, "currency": "USD", "message": "Test message" } What is the best way to achieve this? Could someone provide an example? -
Why am I getting timeout error in Django Channels?
I have recently started learning Django Channels and found this very nice and detailed project: Real-Time Taxi App With Django Channels and React. However, this project uses Django Channels v2.3.1 and I have v3.0.3 so I made the changes to make it work the latest version. The code below is supposed to be working in the latest version but it doesn't. What am I doing wrong? test_websocket.py import pytest from channels.db import database_sync_to_async from channels.layers import get_channel_layer from channels.testing import WebsocketCommunicator from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import AccessToken from taxi.asgi import application TEST_CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } @database_sync_to_async def create_user(username, password): user = get_user_model().objects.create_user( username=username, password=password ) access = AccessToken.for_user(user) return user, access @pytest.mark.asyncio @pytest.mark.django_db(transaction=True) class TestWebSocket: async def test_can_connect_to_server(self, settings): settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS _, access = await create_user('test.user@example.com', 'pAssw0rd') communicator = WebsocketCommunicator(application=application, path=f'/taxi/?token={access}') connected, _ = await communicator.connect() assert connected is True await communicator.disconnect() async def test_can_send_and_receive_messagges(self, settings): settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS communicator = WebsocketCommunicator( application=application, path='/taxi/' ) connected, _ = await communicator.connect() message = { 'type': 'echo.message', 'data': 'This is a test message.' } await communicator.send_json_to(message) response = await communicator.receive_json_from() assert response == message await communicator.disconnect() async def test_can_send_and_receive_broadcast_messages(self, settings): settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS communicator … -
Fargate oneoff task keeps running
I'm having an issue with a fargate one off task , it's meant to run database migration and then stop but it keeps stuck in running status this is the task definition : resource "aws_ecs_task_definition" "migrate" { family = "${var.project_name}-${var.environment}-migrate" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] cpu = 512 memory = 1024 execution_role_arn = aws_iam_role.ecs_task_execution_role.arn task_role_arn = aws_iam_role.ecs_task_execution_role.arn container_definitions = <<DEFINITION [ { "name": "${var.project_name}-migrate", "image": "${var.repository_url}:latest", "cpu": 512, "memory": 1024, "command": [ "/bin/sh", "-c", "python manage.py migrate --no-input" ], "mountPoints": [], "environment": [ { "name": "DJANGO_SETTINGS_MODULE", "value": "****" }, { "name": "DB_HOST", "value": "****" }, { "name": "DD_API_KEY", "value": "****" } ], "secrets": [ { "name": "SECRETS", "valueFrom": "*****" } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "****", "awslogs-region": "****", "awslogs-stream-prefix": "******" } }, "volumesFrom": [] } ] DEFINITION } and this is how i call it from github actions aws ecs run-task --launch-type FARGATE --cluster cs-name --task-definition $MIGRATE_TASK_ARN --network-configuration "awsvpcConfiguration={subnets=[${{ secrets.MIGRATE_TASK_SUBNET_IDA }}, ${{ secrets.MIGRATE_TASK_SUBNET_IDB }}],securityGroups=${{ secrets.MIGRATE_TASK_SECURITY_GROUP_ID }}}" any idea what's wrong ? -
Need fo get the domain from which the user landing to my website?
I am sharing one url link in different social media platforms. I need to find from which domain the user has landed to my website page. is there any possible way for finding the base url of social media plotforms. Thanks in advance. -
python-social-auth return drf token as a parameter
I am using django rest framework's token authentication for my clients. I have also implemented social auth using python-social-auth in my project. However, once the user has logged in (or signed up) using python social auth, I want to redirect to the next url along with the drf token as a parameter. So, if I make a request like this from the frontend: localhost:8000/auth/login/github?next=localhost:3000 then the backend should redirect to the following url localhost:3000?token=USER_TOKEN_HERE the USER_TOKEN would be the drf token for the user who was created or logged in. How can this be implemented in python-social-auth? I couldn't find any good references. Thanks a lot! -
(1048, "Column 'user_id' cannot be null") with Django DRF
I wrote code to create new users via POST and DRF (Django Rest Framework) successfully and I can obtain token correctly, however when I try to POST (via DRF) to fill Profile linked to that user I get (1048, "Column 'user_id' cannot be null") This is snippets of my code: for serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ('username','email','first_name','last_name','password') def create(self, *args, **kwargs): user = super().create(*args, **kwargs) p = user.password user.set_password(p) user.save() return user def update(self, *args, **kwargs): user = super().update(*args, **kwargs) p = user.password user.set_password(p) user.save() return user class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('bio','birth_date','location','country') def create(self, *args, **kwargs): profile = super().create(*args, **kwargs) profile.save() return profile def update(self, *args, **kwargs): profile = super().update(*args, **kwargs) profile.save() return profile and for views: class ProfileViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ permission_classes = IsAuthenticated, serializer_class = ProfileSerializer queryset = Profile.objects.all() class UserViewSet(viewsets.GenericViewSet,mixins.CreateModelMixin,): """ API endpoint that allows users to be viewed or edited. """ #permission_classes= (IsAdminUser,) serializer_class = UserSerializer queryset = User.objects.all().order_by('-date_joined') and for models: @receiver(post_save, sender = settings.AUTH_USER_MODEL) def create_auth_token(sender,instance=None,created=False, **kwargs): if created: Token.objects.create(user=instance) class Country(models.Model): iso = models.CharField(max_length = 2,unique = True) name = models.CharField(max_length = 250) iso3 … -
How to have a views function be called when the respective template is loaded?
So far, on my entirely blank django project I have created a simple template that looks as following. test.html: {% block includes %} {{ mytext }} {% endblock includes %} to my views.py I added the following function: from django.template.response import TemplateResponse def testdex(requset, template_name="news.html"): args = {} text = "hello world" args['mytext'] = text return TemplateResponse(request, template_name, args) My settings.py includes the following: TEMPLATE_DIR = os.path.join(BASE_DIR, "core/templates") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] However, loading the template only shows me a blank page. Is there something I am missing? -
Validation on filed in signupform with django Alluth
i have a custom signupform created for Djangp Alluth. Everyghing works well. But i want to ad a validation to the form but i cant get the validation to work. I want a lookup on the value Pid. This value is unique so if there already is a user registrered the form validation error should pop up. Any tips or ideas? class SignupForm(SignupForm): def __init__(self, *args, **kwargs): # Call the init of the parent class super().__init__(*args, **kwargs) # Remove autofocus because it is in the wrong place self.fields[_("first_name")] = forms.CharField(required=True) self.fields[_("last_name")] = forms.CharField(required=True) self.fields[_("pid")] = SEPersonalIdentityNumberField(required=True) # Put in custom signup logic def custom_signup(self, request, user): # Set the user's type from th form reponse user.profile.pid = self.cleaned_data[_("pid")] user.first_name = self.cleaned_data[_("first_name")] user.last_name = self.cleaned_data[_("last_name")] # Save the user's type to their database record user.save() -
Custom authentication raises 400 instead of 403
I have written a custom authentication that should return 403 incase of unauthorised login (i.e. when user exists but is not allowed to login). Here is my code: def authenticate(self, request, username=None, password=None): # do something if not results: if not user.has_perm('some_permission'): raise PermissionDenied("Insufficient permission") return None In settings.py I have added this custom authentication before ModelBackend. However, I notice that 400 is returned instead of 403. How can I fix this? Thanks in advance -
Python-Django import csv to Jupiter Note local
Hi I create in Django app that export csv file, next I import this to Jupiter, everything works when my Django published on line, but cant import this when my project run local like http://127.0.0.1:8000/ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import io import requests import urllib.request as urllib2 df = pd.read_csv('http://127.0.0.1:8000/covid/covid.csv/') df.head(100) ConnectionRefusedError Traceback (most recent call last) /usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1349 h.request(req.get_method(), req.selector, req.data, headers, -> 1350 encode_chunked=req.has_header('Transfer-encoding')) 1351 except OSError as err: # timeout error 18 frames ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: URLError Traceback (most recent call last) /usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1350 encode_chunked=req.has_header('Transfer-encoding')) 1351 except OSError as err: # timeout error -> 1352 raise URLError(err) 1353 r = h.getresponse() 1354 except: URLError: <urlopen error [Errno 111] Connection refused> Any ideas? -
Django Chart with chart.js
I working on the project where I need chart. I tries to use chart.js but something went wrong. I have list of indicators with target and progress for each. I want to display this list of indicators and their corresponding target and progress. Below is the code I am using and the output. How can I modify the codes to display the full chart with bars. def chart(request): dataset = Indicators.objects.values('indicator','target','progress') indicator = list() target = list() progress = list() for entry in dataset: indicator.append(entry['indicator']) target.append(entry['target']) progress.append(entry['progress']) target_series = { 'name': 'Target', 'data': target, 'color': 'blue', } progress_series = { 'name': 'Progress', 'data': progress, 'color': 'red' } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Indicator Analysis'}, 'xAxis': {'categories': indicator}, 'series': [target_series,progress_series] } dump = json.dumps(chart) return render(request,'staff/analysis.html',{"chart":dump}) Output of the above codes -
SocialApp matching query does not exist error with an actual domain
I'm trying to add a Google Login to my Django application by using the django-allauth library. It worked fine on my localhost. However, when I try to test it with a domain, it gives SocialApp matching query does not exist error. I have tried to change the SITE_ID, also I have tried to delete the site and insert again. When I run the code below, it returns 4. from django.contrib.sites.models import Site Site.objects.get(domain='www.subdomain.mysite.com') So my SITE_ID is 4 and I have already added the site to the socialapp_sites table. How can I fix this issue? -
Django - How to handle DateTime field as primary key
I have a class with a DateTime as primary key defined class GrowEntry(models.Model): dateTime = models.DateTimeField(primary_key=True, unique=True, null=False, blank=False) airTemperature = models.FloatField(null=True, blank=True) airHumidity = models.FloatField(null=True, blank=True) def __str__(self): return "time {datetime}T:{airtemp}H:{airHumidity}".format(datetime = self.dateTime, airtemp = self.airTemperature, airHumidity = self.airHumidity) def get_absolute_url(self): return reverse('growentry_edit', kwargs={'pk': self.pk}) def get_formatted_id(self): return self.dateTime.strftime("%Y-%m-%d %H:%M:%S") It works, but in Admin I noticed I can't delete entries because the default method (or action, whatever it is) try to use the DateTime field as parameter with the long date format. To solve this I have overridden the Admin this way @admin.action(description='Delete entry') def delete_model(modeladmin, request, queryset): if not modeladmin.has_delete_permission(request): raise PermissionDenied for obj in queryset: obj.delete() class GrowEntryAdmin(admin.ModelAdmin): list_display = ['dateTime', 'airTemperature', 'airHumidity'] ordering = ['dateTime'] actions = [delete_model] but now I have two actions in the list (the default one and my custom). I think I am missing something. There is some guideline about this? How can I get rid of the default action? -
Django: Subtract the time from two datetime objects
I need to subtract two times and get the number of minutes between them to the nearest minutes. For the scheduled_time, it has become in string and im not able to convert it back to time present_time = timezone.now().time() print(present_time) //output is -> 10:36:01.847822 scheduled_time = datetime.strftime(test.scheduled_date_time, '%H:%M:%S') //output is -> 10:20:52 in string format print(scheduled_time) How do I subtract both and get the result to the nearest minutes? :(