Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to keep loop runnning while user gets redirected back to form after making a post request to start the loop
I have a django app with a view that handles a post request from a user to start an infinite loop. The problem is after succesful post request loop starts and the browser keeps loading waiting for response from the server resulting to timeouts from proxy server handling this request. Is there anyway to start the loop and keep it running while redirecting or giving back response to the browser to prevent timeouts view code below: def ticket_miner(request): mining_urls = credentials.mining_urls if request.method == 'GET': form = forms.UpdateForm() return render(request, 'tickets/mine.html', {'form': form}) else: net_test = network_acess.network_test(urlpaths.net_urls) while net_test: with requests.session() as s: try: print('logging in ....') s.post(login_url, data=payload, headers=headers, timeout=5) r = s.get(success_url, timeout=5) print(r) if r.status_code == 200: print('Logged in successfully') while r: count = 0 for mining_url in mining_urls: r2 = s.get(mining_url, timeout=5) count += 1 response_result = r2 if response_result.status_code == 404: print('TICKET NOT FOUND!') pass else: new_data = response_result.json() miner.ticket_mapper(new_data) print('mining') continue print('mining successfull restarting ...') else: print('Unable to authenticate... redirect detected') except requests.exceptions.ConnectionError as e: print(f'ConnectionError: {e.response} response. No internet connections!!') except requests.exceptions.InvalidURL as e: print(f'InvalidURL: {e.response} response. Incorrect url specified!!') except requests.exceptions.Timeout as e: print(f'ConnectTimeout: {e.response} response. Network interrupt') except requests.exceptions.RequestException as e: … -
Django automated email sending
I am building a multivendor market place using django and I have to send automated emails for two reasons. I have to verify their email each time someone signs up (A verification email will automatically be sent when they completed their form). Automated email is sent to the user when order is ordered. All the above worked fine when I test them, but I used my gmail account for that purpose. I have read that gmail is not the perfect choice for business purposes. Plus there is no online payment system in my country for payed services and all the free options I see can only send very limited emails per day. So should I continue using gmail? Or is there any other system I can use? Thank you in advance! -
How can I utilize the JWT for authintication and authorization in Django
I started learning Django two weeks ago, while I was searching for authentication and authorization in Django I found the following lines for Jason Web Tokens (JWT): project urls.py from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/cookie-stand/", include("cookie_stands.urls")), path("api-auth/", include("rest_framework.urls")), path( "api/token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair", ), path( "api/token/refresh", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), ] app permission.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True if obj.owner is None: return True return obj.owner == request.user My question is: Tokens are usually sent as a header with the request, how does Django do that? I mean for example, how can I use Django and JWT to make an authorized group of users? -
Correct way to define the initial value of a form field in Django from a database, when database values may change
I am trying to create an interview feedback capture app using Django. The interview feedbacks follow a template. The template would evolve with time. Therefore whenever a new interview feedback template is available, it is updated to the database by an admin user. Whenever an interviewer opens the app, he should see the latest value of the template available in the database as the initial value of the feedback form. Currently I am able to provide the initial value of the feedback field using the 'initial' argument of the feedback field. Below is the code: from django import forms from .models import R1 from .model_templates import template_R1 from ckeditor.widgets import CKEditorWidget class R1Form(forms.ModelForm): interview_date = forms.DateField(widget = DateInput()) feedback = forms.CharField(widget = CKEditorWidget(), initial = template_R1.objects.all().last().template) class Meta: model = R1 fields = ['interview_date', 'interviewers', 'comment', 'recommended_level', 'progress'] The problem with this approach if that if the template is updated the form field still shows an earlier snapshot of the template when the django server was started. Is there any other way the form field would show dynamic values as soon as the template is updated in the database? -
Translation Memory TM (Computer assisted translation system ) CAT Tools
Can anyone help me how to code a translation memory (TM) using language python Django as I am going to build a web-based Computer assisted translation system (CAT) everything else is done only only thing remains.? Or suggest me any GitHub repository. -
Django AssertionError when testing Create View
I'm running some tests for my app 'ads', but when I try to test the CreateView it fails with the following message: AssertionError: 'just a test' != 'New title' Here's the test: class AdTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='test_user', email='test@email.com', password='secret' ) self.ad = Ad.objects.create( title='just a test', text='Ehy', owner=self.user ) def test_ad_create_view(self): response = self.client.post(reverse('ads:ad_create'), { 'title': 'New title', 'text': 'New text', 'owner': self.user.id, }) self.assertEqual(response.status_code, 302) self.assertEqual(Ad.objects.last().title, 'New title') self.assertEqual(Ad.objects.last().text, 'New text') So it could be that the test fails in creating a new ad, and then it compares the fields with the first ad in the setUp method. I upload the rest of the code if it can help: urls.py from django.urls import path, reverse_lazy from . import views app_name='ads' urlpatterns = [ path('', views.AdListView.as_view(), name='all'), path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'), path('ad/create', views.AdCreateView.as_view(success_url=reverse_lazy('ads:all')), name='ad_create'), ... ] models.py class Ad(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() """We use AUTH_USER_MODEL (which has a default value if it is not specified in settings.py) to create a Foreign Key relationship between the Ad model and a django built-in User model""" owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) comments = … -
why TemplateDoesNotExist at / index.html
i cant findout my problem this is views.py file from django.http import HttpResponse from django.shortcuts import render def aboutUs(request): return HttpResponse('hello BD') def homePage(request): return render(request,"index.html") this is urls.py """wscubetech_firstproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from wscubetech_firstproject import views urlpatterns = [ path('admin/', admin.site.urls), path('about-us/',views.aboutUs), path('',views.homePage), ] this is settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,"templates"], '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', ], }, }, ] The error messagr is: TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.2 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Python310\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\Users\Asus\Desktop\31-5-22 Django\wscubetech_firstproject', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Sat, 04 … -
CSS not applying to image in django
I am trying to create a django app in which i have inserted an image. But css rule is not applying on the image. Image is inside a div which is inside a section html file code: <!DOCTYPE html> {% load static %} <html lang="en"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <meta charset="UTF-8"> <title>Venkatesh Akhouri</title> </head> <body> <div class="conatiner"> <nav class="navbar navbar-expand-sm navbar-light"> <a class="nav-item nav-link" href="#">Home</a> <a class="nav-item nav-link" href="#">Contact</a> <a class="nav-item nav-link" href="#">Skills</a> <a class="nav-item nav-link" href="#">Projects</a> </nav> </div> <section id="small-info"> <div class="row"> <div class="col-md"> <img class="my-img" src="{% static 'images/myImg2.jpg' %}" alt="no img"> </div> <div class="col-md"> <h3> some info</h3> </div> </div> </section> CSS: body { background-color: #cce6ff; } .nav-item { font-family: font-family: Helvetica, sans-serif; color: black; } .col-md { float: left; width 50%; } #small-info .col-md { width: 10px; border-radius: 50px; } I know there is some foolish mistake here, but i am not able to identify. I've also tried w/o any div but still not working. -
Django POST requests from Postman forbidden after HEROKU DEPLOYMENT
I uploaded my Django REST Framwork project to Heroku after following the steps carefully. https://www.youtube.com/watch?v=TFFtDLZnbSs&t=193s&ab_channel=DennisIvy In my project, I used BEARER tokens with jwt. My database is PostgreSQL which is provided by Heroku. It worked perfect while working locally but after deployment, I couldn't send requests through Postman. Any ideas? 2022-06-04T16:36:50.456061+00:00 heroku[router]: at=info method=POST path="/api/login" host=roy-messenger.herokuapp.com request_id=******-****-****-****-********** fwd="**.***.***.**" dyno=web.1 connect=0ms service=46ms status=403 bytes=3660 protocol=https 2022-06-04T16:36:50.458497+00:00 app[web.1]: Forbidden (Referer checking failed - no Referer.): /api/login 2022-06-04T16:36:50.459018+00:00 app[web.1]: 10.1.10.154 - - [04/Jun/2022:16:36:50 +0000] "POST /api/login HTTP/1.1" 403 3372 "-" "PostmanRuntime/7.29.0" . settings.py """ Django settings for abra project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path from datetime import timedelta import os import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['roy-messenger.herokuapp.com', '127.0.0.1'] CSRF_TRUSTED_ORIGINS = ['roy-messenger.herokuapp.com'] # Application definition … -
Filter Categories from list of Products in Django templates
So I'm working on this Django e-commerce website where I'm supposed to filter the products on my page based on three separate categories. Since there were only three fixed categories, I decided to create a dictionary in my model class for Products and thought there would be a way to filter products later on in my templates accordingly using a {%For%} loop. It's not working as I expected tho and I'm getting errors, probably because I'm not that familiar with Django and don't know how to get my way around it. Would greatly appreciate the help! (I've attached some screenshots for context) MODELS.products screenshot working implementation of for loop that directly shows all products Views.catalogue -
How to render a value of a single variable to a template using Django?
I am building a web application where the completion of the project (status) is returned to the client(user) through a dynamic URL. The view looks something like this:1 I want to retrieve the single value from phase field (phase field stores integer values from 1 to 10) and perform percentage = (phase / 10) * 100. How can I render the query phase and render percentage variable which stores the percentage, to template? Here's my model.py: from cmath import phase from pyexpat import model from django.db import models from sqlalchemy import delete class Project(models.Model): STATUS = ( ('Inititated', 'Inititated'), ('Paused', 'Paused'), ('In progress', 'In progress'), ('Aborted', 'Aborted'), ('Completed', 'Completed') ) PHASE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10') ) p_id = models.IntegerField(null=True) p_name = models.CharField(max_length=100, null=True) c_name = models.CharField(max_length=100, null=True) c_mail = models.CharField(max_length=100, null=True) init_date = models.DateField(null=True) ect = models.DateField(null=True) status = models.CharField(max_length=200,null=True, choices=STATUS) collabs = models.IntegerField(null=True) phase = models.CharField(max_length=100,null=True, choices=PHASE) def __str__(self): return self.p_name views.py: from cmath import phase from multiprocessing import context import re from unicodedata import name from django.shortcuts import render from django.http import HttpResponse from .models import Project from django.shortcuts import … -
Form not submitting to correct url in django
Im making a web app in django and im having a problem with a form which isnt submitting to the correct place searcc.html <form method='POST', action='/saveApply'"> {% csrf_token %} <div class="JobSub"> <input value="{{user.id}}" name="usrid"> <input value="{{comp.id}}" name="compid"> <button type="submit">Submit</button> </div> </form> views.py def saveApply(request): current_user = request.user if request.method == 'POST': # Foreign key to User is just the username savedApply.objects.create( user = request.POST.get('usrid'), company = request.POST.get('company') ) return render('main/profile.html') # Change later return redirect('login') The confusing thing is, when I press on the submit button Im not even getting sent to the login view. I am getting sent to the home page. I think the problem has something to do with the fact that this html page is getting included in another. main.html {% include 'main/search.html' %} {% endblock %} Main.html is also inheriting from another file -
Why can't i display my foreign key instance in Django?
I'm having trouble in viewing items from a list using foreign key. I have no problems with other models, but this one seems tricky. I'm not getting something I guess... The assignement is about creating a rental place that rents movies, books and music cd's. I've created a model for Cd's and hooked a model called "songs" to it with a foreign key. Here's the code: Models: class Cd(models.Model): cd_band=models.CharField(max_length=100) cd_title=models.CharField(max_length=100) CD_GENRE= ( ('POP', "POP"), ("HIP", "Hip-Hop"), ("ROC", "Rock"), ("BLU", "Blues"), ("SOU", "Soul"), ("COU", "Country"), ("JAZ", "Jazz"), ("CLA", "Classical music"), ) cd_genre=models.CharField(max_length=3, choices=CD_GENRE) cd_length=models.DurationField() cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1) class Songs(models.Model): song=models.CharField(max_length=50) song_duration=models.CharField(max_length=10, default='') list_number=models.ForeignKey(Cd, on_delete=models.CASCADE, related_name='song_name') def __str__(self): return "{} {}".format(self.song, self.song_duration) template: {% block content2 %} {%for songs in object_list%} <div class="song-entry"> <h3>{{object.song_name}}</h3> </div> {% endfor %} {% endblock content2 %} -
Django Query Annotation Does Not Support math.tan() Calculation
I have a django 3.2/mysql website. One of the tables, Flights, has two columns, angle and baseline. These two columns are combined in a view to display the value altitude using the formula altitude = baseline * tan(angle). I am building a search form for this table, and the user wants to search for flights using a minimum altitude and a maximum altitude. My normal approach to the problem is to gather the inputs from the search form, create appropriate Q statements, and use query the table with filters based on the Q statements. However, since there is no altitude field, I have to annotate the query with the altitude value for the altitude Q statement to work. It seems that a query annotation cannot use an expression like math.tan(field_name). For example, Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * math.tan(F("angle"))), output_field = models.FloatField(),),) generates the error builtins.TypeError: must be real number, not F whereas the expression Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * F("angle")), output_field = models.FloatField(),),) does not generate an error, but also does not provide the correct value. Is there a way to annotate a query on the Flights table with the altitude value so I can add a filter like Q(altitude__gte= min_altitude) to the query? Or, is … -
How to customize AdminPanel of django rest such as admin can see full details of Model having one to many relationship?
I want to allow the admin to see the full detail of BusinessAccountModel and can edit the is_approve field as Approved, pending, Not Selected. But the problem is that BusinessAccountModel has one to many relationships with WorkSamplesModel. WorkSamplesModel has images. How to display BusinessAccountModel and its WorkSamplesModel details in AdminPanel together on single page. class BusinessAccountModel(models.Model): business_title = models.CharField(max_length=70) business_description = models.CharField(max_length=500) status = models.CharField(max_length=100) note = models.CharField(max_length=200) is_approved = models.CharField(max_length=15, choices=IS_APPROVE_CHOICES,default='Pending') user = models.OneToOneField(UserModel,on_delete=models.CASCADE) class Meta: db_table = 'wp_business_acc' class WorkSamplesModel(models.Model): work_sample_image = models.ImageField(blank=True,null=True,upload_to="work_samples") work_sample_description = models.CharField(max_length=1000) is_business_card_image = models.BooleanField(default=False) business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'work_samples' I try the following code from django.contrib import admin from .models import BusinessAccountModel class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id','business_title','business_description','status','note','is_approved'] list_editable = ('is_approved',) list_per_page = 4 search_fields = ('business_title',) list_filter = ('is_approved',) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) How to customize AdminPanel as admin can see BusinessAccountModel full details and its WorkSampleModel can change is_approve field of BisinessAccountModel? -
How to let <input type='date'>, display as yyyy.mm.dd? [duplicate]
For example: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date with value={% now 'Y-m-d' %}, it displays as 04/06/2022 would it be possible for the date-picker to display as 2022.06.04? Thanks! -
Reciveing an error while downloading a package gunicorn
ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'C:\Python310\Scripts\gunicorn.exe' -> 'C:\Python310\Scripts\gunicorn.exe.deletem -
how do make a query for this issue ? in django
I'm having a 2 models Zone and DailyTask So I want to make a table in the front end(HTML) that like image is shown below. U is used_tasks UN is unused_tasks T total_tasks I want list this data for each zones for the currusponding timeslots this is my current code model one Zone class DailyTask(models.Model): date = models.DateField() zone = models.ForeignKey(Zone, on_delete=models.SET_NULL, null=True) slot = models.ForeignKey(GeneralTimeSlot,related_name='daily_task', on_delete=models.CASCADE) total_tasks = models.IntegerField(default=0) used_tasks = models.IntegerField(default=0) unused_tasks = models.IntegerField(default=0) available_driver_slots = models.ManyToManyField(DriverTimeSlot) model two Zone class Zone(models.Model): name = models.CharField(max_length=200) coordinates = models.TextField(null=True, blank=True) time slot view.py def get(self, request, *args, **kwargs): zones = Zone.objects.all() today = datetime.date.today() daily_task = DailyTask.objects.filter(date="2022-06-04") return render(request, self.template_name, {'zones': zones, 'daily_tasks': daily_task}) template timeslotreport.html {% extends 'macro-admin/base.html' %} {% load crispy_forms_tags %} {% block title %} <title>Time Slot Report</title> {% endblock %} {% block content %} <style type="text/css"> table { border-collapse: collapse; width: 100%; } td, th { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } .button1 button{ border: 2px solid #3783b5; border-radius: 5px; padding: 5px 15px; margin: 2px 0; background-color: white; width: 80px; } .under{ text-decoration:underline; } .order2 .card-title{ font-size: 25px!important; } .order2 button{ float: right; padding: 10px 80px!important; } .marg{ padding-top: 50px; } … -
How to rank query results when using Q objects in Django
I am building an jobs database using Django. The user should be able to search for an jobs using its title,and its company, etc. I am currently using Q Objects to construct the query: if keyword: q=Q() qs = stemming(keyword) for key in qs: q &= Q(title__iregex = r'\b{}.*\b'.format(key))|Q(company__iregex=r'\b{}.*\b'.format(key)) jobs_list = jobs_list.filter(q).distinct() jobs_count = jobs_list.count() jobs_list = jobs_list.order_by('-title') I would like to order the results by relevance. As far as I understand this is usually accomplished by using annotate(): A ranking number is set and then used by order_by(). However, I am not sure how to do this when using Q objects. Is it possible to "annotate" Q objects? Or am I barking up the wrong tree here? Maybe someone can help, Thank you.. -
Django filter tasks done in project ListView
I have ListView of projects that has tasks i want to calculate progress % of each project i have made it like this code bellow but the progress calculate all tasks even that is not related to project haw can i do it for the tasks that is related to the project Preview image class ClientProjectView(LoginRequiredMixin, SuccessMessageMixin, ListView): model = Project template_name = 'project/list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['tasks'] = Task.objects.all() if Task.objects.exists(): task_done = Task.objects.filter(is_done='3', project_id__in=self.object_list).count()* 100 / Task.objects.filter(project_id__in=self.object_list).count() context['percentage_done'] = task_done else: context['percentage_done'] = '0' return context -
Two foreign key's : how to select one foreign key data that has relation to another foreign key
I've two tables User and Shop.Then I've create third table which has username_id(from table User) and shopname_id(from table shop) as foreign keys.When I search a shopname_id it should display a table in front-end that has username_id that(that is the username_id has access to that particular shop)relates with searched shopname_id( data fetch from third user-shop-mapping table) How to write it's queryset in view. -
View and CSS are not updated on mobile after I modify an element classlist with javascript
So for some context, I have a portfolio page with some projects which I can filter by tags. The CSS (color) of the tags change when it's selected/deselected, by adding/removing a selected class to the element. But somehow a selected tag doesn't go back to it's initial state when it's clicked a second time, even though the class list is correctly updated. This happens only on mobile (I could test on Android and iOS), the behavior is the one expected on desktop. The page is rendered with Django, and the HTML and JavaScript look like this: {% extends './base.html' %} {% load static %} {% block title %}Pierre Bonneau - Portfolio{% endblock title %} {% block content %} <main class="container flex-shrink-0"> <!-- TAGS --> <div class="tag-list text-center"> <ul> <li class="project-tag selected" data-filter="All">All</li> {% for tag in tags %} <li class="project-tag" data-filter="{{tag.name}}">{{tag.name}}</li> {%endfor%} </ul> </div> <!-- GALERY --> <div class="project-grid"> {% for project in project_list %} <div class="project-card" data-tags="{%for tag in project.tags.all%}{{tag.name}}, {%endfor%}"> <img src="{{ project.thumbnail.url }}" class="img-fluid w-100 h-100" alt="{{ project.project_name }} thumbnail"> <div class="project-text"> <a href="{{project.gitlab_link}}"> <h4>{{project.project_name}}</h5> <p>{{project.description}}</p> </a> </div> </div> {%endfor%} </div> <div id="no-project" class="hidden">There is no project of this type.</div> </main> {% endblock content %} {%block scripts%} … -
Using Django to add and modify an existing table in mssql
Im trying to use django to create a webpage that allows people to register themselves my django is connected to a local ms sql server and the login is correct my users table that is from BooksDataBase has the following columns with these coditions: the login column is the primary key with auto increment option and the value always start above 1000 and it will filled whenever a user is created(we dont need to fill that manuall) my 1st problem is when i order django to return the value of this table it returns with only login table with a different name: Users.objects.all() <QuerySet [<Users: Users object (1000)>, <Users: Users object (1001)>, <Users: Users object (1002)>]> my Models.py : class Admins(models.Model): adminid = models.IntegerField(db_column='AdminID', primary_key=True) # Field name made lowercase. adminlogin = models.CharField(db_column='AdminLogin', max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. usersecret = models.CharField(max_length=254, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) class Meta: db_table = 'Admins' class Books(models.Model): uid = models.AutoField(db_column='UID', primary_key=True) # Field name made lowercase. bookname = models.CharField(db_column='BookName', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. author = models.CharField(db_column='Author', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. category = models.CharField(db_column='Category', max_length=255, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. … -
django Pagination dosent show up
am trying to get Pagination to work on my django blog. I got pagination to work on my home.html but when i want it on my categories.html the code dosent work. Any ideas why it works on home.html but not on categories.html? I think this is the only files that you need to look at if am wrong ask me and i post more. Would be really glad with some help on this one. APP location views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() ordering = ['-post_date'] paginate_by = 5 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', {'cat_menu_list':cat_menu_list}) def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts}) class ArticleDetailView(DetailView): model = Post template_name = … -
how to send every specific time interval in django websocket?
When a user requests a post, the sever sends the progress of the work to the websocket When the process is finished, send a message that it is finished. Then javascript receives the message and requests to get to a specific url. The server does the filer response. The question here is how the actual service checks progress asynchronously... First of all, the code is as below. class GifConsumer(WebsocketConsumer): .... def receive(self, text_data): ... t = downloand_video.delay(data) # celery while not t.ready(): # async_to_sync(asyncio.sleep)(1) self.send(text_data=json.dumps({ 'message': "Doing" })) self.send(text_data=json.dumps({ 'message': "Done" })) The code keeps checking the status with while statements, so it seems to waste resources too much. How can I modify this? If use sleep, the web server will sleep. so, I don't think I can even request get, post.