Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pagination: redirect to specific page after edit (FBV)
I'm listing 300 of customers records using a pagination in Django. Each page contains 20 records. Suppose i'm on page 7 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). So I want , if I edit in ?page=7, when the edit in done by customer id it will come back to ?page=7. Here is my customer_list view in view.py: def customer_list(request): posts_list = Customer.objects.all() query = request.GET.get('q') if query: posts_list = Customer.objects.filter( Q(invoice__addresses__contact_number__icontains=query) | Q(invoice__addresses__address__icontains=query) | Q(shipping_method__icontains=query) ).distinct() page = request.GET.get('page') paginator = Paginator(posts_list, 20) # 20 posts per page try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'page': page } return render(request, "customers/customer_list.html", context) Here is update_customer_list view in view.py: def update_customer_list(request, id): """ Here, update single customer id form customer table :param request: :param id: :return: """ obj = get_object_or_404(Customer, pk=id) form = CustomerForm(request.POST or None, instance=obj) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Customer successfully Updated') return redirect('customer_list') return render(request, 'customers/customerUpdateForm.html', {'form': form}) Here is update_customer_list url in urls.py: path('update_customer_list/<int:id>/', views.update_customer_list, name='update_customer_list'), I am waiting for someones help and help will be highly appreciated... -
How to Convert SQL query to Django ORM?
this is the SQL query which I want to change to Django ORM please help? select 0 'bucket_id', 'Incomplete' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf is null union select 1 'bucket_id', 'Very Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 0 and 1.999 union select 2 'bucket_id', 'Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 2 and 2.999 union select 3 'bucket_id', 'OK' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 3 and 3.999 union select 4 'bucket_id', 'Good' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4 and 4.599 union select 5 'bucket_id', 'Great' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4.599 and 5 -
Ckeditor in local is not working due to the aws settings for static and media file in settings.py
I have installed the CKEditor package for my CRM backend, it was working perfectly fine. Now, I have put AWS settings in my settings.py file which contains STATIC & MEDIA root and URL settings. Due to this, my CKEditor has stopped working and I cant fill in the text data now. But, if I comment out again, CKEditor starts working again in local otherwise not. My AWS settings: DEFAULT_FILE_STORAGE = 'travel_crm.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'travel_crm.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'bonbonstage' S3DIRECT_REGION = 'ap-southeast-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } My ckeditor settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } My URLS settings: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: … -
How can I make API in django?
I have to create api in django using models.py that take data from models.py and make its api. Here is code that I have tried from rest_framework import serializers from .models import * class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('line1','line2','city','state','country','postal code') But I am finding problem to do this. How can I do this? -
Django-Vue error "Failed to mount app: mount target selector returned null."
Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. For this app job, I am implementing a job search api with Vue but somehow the error that get's shown in browser's JS console is as follows Failed to mount app: mount target selector returned null. and the search results seem to be broken and not as expected, Here is the snap of my screen as you can see the results are not as expected, it was supposed to give me the company name, job title and a link to job description, also the exact same problem occurred with another html template, what is wrong here? Search.html template file {% extends 'core/base.html' %} {% block content %} <div class="search-app"> <h1 class="title"> Search</h1> <form v-on:submit.prevent="performsearch()"> <div class="columns"> <div class="column is-4"> <div class="field"> <label>Query</label> <div class="control"> <input type="text" name="query" class="input" v-model="query"> </div> </div> <div class="field"> <label>Company Size</label> <div class="control"> <div class="select"> <select name="company_size" v-model="company_size" id=""> <option value="" selected>All</option> <option value="size_1_9" … -
django-angular for Angular?
Just want to know that if there's something like this for Angular too? This is actually a wrapper around angularJS $http service which let's us call view methods from Javascript. Wondering if there's same for latest versions Angular. This is very convenient for AngularJS as I can call view methods from my controller. django-angular -
TemplateDoesNotExist: home.html, femat/law_list.html
Why I am getting the above error while I have not defined or requested "law_list.html"? Where does the law_list.html come from? It should be something wrong with model and class based view. I am using Django 3.1.3. #models.py from django.db import models class Law(models.Model): name = models.CharField(max_length=100) E = models.FloatField(null=False, blank=False, default=0) def __str__(self): return '{} {}'.format(self.name, self.E) #views.py from django.views.generic import ListView from .models import Law class HomeView(ListView): model = Law template_name = 'home.html' #urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('', HomeView.as_view(), name='home'), ] -
Adding an annotation to django queryset to be used by django_tables2
I have a model that has (among other fields) one value for the current price of an item and one value for the usual price of an item. I'd like to include a field for the percentage saving. I've done this using the @property: @property def percSaving(self): aval = self.stickerprice bval = self.currentprice if self.stickerprice > 0: return "%0.2f" % ((aval-bval)/aval*100) + "%" elif self.currentprice == 0: return "Always Free" else: return "100% OFF" This works, I can add this column to my django_table2 table with: percSaving = tables.Column(verbose_name='% Saving') Super easy and all good. However, I am unable to sort by this column. This is because it's not one of the columns of data from the query set. So I've been trying to annotate the query set to allow for this ordering I've based by annotation attempt on this queryset api reference page and have produced this: annoed = products.objects.annotate(percSaving=((stickerprice)-(currentprice))/(stickerprice)) However this gives me an error of "name 'stickerprice' is not defined" which I thought might be because of not using inverted commas around the field names, but I tried that and got an error saying "unsupported operand type(s) for -: 'str' and 'str'" - basically using the inverted … -
What to do after learning basics of flask
I currently finished some courses with flask and made an application with fladk sqlserver for my company, but I'm stuck here, i want to work as a freelancer to improve my income but i don't know what to do next, some people told me to make more projects, but i don't have any ideas to create, And should i stick with flask or learn making rest api with flask and make other framework handle the api requests (The app i made for my company is a simple ticketing system, where employers make a support ticket for requesting help and at admin panel we have all users data and all of their printers , used flask, sql alchemy, and for the templates html css js bootstrap jquery alongside jinja2 within some templates No real hobbies) , please give me your advice -
What should I use Django Non-Global Middlewares or Django triggers
My problem is basically that I am currently making a customized management system based on Django(3.1) Python(v3.7.9) in which I am pulling the data from a third-party tool. The tool is not giving me the webhooks of every data that I want for visualization and analysis. The webhook is giving me bits of information and I have to perform a GET request to their API to fetch the rest details if those are not in my database. They are asking for a successful response of webhook within 5 secs otherwise it will trigger a retry. If I try to do a get request within the function of webhook the time of 5 second will get exceeded the solutions that I came up with was to Django Middleware or Django Triggers so which would be best suitable for my problem I am bit confused. Note: I can not lower the Django version as I have to use Async Functions -
django how to add logo in admin site
cant override the django admin site page, i just want to put a logo in my admin page, did i miss something in my code? TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, template {% extends "admin/base.html" %} {% load staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> <img src="{% static 'logo.png' %}" height="40px" /> </a> </h1> {% endblock %} {% block nav-global %}{% endblock %} -
Why can Django handle multiple requests?
According to Django is synchronous or asynchronous. Django is synchronous. However I tested a blocking view with python manage.py runserver 8100: import time @action(detail=False, methods=['get']) def test(self, request): time.sleep(5) return {} and triggered two requests with postman at 0s, 1s, and they returned at 5s, 6s. That seems not blocking/synchronous. Where am I wrong? -
Getting error on Heroku for "Django DisallowedHost at / Invalid HTTP_HOST header:" even after adding the url to ALLOWED_HOST
So I'm trying to deploy my django project to heroko, and I got this. I know what is the issue here, so I have added the url the-yogify.herokuapp.com to the ALLOWED_HOST in the settings.py file of my django project. ALLOWED_HOSTS = ['http://the-yogify.herokuapp.com/', 'https://the-yogify.herokuapp.com/', 'the-yogify.herokuapp.com', 'the-yogify.herokuapp.com/', '127.0.0.1'] But the error is still persistent. What am I doing wrong here? I thought the actual error might be something else. So I printed out the heroku logs, it also shows same error. 2020-11-24T04:10:53.978271+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-11-24T04:10:53.979367+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Listening at: http://0.0.0.0:25352 (4) 2020-11-24T04:10:53.979552+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [4] [INFO] Using worker: sync 2020-11-24T04:10:53.991703+00:00 app[web.1]: [2020-11-24 04:10:53 +0000] [10] [INFO] Booting worker with pid: 10 2020-11-24T04:10:54.026534+00:00 app[web.1]: [2020-11-24 04:10:54 +0000] [11] [INFO] Booting worker with pid: 11 2020-11-24T04:10:54.200285+00:00 heroku[web.1]: State changed from starting to up 2020-11-24T04:10:57.847722+00:00 app[web.1]: Invalid HTTP_HOST header: 'the-yogify.herokuapp.com'. You may need to add 'the-yogify.herokuapp.com' to ALLOWED_HOSTS. 2020-11-24T04:10:58.083555+00:00 app[web.1]: Bad Request: / 2020-11-24T04:10:58.092696+00:00 app[web.1]: 10.11.198.97 - - [24/Nov/2020:04:10:58 +0000] "GET / HTTP/1.1" 400 59515 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.51" 2020-11-24T04:10:58.099353+00:00 heroku[router]: at=info method=GET path="/" host=the-yogify.herokuapp.com request_id=dafb2e9e-fd1c-49d7-8375-fb0b707ef5bc fwd="42.111.13.118" dyno=web.1 connect=1ms service=2796ms status=400 bytes=59767 … -
Problem working in models rendering admin add page
i tried so many things like .formate and using id explicit in the model now i dont know what to do :( class Horas_medica(models.Model): id_boxes = models.ForeignKey(Boxe, on_delete=models.CASCADE) id_medico = models.ForeignKey(Medico, on_delete=models.CASCADE) id_paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE) descripcion = models.TextField() diagnostico = models.TextField() created_date = models.DateTimeField( default=timezone.now) def __str__(self): return str(self.id) Error in console is error TypeError: str returned non-string (type tuple) -
Django, Can tokens be used to verify user rights?
admin account test account setting.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } model.py class TestList(models.Model): key = models.AutoField(primary_key=True) pid = models.CharField(max_length=200) name = models.CharField(max_length=300) gender = models.CharField(max_length=50) age = models.IntegerField() birth_date = models.CharField(max_length=100) view.py class ListTest(generics.ListCreateAPIView): permission_classes = [permissions.DjangoModelPermissions, ] queryset = TestList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = TestListSerializer Sorry First of all, I am not good at English. I want to check if I have permission or not via token value. admin account has the "view" permission and the test account does not. However, despite the different permissions, both accounts were able to "view". What I want is to make sure that only users who have permission for that task can work with that permission. Thanks in advance to those who help me. Please let me know if you have any related sites or posts for that question! I am currently using tokens using knox. -
Get Input data perform calculation store in different field of same model
i have a models.py class DateConverterModel(models.Model): input_date = models.CharField(max_length=256, null=False) output_date = models.CharField(max_length=256) and a form forms.py class DateConverterForm(forms.ModelForm): class Meta: model=DateConverterModel fields=['input_date'] where im taking only input_date, now i'm performing calculation on it say converting date-string to date in views.py from django.shortcuts import render from .models import DateConverterModel from .forms import DateConverterForm from django.http import HttpResponseRedirect from dateutil import parser def date_converter(request): form = DateConverterForm() if request.method == 'POST': form = DateConverterForm(request.POST) if form.is_valid(): input_string = form.cleaned_data['input_date'] try: data = search_dates(input_string) except Exception as msg: print('Exception :', msg) else: try: for i in data: output_date = parser.parse(i[0]).strftime('%d/%m/%Y') DateConverterModel.objects.update(output_date=output_date) except TypeError as msg: print("String does not contain any day or dates") form.save() return HttpResponseRedirect('/response') return render(request, 'DateTimeConverter/dateconverter.html', context={'form':form}) how should i store calculated data in same field, im stuck can anyone help. -
Django unable to find javascript static files, not rendering any styling
Feels like I'm missing something basic. I'm just trying to make an django application of currently nothing but a login page using an html template that has its own css and js. But I'm having weird issues with the statements for linking my static files. No CSS styling is being rendered in my browser, and all of the javascript links get 404 file not found errors on my django server. This is the <head> of auth-login.html. {% load static %} <!doctype html> <html lang="en"> <head> <title>Login template from online</title> <!-- these aren't giving errors --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/> <link href="{% static 'assets/css/icons.min.css' %}" type="text/css" /> <link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" /> <!-- these are giving errors for some reason --> <script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script> <script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script> <script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script> <script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script> <script src="{% static 'assets/js/app.js' %}"></script> </head> In settings.py, this is how I'm specifying the static files location: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # lpbs_demo/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticAssets') The Django project is currently structured with a project app called lpbs_demo and an … -
ServerSelectionTimeoutError when using MongoClient
In my current project, I tried to connect to a MongoDB database on our server in one of my view functions. Here is my code: 260 context = {} 261 client = MongoClient() 262 db = client.lichess 263 puzzles = db.puzzle.find().limit(5) 264 265 try: 266 player = models.Player.objects.get(player_user_id=request.user) 267 logger.debug('found player') 268 except: 269 logger.debug('player doesn\'t exist!') 270 player = models.Player(player_user_id=request.user, player_isconsented=True, player_isactive=True, player_deactivated_ts=None) 271 player.save(force_insert=True) 272 273 puzzle_record_count = len(models.PR.objects.filter(PR_player_id=player.player_id)) 274 logger.debug('puzzle record count: ' + str(puzzle_record_count)) 275 # some puzzles are attempted 276 if puzzle_record_count > 0: 277 logger.debug('puzzle id: ' + str(puzzles[puzzle_record_count-1]['_id'])) 278 most_recent_puzzle_record = models.PR.objects.get(PR_puzzle_id=puzzles[puzzle_record_count-1]['_id']) However, when I tried to access puzzles[puzzle_record_count-1]['_id'](on line 277), I encountered this ServerSelectionTimeoutError: Could it be caused by my lab's server change that I didn't know? This code worked fine before, and it started causing such error about 2 days ago. Thanks in advance! -
Django and Heroku: Request has blocked by CORS in production
I created a single page web app and used Django as backend. The webapp worked as expected on local but my requests from client side has been blocked by CORS in production (I host backend on Heroku). My current code is like this. settings.py INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] ... CORS_ALLOWED_ORIGINS = [ "http://...", ] ... This settings works on local but doens't work on production. Am I missing something? -
django.db.utils.OperationalError: FATAL: password authentication failed for user using postgres
I have this code in my settings.py, and why i am getting this is error? django.db.utils.OperationalError: FATAL: password authentication failed for user "gmovesDatabasev1"? ive already done doing this to my pgadmin CREATE USER gmovesDatabasev1 WITH PASSWORD 'password'; and still im getting stuck in this error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'gmoves', 'USER': 'gmovesDatabasev1', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } -
How to prevent Duplicate Signals in Django
I have added a notification where every time a user submits a Like button to a post, the owner of the liked post receives a notification. I have set Value options for each Like button to be Like or Unlike I have restricted the notification to be sent only if the Value of the like clicked is Like only. So, now in the Like Model I have added signal and a condition that if the Like.value== Like the signal activates but for some reason it is sent twice only when a new post is created and a new user clicks like for the very first time, afterwards if he unike and likes again it is sent once. My question is: Why is the signal duplicated everytime a new user clicks the Like button? How to fix it? Here is the post models.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField(User, related_name='liked', blank=True) here is the Like model.py: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, … -
I'm using the Google Calendars API with Django, where do I get my token and refresh_token?
I'm trying to do something like what's shown below. However, I can only see my client ID and secret key on the developers console. I wasn't sure about the token, but I tried creating an API key and passing that in. However, I have no clue where to get the refresh_token. I've included a screen cap of my developer console. We're using django-allauth, and I know that you can set social account tokens in the Django admin, is that what I would need to do? from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials creds = Credentials( token='token here', refresh_token='refresh token here', scopes=['scopes', 'listed', 'here'], token_uri='https://accounts.google.com/o/oauth2/token', client_id='client_id', client_secret='client secret' ) creds.expiry = timezone.make_naive(self.token.expires_at) if not creds.valid or creds.expired: creds.refresh(Request()) -
Use Wordpress for authenticating Django users
I have a WordPress site with multiple users configured. I also have a Django-based site. I would like to have my Django site use the Wordpress site to authenticate users. Is it possible to have Wordpress serve as an authentication server for a Django site? If so, how? If that's not practical, I would also be OK with configuring a self-hosted third-party authentication server that both systems could query to authenticate a user. The net result, either way, is that I'd like for the same Wordpress credentials to work in Django, even if it requires entering them separately - I don't need the logged-in session to pass from one to the other. Thanks! -
django-allauth AUTHENTICATED_LOGIN_REDIRECTS is not working
the redirect from /login/ when user is authenticated is handled in this method: class RedirectAuthenticatedUserMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated and app_settings.AUTHENTICATED_LOGIN_REDIRECTS: redirect_to = self.get_authenticated_redirect_url() response = HttpResponseRedirect(redirect_to) return _ajax_response(request, response) else: response = super(RedirectAuthenticatedUserMixin, self).dispatch( request, *args, **kwargs ) return response def get_authenticated_redirect_url(self): redirect_field_name = self.redirect_field_name return get_login_redirect_url( self.request, url=self.get_success_url(), redirect_field_name=redirect_field_name, ) the AUTHENTICATED_LOGIN_REDIRECTS is set by default to True according to documentation using breakpoints to debug, I have found out that request.user.is_authenticated and app_settings.AUTHENTICATED_LOGIN_REDIRECTS is always returning false, changing the condition to request.user.is_authenticated and settings.AUTHENTICATED_LOGIN_REDIRECTS the condition was corrected and it returns True and the user was redirected from /login/ URL to the one set in settings: LOGIN_REDIRECT_URL = "/" my question why the app_settings was not able to fetch the variables in settings? and How do I fix this problem? -
How to reload django app if there is a file change inside it?
I have two api in django apps python, create model api and use model api for predict data. how to automatically reload file change on it?