Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GeoDjango: Filter by distance to objects from unrelated model
I'am using geodjango and django-rest-framework to set up a gis application. Now I have two Models (Shop and BusStation) which have no relation. Now I want to filter the shops based on the fact, if there is a bus station nearby. Somesting like: .../getAllShops/?city=Berlin&busstationdistance_min=3km Is there a possibility to add such a filter into my current FilterSet?? Thanks a lot for any help! :) My Models: class Shop(models.Model): name = models.CharField(max_length=254) address = models.CharField(max_length=254) city = models.CharField(max_length=254) size = models.FloatField(null=False) website = models.CharField(max_length=254) geom = models.MultiPointField(srid=4326, null=False) class BusStation(models.Model): name = models.CharField(max_length=254) geom = models.MultiPointField(srid=4326, null=False) My ViewSet: class ShopViewSet(viewsets.ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer filterset_class = ShopFilter My FilterSet: class ShopFilter(filters.FilterSet): city = filters.CharFilter(field_name="city", lookup_expr='iexact') size = filters.RangeFilter(field_name="size"); class Meta: model = Shop fields = ['name', 'city', 'size'] -
Why are users not logged in when using a customized backend in Django?
With gracious help from another member on here, I am using a customized backend that checks for two requirements to log someone in. backends.py from django.contrib.auth.backends import ModelBackend class ProfileCheckBackend(ModelBackend): def user_can_authenticate(self, user): is_active = super().user_can_authenticate(user) return is_active and getattr(user.profile, "approved", False) settings.py AUTHENTICATION_BACKENDS = [ "django_site.backends.ProfileCheckBackend", # "django.contrib.auth.backends.ModelBackend" ] This works great, but when a user tries to sign up, they need to be logged in to move to the next function: views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user_object = form.save() user_object.is_active = True user_object.save() username = form.cleaned_data.get('username') password = make_password(form.cleaned_data.get('password1')) # user = authenticate(username=username, password=password) user = form.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') # messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('sign_up_post') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def sign_up_post(request): if request.method == 'POST': ... The login function, however, does not log the user in. How can I fix this? -
'pip' is not recognized as an internal or external command (i tried adding pip to my path)
im trying to download django and i keep running into this problem C:\Users\rondo11>pip install django 'pip' is not recognized as an internal or external command, operable program or batch file. i tired adding pip to the path virable and its still not working here is my path C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Users\rondo11\AppData\Local\Microsoft\WindowsApps;;C:\Python34\Scripts what should i do? -
Is there a limitation to creating model instances in django?
Below is an implementation of a registration form. I was creating a registration form and wanted to store the form data on the database by defining a model class. APP NAME=main main/forms.py from django import forms class NameForm(forms.Form): your_name= forms.CharField(label="your_name", max_length=500) your_email= forms.EmailField(label="your_email") main/models.py from django.db import models # Create your models here. class RegisteredPeople(models.Model): your_name= models.CharField(max_length=200) your_email= models.EmailField() main/views.py from django.shortcuts import render,redirect, HttpResponse from .forms import NameForm from .models import RegisteredPeople # Create your views here. def homepage(request): if request.method=="POST": form= NameForm(request.GET) if form.is_valid(): inst=RegisteredPeople(**form.cleaned_data) inst.save() return redirect('main:homepage') else: form=NameForm() return render(request, "main/homepage.html",context={'form':form}) When I run the server and enter the fields in the homepage, the values won't get mapped to the RegisteredPeople model. But when I tried the same using the shell, it was successful. Please help -
How to create Relationship between Category and Subcategory in Django?
I created category table in Django and when i am submitting for Category are storing in my database table, but i want relation between Category and SubCategory. i want something like this- When i will submit Subcategory form then each subcategory will be store under one Category, it means a SubCategory has at leas one Category. I am doing this after creating my own Dashboard in Django, Please check my code and let me know where I am Mistaking. Here are my Models.py file for Category and Subcategory Code... from django.db import models from django.utils.text import slugify # Create your models here. class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) title=models.CharField(max_length=280) description=models.TextField() keyword=models.CharField(max_length=225) is_linkable=models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.cat_name def save(self,*args, **kwargs): self.cat_slug = slugify(self.cat_name, self.title) #unique_slugify(self, cat_slug_str) super(Category, self).save(*args, **kwargs) class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category_id = models.ForeignKey('Category', on_delete=models.CASCADE, blank=True, null=True) title=models.CharField(max_length=280) description=models.TextField() keyword=models.CharField(max_length=225) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subcat_name def save(self,*args, **kwargs): self.subcat_slug = slugify(self.subcat_name) #unique_slugify(self, cat_slug_str) super(SubCategory, self).save(*args, **kwargs) Here are my views.py File and here are functions for category and subcategory.. def add_category(request): if request.method == "POST": cat_name=request.POST['cat_name'] cat_slug=request.POST['cat_slug'] title=request.POST['title'] description=request.POST['description'] keyword=request.POST['keyword'] is_linkable=request.POST['is_linkable'] data=Category(cat_name=cat_name, cat_slug=cat_slug, title=title, description=description, keyword=keyword, is_linkable=is_linkable) data.save() … -
How to add in Django a non-nullable ForeignKey to an existing table?
I have the following models: class Parent(models.Model): name = CharField(max_length=80, ...) class Child(models.Model): name = CharField(max_length=80, ....) And I want to add a non-nullable foreign key as shown here: class Child(models.Model): name = CharField(max_length=80, ....) parent = ForeignKey(parent) Both tables already exists in the database but have no data. When running makemigrations Django asks for a default value. If I don't want to provide a default value, is it better to perform 2 migrations, the first one with null=True and then run a second one with null=False, before ingesting data in the DDBB? Thank you for your advice. -
Show curly bracket in innerhtml for jquery
I am trying to keep the curly brackets in this innerhtml to be displayed but I don't think its happening correctly so the {} around the source needs to be a part of my inner html. var htmlString = `<div class="d-flex flex-column player-card mx-1 block my-2"> <img src= "{% thumbnail rowingWebsite/rowingWebsiteApp/media/Caitlin.png 370x550 box=${ rowers[i].cropping } crop detail %}" alt=""> <div> Thank you for all your help. -
Getting error in running django hello world web server
When run server got following error. Please help Error "(test) C:\Users\91989\Projects\telusko>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\91989\Envs\test\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\91989\Envs\test\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\91989\Envs\test\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\91989\Envs\test\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\Users\91989\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\91989\Envs\test\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\91989\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\91989\Envs\test\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is … -
Selenium - assert element exists
I'm using Selenium (Django) and am wanting to ensure that before a user logs in the 'login' button is present, but after they log in it is no longer present and is replaced with a 'logout' button. I thought this would work but it doesn't: self.assertFalse(self.browser.find_element_by_link_text('Register')) So my question is, how can I use an assert to determine if an element exists on the page please? Thank you. -
i am getting this application error in my heroku server on my new application , is there any way to solve
enter image description here2020-05-09T17:18:43.014428+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/home/" host=ankitcovid19.herokuapp.com request_id=210ac699-321f-4b7f-a2e5-7fa842a392c7 fwd="111.125.205.170" dyno= connect= service= status=503 bytes= protocol=https 2020-05-09T17:21:43.864581+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/home/" host=ankitcovid19.herokuapp.com request_id=488e1912-8818-4060-a36a-c0e75b8b6a19 fwd="111.125.205.170" dyno= connect= service= status=503 bytes= protocol=https 2020-05-09T17:21:56.506265+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/home/" host=ankitcovid19.herokuapp.com request_id=027c3180-31eb-428c-bd59-50fd8057c83d fwd="111.125.205.170" dyno= connect= service= status=503 bytes= protocol=https 2020-05-09T17:29:11.676731+00:00 heroku[web.1]: State changed from crashed to starting 2020-05-09T17:29:21.048127+00:00 app[web.1]: [2020-05-09 17:29:21 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-05-09T17:29:21.048716+00:00 app[web.1]: [2020-05-09 17:29:21 +0000] [4] [INFO] Listening at: http://0.0.0.0:51772 (4) 2020-05-09T17:29:21.048804+00:00 app[web.1]: [2020-05-09 17:29:21 +0000] [4] [INFO] Using worker: sync 2020-05-09T17:29:21.052964+00:00 app[web.1]: [2020-05-09 17:29:21 +0000] [10] [INFO] Booting worker with pid: 10 2020-05-09T17:29:21.119366+00:00 app[web.1]: [2020-05-09 17:29:21 +0000] [11] [INFO] Booting worker with pid: 11 2020-05-09T17:29:21.748486+00:00 heroku[web.1]: State changed from starting to up 2020-05-09T17:29:22.474646+00:00 heroku[web.1]: State changed from up to crashedenter image description here -
How to solve the problem of broken styles in a django project?
I have a problem with my django project. When I write my function to make my home page appear in views.py it comes normally but the styles are broken and it's very weird. Please help me. -
I have retrieve followers of certain user using django rest api but can you help me retrieve following list from certain user?
class User_Profile(models.Model): userprofilename = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='user_p') image_url = models.ImageField(upload_to=upload_location,null=True,blank=True) date_published = models.DateTimeField(auto_now=True,verbose_name="date published") date_updated =models.DateTimeField(auto_now=True,verbose_name="date updated") profile_slug = models.SlugField(blank=True,unique=False) followers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name = 'is_following',blank=True,null=True) # user.followers.all() Followers list of certain user -
Django Azure AD get user info
I am currently using django-azure-ad-auth package for user authentication purpose. I wanted to retrieve user information too like displayName etc, How do I go about implementing this? -
Not able to link the the Template in Django
Urls.py - company Details ** `from django.urls import path > > > from . import views > > urlpatterns = [ > path('', views.contact, name='contact'), > ] ** urls.py - S3 (main Project) ** from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('traveller.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('companydetails', include('companydetails.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** views.py -company Details ** from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('traveller.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('companydetails', include('companydetails.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** Screenshot of the file structure -
Django, ho to reuse variable results get in a views in another one?
I have the following question for you. I want to know the best and elegant way to reuse some variable results obtained in a view in another one. I'm trying to explain me better with an example. I'have 2 differente app, app A and app B. In app A views.py I have a lot of code to process data from the models with a creation of a lot of new variables. Now, in app B I have the necessity to reuse some variables obtained in views.py app A, but I wonna write again the same code to get them. Is there a way to achive my goal? Here an extract of my views.py in app A: app A/views.py def iva(request): defaults = list(0 for m in range(13)) #IVA A DEBITO iva_debito = dict() for year, month, totale in(Ricavi.objects.values_list( 'data_contabile__year', 'data_contabile__month'). annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('ricavo')*(F('iva'))), output_field=FloatField())).values_list('data_contabile__year', 'data_contabile__month', 'totale')): if id not in iva_debito.keys(): iva_debito[id]=list(defaults) index=month iva_debito[id][index]=totale iva_debito_totale={'IVA a Debito Totale': [sum(t) for t in zip(*iva_debito.values())],} # iva_debito_totale['IVA a Debito Totale'][0]=float('1') #IVA A CREDITO // MATERIALE iva_credito_materiale = dict() iva_credito_materiale_totale=dict() for year, month, totale in(Materiale.objects.values_list( 'data_contabile__year', 'data_contabile__month'). annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')*(F('iva'))), output_field=FloatField())).values_list('data_contabile__year', 'data_contabile__month', 'totale')) : if id not in iva_credito_materiale.keys(): iva_credito_materiale[id]=list(defaults) index=month iva_credito_materiale[id][index]=totale iva_credito_materiale_totale={'IVA … -
django-smart-selects not working properly
I want to have chained foreign key in my django-admin and thus I am using django-smart-selects. I have followed the documentation properly Install django-smart-selects Add it in installed_apps in settings.py Add this line in my base urls.py url(r'^chaining/', include('smart_selects.urls')), changed my model accordingly: class AddressModel(BaseModel): country = models.ForeignKey(CountryModel, null=True, blank=True, on_delete=models.PROTECT) state = ChainedForeignKey(StateModel, chained_field=country, chained_model_field=country, null=True, blank=True, on_delete=models.PROTECT) city = models.CharField(max_length=200, null=True, blank=True) and added this to my setting.py JQUERY_URL = True But everytime I try to create an address from admin, I get this error:- if path.startswith(('http://', 'https://', '/')): AttributeError: 'bool' object has no attribute 'startswith' How to solve this? -
List all Users of ManytoManyField in Django
I have three model classes: 1. Pupils class Pupils(models.Model): Name = models.CharField(max_length = 25) Surname = models.CharField(max_length = 25) ... def __str__(self): return self.Name + self.Surname Courses: in this class I add a pupil to a specific course. class Courses(models.Model): Course_pupils = models.ManyToManyField(Pupils) CourseID = models.Autofield(primary_key = True) ... Course visits: in this class I want to see what students are in a specific course class CourseVisits(models.Model) Course_visit_ID = models.AutoField(primary_key = True) course_ID = models.ForeignKey(Courses, default = 1, verbose_name = 'CourseID', on_delete = models.SET_DEFAULT) In my CoursesAdmin I could easily write filter_horizontal = (...) to show and add pupils to Courses class. But in CourseVisits class I want just to show the attendants(pupils) that are in the courses I added. I currently don't know how to do it. Does anybody know a way? -
How to use or inherit 2 models classes fields in one model class in Django Model?
I have created 2 different model classes, I want to use both models fields in a specific model. user_types = (("Agent", "Agent"), ("Branch", "Branch"), ("Company", "Company")) class CommonModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True ordering = ['-created_at', '-updated_at'] class PersonType(models.Model): user_type = models.CharField(max_length=100, choices=user_types, blank=False) class UserData(CommonModel, PersonType): user = models.ForeignKey(User, on_delete=models.CASCADE) But I am getting an error when I am trying to access admin models page http://127.0.0.1:8000/admin/mysite/userdata/ Internal Server Error: /admin/mysite/userdata/ Traceback (most recent call last): File "/home/shiv/.local/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column mysite_userdata.created_at does not exist LINE 1: ..., "mysite_userdata"."usertype_ptr_id", "mysit... ^ The above exception was the direct cause of the following exception: How can I fix it? -
Problem including a javascript game inside a django template
I have a django server (which is for my personal/local use only) and I am trying to include an interactive game in it (again, for my personal use, not for deployment). I have found this open-source game: https://github.com/MattSkala/html5-bombergirl.git which I found very nice. I can make this game run from a simple html page but when I tried to make it run inside a django template, it won't work. Here is the html code that works i.e. from which the game launches in my web browser: <!doctype html> <html> <head> <script type="text/javascript" src="bower_components/EaselJS/lib/easeljs-0.8.1.min.js"></script> <script type="text/javascript" src="bower_components/PreloadJS/lib/preloadjs-0.6.1.min.js"></script> <script type="text/javascript" src="js/core.js"></script> <script type="text/javascript" src="js/Utils.js"></script> <script type="text/javascript" src="js/Entity.js"></script> <script type="text/javascript" src="js/Player.js"></script> <script type="text/javascript" src="js/Bot.js"></script> <script type="text/javascript" src="js/Bonus.js"></script> <script type="text/javascript" src="js/Tile.js"></script> <script type="text/javascript" src="js/Fire.js"></script> <script type="text/javascript" src="js/Bomb.js"></script> <script type="text/javascript" src="js/Menu.js"></script> <script type="text/javascript" src="js/InputEngine.js"></script> <script type="text/javascript" src="js/GameEngine.js"></script> <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/docs/assets/css/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> </head> <canvas id="canvas" width="545" height="416"></canvas> <script> gGameEngine = new GameEngine(); gGameEngine.load(); </script> </html> In django, I have updated and loaded all the necessary (js, css, bower_components) static files. Here is my django views.py: def game(request): return render(request, 'game.html') and my template game.html: {% extends "base.html" %} {% block content %} <canvas id="canvas" width="545" height="416"></canvas> <script> gGameEngine = new … -
Queryset get empty values in query
I want to show the information of the actors I have chosen, but on the list page, it shows all the actors' information. How can I filter only the actors I choose? I have written the code as follows : my view.py class LiveListView(LoginRequiredMixin, ListView): model = Live def get_queryset(self): try: self.date = isodate.parse_date( self.kwargs.get("date", now().date().isoformat()) ) except isodate.ISO8601Error: self.date = now().date() qs = super().get_queryset() return qs.filter(date=self.date, slug=self.kwargs["actor_slug"]) And I checked on the webpage It doesn't show the list of actors. How should I filter? And I checked on the terminal on my computer by : print(self.kwargs["actor_slug"]) It shows the name of the actor that I chose correctly. But when I tried print(qs.filter(date=self.date, slug=self.kwargs["actor_slug"])) It doesn't show any information. It shows --> QuerySet [] What should I do? Please help me T-T -
Why serializer fields return blank?
I was able to get the fields before enabling author but now i can't get them.They all return blank but id and author returns fine. class ArticleCreateSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Post fields = ('id','author','caption','details') def create(self, validated_data): author=self.context['request'].user.profile article = Post.objects.create(author=author,**validated_data) return article Returning data: { "id": "3677676c-f155-494f-9926-8cdb68765a2c", "author": { "first_name": "John", "last_name": "Smith", "phone_number": "0123", "gender": "M", "birth_date": "1964-04-12" }, "caption": "", "details": "" } Did i do a mistake in the codes or so? -
page_size_query_param is throwing error when giving custom pagesize in DRF PageNumberPagination
I have defined custom pagination as follows class CustomPagination(PageNumberPagination): page_size_query_param='size' max_page_size = 100 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'page_size': self.page_size, 'results': data }) And in the views I imported this pagination class as follows class LeadViewSet(generics.ListCreateAPIView): def get_queryset(self): user = self.request.user customer = get_customer_for_client_user(user) myDict = dict(self.request.query_params) ---- # some code ---- return queryset pagination_class = CustomPagination serializer_class = LeadsSerializer permission_classes = [permissions.IsAuthenticated] And my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'lead.pagination.CustomPagination', 'PAGE_SIZE': 10 } My query is as follows http://127.0.0.1:8000/leads/?size=5 "Authorization: Bearer xxxxx" But Im getting error FieldError at /leads/ Cannot resolve keyword 'size' into field. Choices are: Call_Optout, Company_Name, Date, Description, Email,etc ... -
get hold on button id in javascript
in my html document that using django-template and jinja2 I'm using many holds on buttons like this: {% for item in mylist%} <button class="button-hold fill" id="{{item.id}}" value="{{item.id}}"> <ul> <li>Delete</li> <li>Sure?</li> <li>Done!</li> </ul> </button> {% endfor %} and in my js script I want to send held button id to some URL: let duration = 2100, success = button => { //Success function button.classList.add('success'); window.location.href = "/somewhere/{id}"; // here i need held button id }; document.querySelectorAll('.button-hold').forEach(button => { button.style.setProperty('--duration', duration + 'ms'); ['mousedown', 'touchstart', 'keypress'].forEach(e => { button.addEventListener(e, ev => { if(e != 'keypress' || (e == 'keypress' && ev.which == 32 && !button.classList.contains('process'))) { button.classList.add('process'); button.timeout = setTimeout(success, duration, button); } }); }); ['mouseup', 'mouseout', 'touchend', 'keyup'].forEach(e => { button.addEventListener(e, ev => { if(e != 'keyup' || (e == 'keyup' && ev.which == 32)) { button.classList.remove('process'); clearTimeout(button.timeout); } }, false); }); }); how can I find which button held? -
How to get django to serve on https (443) on docker on AWS?
I have my Django backend hosted on an ec2 server. I only use it for the REST API. The frontend is in React and it is hosted already with an https certificate on Netlify. When I did this, all API calls failed because of this error: In Django Log: You're accessing the development server over HTTPS, but it only supports HTTP. I tried this, this, and this tutorial. My files look like this. docker-compose.prod.yml version: '3' services: db: image: postgres environment: - POSTGRES_PASSWORD=postgres web: build: context: . dockerfile: Dockerfile.dockerfile command: bash -c "python -m pip install -r requirements.txt && python -m pip install -r requirements_ml.txt && python -m spacy download en_core_web_sm && apt-get update && python manage.py makemigrations && python manage.py migrate && gunicorn djserver.wsgi:application --bind 0.0.0.0:8000" volumes: - static_volume:/code/static expose: - 8000 depends_on: - db env_file: - ./.env.prod nginx: build: ./nginx volumes: - static_volume:/code/static - ./data/nginx:/etc/nginx/conf.d - ./data/certbot/conf:/etc/letsencrypt - ./data/certbot/www:/var/www/certbot ports: - "1337:80" - "443:443" depends_on: - web command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\"'" certbot: image: certbot/certbot volumes: - ./data/certbot/conf:/etc/letsencrypt - ./data/certbot/www:/var/www/certbot entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h … -
Running output of Python in html in Djngo
I am working on a django project. In the app's views.py I am having some outputs that I am storing in a dictionary. The views.py looks like this: from django.shortcuts import render def allblogs(request): a = request.GET['a'] b = request.GET['b'] return render(request, 'blog/allblogs.html', {'a': a, 'b':b}) I am calling these a and b in the html file. When I am just showing them without any html code like this: here are your {{a}} and {{b}} then I am getting them in the boring white page. However, when I am trying to call them in a html code, I am getting nothing. If I try to run them like this: {% a %} this gives me error: TemplateSyntaxError at /blog/ Invalid block tag on line 98: 'a'. Did you forget to register or load this tag? Request Method: GET Request URL: http://localhost:8000/blog/?the_sender=&the_amount= Django Version: 3.0.6 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 98: 'a'. Did you forget to register or load this tag? Exception Location: C:\Users\Winter\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py in invalid_block_tag, line 530 Python Executable: C:\Users\Winter\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\Winter\\Desktop\\portfolio-project', 'C:\\Users\\Winter\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Winter\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Winter\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Winter\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Winter\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] Server time: Mon, 11 May 2020 09:25:36 +0000 Can anyone help me?