Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache mod_wsgi error when switching from Mysql to Postgres database for Django application
My django application has been running fine on my ubuntu ec2 instance, Apache2 + mod_wsgi, and a Mysql database running on the same instance. I decided to switch to a separate postgres RDS database, but when I try to use this database I get an Apache 'Internal server error' and the following wsgi errors in my Apache error.log file. If I switch to the Mysql database in my settings.py, the website still works. The error only occurs when I just the separate postgres database. I am using Django 2.2 with python3.7 Apache configuration: <IfModule mod_ssl.c> <VirtualHost *:443> ... Alias /static /home/ubuntu/ratemanager/Projects/static <Directory /home/ubuntu/ratemanager/Projects/static> Require all granted </Directory> <Directory /home/ubuntu/ratemanager/Projects/Projects> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ubuntu/ratemanager/Projects/Projects/wsgi.py WSGIDaemonProcess django_app python-path=/home/ubuntu/ratemanager/Projects python-home=/home/ubuntu/ratemanager/Projects/venv WSGIProcessGroup django_app SSLCertificateFile /etc/letsencrypt/live/... SSLCertificateKeyFile /etc/letsencrypt/... Include /etc/letsencrypt/options-ssl-apache.conf error.log [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:error] mod_wsgi (pid=27601): Target WSGI script '/home/ubuntu/ratemanager/Projects/Projects/wsgi.py' cannot be loaded as Python module. [wsgi:error] mod_wsgi (pid=27601): Exception occurred processing WSGI script '/home/ubuntu/ratemanager/Projects/Projects/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/usr/local/lib/python3.6/dist-packages/django/db/backends/postgresql/base.py", line 20, in <module> [wsgi:error] import psycopg2 as Database [wsgi:error] ModuleNotFoundError: No module named 'psycopg2' [wsgi:error] [wsgi:error] During handling of the above exception, another exception occurred: [wsgi:error] [wsgi:error] Traceback (most recent call … -
Getting Django CSRF error with raw html form
I'm trying to set up a raw html form where a user can make a suggestion and then save it on a database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section. I have found that I don't get the error if I add csrf_exempt on top of my view like this: from django.views.decorators.csrf import csrf_exempt @csrf_exempt def suggest_ptags(request): context = {} print("Form is submitted.") return render(request, "partials/search_form.html", context) But I was made aware that It removes completly the CSRF protection and I don't want that. So what should I do? Here's my search_form.html form in a partials folder in templates: <!-- Suggestion Form in popup --> <div class="prop-modal"> <div class="prop-content"> <a class="btn-close-prop">&times;</a> <img src="{% static 'images/pyramids.svg' %}"> <form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain"> {% csrf_token %} <h5 class="title-prop">Suggestion</h5> <input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input> <input class="button-prop" type="submit" value="Envoyez"></input> </form> </div> </div> My current Views.py: from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def suggest_ptags(request): context = {} print("Form is submitted.") return render(request, "partials/search_form.html", context) And in my Urls: from django.conf.urls import url from django.contrib import admin from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags from .settings … -
What are the best practice/structure for setting up Web front-end with heavy calculation at back-end?
Project has 2 parts: 1st: Python + Django for a front-end web interface 2nd: Python/C++ for heavy calculations/Machine Learning As me and my partner have no experience in projects of this scale, we are looking for a general overview or/and best-practice for setting them up to be independent and maybe having back-end on a different server for haevy 'math' and use web front-end as an interface. Project is in Bioinformatics and ML so users will just input some data and get data back and some graphs as an example. How to set up Web interface (Py+Django) and back-end (py-cpp-heavy math) so they can be updated independently but still link each other and for the first one not to include the second one? Right now we just have 2 folders, one with the web-front-end and other one with back-end and first one just imports the second one. What is they are on a different servers/locations ? -
can i show or make clickable only specific timeslots in models.DateTimeField in Django?
I am trying to make a simple appointment webpage. User will choose a date, choose one of the available time slots for that date (time slots already chosen would be greyed out). I was using models.DateTimeField which gives a textfield and some time slots to choose from. i don't want the textfield and need specific timeslots with 30 minute gaps. I have tried using django-scheduler which I really don't seem to understand, probably because I'm new to django. Any help on how can I achieve that? thanks in advance. -
how to set cookies during vuejs post
I am trying to send post data to a django Restful API using vuejs. here is the code I have so far: <script> import axios from 'axios' import VueCookies from 'vue-cookies' //3RD ATTEMPT VueCookies.set("csrftoken","00000000000000000000000000000000"); // @ is an alias to /src export default { name: "Signup", components: {}, data: () => { }, methods: { sendData(){ // 2ND ATTEMPT // $cookies.set("csrftoken", "00000000000000000000000000000000"); axios({ method: 'post', //you can set what request you want to be url: 'https://localhost:8000/indy/signup/', data: { csrfmiddlewaretoken: "00000000000000000000000000000000", first_name: "wade", last_name: "king", email: "wade%40mail.com", password1: "05470a5bfe", password2: "05470a5bfe" }, // 1ST ATTEMPT // headers: { // Cookie: "csrftoken= 00000000000000000000000000000000" // }, withCredentials: true }) } } </script> I have a button which executes the sendData() method on a click. The code uses the axios library to send a post request to the django API running on http://localhost:800/indy/signup/ The problem with just sending a post request to the API is that it will get blocked in order to prevent Cross Site Response Forgery (CSRF), I dont quite understand CSRF but I know if the csrftoken is set as a cookie and has the same value as the csrfmiddlewaretoken then the post should go through to the API. You can … -
Test database not keeping data during Django Channels Pytest test
I'm writing tests for a Django Channels application following the documentation. I can successfully test connection and communication with the WebSocket consumer. However, in one of the tests I need to create a user. This is my test method: @pytest.mark.django_db @pytest.mark.asyncio async def test_1(): my_user = get_user_model().objects.create_user(username='my_user', email='user@user.com', password='123456') my_user.save() print(User.objects.all()) communicator = WebsocketCommunicator(MyConsumer, '/websocket/') communicator.instance.scope['user'] = my_user connected, subprotocol = await communicator.connect() assert connected await communicator.send_json_to({ 'command': 'test', }) response = await communicator.receive_json_from(timeout=5) await communicator.disconnect() The error occurs inside the method that handles the 'command' == 'test' case. When it tries to save another model instance that has User as a foreign key, the test fails. client = Client(user=scope['user']) client.save() If I add a print(User.objects.all()) to the method inside the consumer (between the previous two lines), it returns an empty QuerySet, while the first print in the test method itself returns the created user. Of course, since there is no User, the test fails with: django.db.utils.IntegrityError: insert or update on table "chat_client" violates foreign key constraint "chat_client_user_id_d10928fc_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". I tried turning user creation into another async method and awaiting for it, but nothing changed. Why is the User table getting emptied … -
converting auth_views.login from django 1 to 2
I'm reading the book "Learning Python" and I've come across an issue with the chapters project. The project uses an older version django so I've had to modify some items, but this one really has me stuck. Basically the auth_views.login needs to become auth_views.LoginView. Same for logout. I can't figure out how to "convert" the code over to the new method. I've taken a look at the documentation and the docs don't show an apples to apples example of the projects workflow (using regex urls). This throws a position argument error (takes 1, 2 were given) tried replacing : url(r'^login/$', auth_views.login, kwargs={'template_name': 'admin/login.html'}, name='login'), with : url(r'^login/$', auth_views.LoginView(template_name='admin/login.html'), name='login'), to no avail. Below is a full snippet. # regex/urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.core.urlresolvers import reverse_lazy from entries.views import HomeView, EntryListView, EntryFormView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^entries/$', EntryListView.as_view(), name='entries'), url(r'^entries/insert$', EntryFormView.as_view(), name='insert'), # here lies the troublemaker url(r'^login/$', auth_views.login, kwargs={'template_name': 'admin/login.html'}, name='login'), # as well as here url(r'^logout/$', auth_views.logout, kwargs={'next_page': reverse_lazy('home')}, name='logout'), url(r'^$', HomeView.as_view(), name='home'), ] -
How do I get path of django project
My previous developer left in between without documenting. The project is running on local remote windows machine on port 8000. I.e 127.0.0.1:8000 I want to know where is the location of code associated with this process. Any help is much appreciated. -
Unable to style Django Default Login Form with Bootstrap
When I try to style Django default login template with a bootstrap in a custom forms.py file it doesn't work. There are no error but I still see the default un-styled login form. In other words, LoginView doesn't appear to be using the AuthenticationForm at all. Login.html <body> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </body> </html> forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput( attrs={'class':'form-control'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control'})) urls.py from django.contrib import admin from django.urls import include from django.urls import path from django.contrib.auth.views import LoginView from django.contrib.auth import views from myProject.forms import LoginForm urlpatterns = [ path("admin/", admin.site.urls), path('accounts/login/', LoginView.as_view(),{'template_name':'registration/login.html','authentication_form':LoginForm}), path('login/', LoginView.as_view(template_name='registration/login.html'),{'authentication_form':LoginForm}) I've tried several things including using different syntax for 'accounts/login/' and 'login/' paths above as I thought that could have been my problem but it hasn't made any difference. -
how to check if list have specific content , if find content "a" perform one action or if find content "b" perform another action
I want to check if posted variable have value ="whatis" or "how" if have "whatis" perform one task or if have value "how" performa different task def addsearch(request): addsearch = request.POST.get('searchcontent') wordlist = re.sub("[^\w]", " ", addsearch).split() s = ''.join(wordlist) question = re.findall('whatis', s)[0] q = ''.join(wordlist) question1 = re.findall('how', s)[0] check1 = "whatis" check2 = "how" if question == check1 #perform taskA if question1 == check2 #perform taskA its working if am only checking "whatis" when am checking if have "whatis" or "how" its show error IndexError: list index out of range -
CSRF verification failed with raw html form
I'm trying to set up a raw html form where a user can make a suggestion and then save it on a postgres database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section. How can I fix this? My search_form.html form: <!-- Suggestion Form in popup --> <div class="prop-modal"> <div class="prop-content"> <a class="btn-close-prop">&times;</a> <img src="{% static 'images/pyramids.svg' %}"> <form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain"> {% csrf_token %} <h5 class="title-prop">Suggestion</h5> <input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input> <input class="button-prop" type="submit" value="Envoyez"></input> </form> </div> </div> My Views' def: from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def suggest_ptags(request): context = {} print("Form is submitted.") return render(request, "search_form.html", context) And in my Urls: from django.conf.urls import url from django.contrib import admin from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags from .settings import MEDIA_ROOT, MEDIA_URL from django.conf.urls.static import static urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), url(r'^admin/', admin.site.urls), url(r'^suggest_ptags/$', suggest_ptags, name='suggest_ptags'), #Suggestions url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'), url(r'^search/autocomplete/$', autocomplete), url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'), ] + static(MEDIA_URL, document_root=MEDIA_ROOT) -
Django ModelForm Custom Date Field
I am trying to create a reservation form that creates an object for model Reservation when the form is posted. I am using a custom datepicker widget to pick the ate, but I am also using ModelForms. The issue is that, if I do not have 'date' listed in the meta fields list in the forms.py, then the form doesn't look for the date field form input on post. But if I include 'date' inside the meta fields of the forms.py Modelform, then it errors and says "date field can not be left blank" even though it is not blank... forms.py class ReservationForm(forms.ModelForm): date = forms.DateField( widget=DatePickerInput(format='%m/%d/%Y') ) def clean_date(self): data = self.cleaned_data['date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - reservation in past'), code='invalid') messages.danger(request, "Reservation Created") print('ERROR') # Remember to always return the cleaned date. return data class Meta: model = Reservation fields = ('reservation_time', 'people', 'name', 'email', 'phone') # REMOVED 'date' views.py def reservationFormView(request): #reservation = create(Reservation) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): … -
Dynamic ChoiceField unable to be validated in form
I have a form that's being given a dictionary of selection, it populates it correctly but on form submit it is not valid. When attempting to print errors, non_field_errors there are just blanks. When I am redirected to the form, now the choice field is populated by one choice and the csrf token from previous submit. I've tried assigning choices in different ways such as self.fields['calendar'] = forms.ChoiceField(choices=choice_list) directly assign in a different way. self.fields['calendar'].choices = choice_list, a custom validator that ignores the validation, and inline debugging. Form model: class CalendarSelectionForm(forms.Form): calendar = forms.ChoiceField(label="Calendar") def __init__(self, calendars=None, *args, **kwargs): super(CalendarSelectionForm, self).__init__(*args, **kwargs) choice_list = [(calendar_id, calendar_name) for calendar_id, calendar_name in calendars.items()] if calendars: self.fields['calendar'].choices = choice_list View: if request.method == "POST": print(request.POST) cal_sync_form = CalendarSelectionForm(request.POST) print("Non-field errors " + str(cal_sync_form.non_field_errors())) print("Reg form errors " + str(cal_sync_form.errors)) # print("Field val " + str(cal_sync_form.calendar)) print("Field data " + str(cal_sync_form.data)) print("Field fields " + str(cal_sync_form.fields) + " Form is " + str(cal_sync_form.is_valid())) if cal_sync_form.is_valid(): data = cal_sync_form.cleaned_data print(data) return render(request, 'management/gcal_sync_dashboard.html') else: return render(request, 'management/acct_select.html', {'form': cal_sync_form}) Form template: <form class="form-import" action="/manage/gcal/sync/" method="post" id = ""> {% csrf_token %} {{ form.calendar }} {{ form.errors }} {{ form.non_field_errors }} <div class="push clearfix"></div> <div class="col-sm-6 … -
Django: post_save signal doesn't trigger on model post save
This is my code. model.py from django.db import models from metrics.models import InventoryProduct from product.models.product import Product class PurchasedOrder(models.Model): __quantity_sold = None product = models.ForeignKey(Product, on_delete=models.CASCADE) purchase_quantity = models.IntegerField() quantity_sold = models.IntegerField(default=0) def __init__(self, *args, **kwargs): super(PurchasedOrder, self).__init__(*args, **kwargs) self.__original_quantity_sold = self.quantity_sold def save(self, *args, **kwargs): # If the quantity sold field has changed run the update_sold_out method if self.quantity_sold != self.__original_quantity_sold: PurchasedOrderLogic.update_sold_out(self) super(PurchasedOrder, self).save(*args, **kwargs) self.__original_quantity_sold = self.quantity_sold def __str__(self): return self.product.name signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from purchasing.models import PurchasedOrder from purchasing.services.models_logic import PurchasedOrderLogic @receiver(post_save, sender=PurchasedOrder) def update_inventory_product_total_qty_purchased(sender, instance): PurchasedOrderLogic.update_inventory_product_total_qty_purchased( sender, instance.product.id, instance.purchase_quantity ) I put here some print statements to see that I get the correct sender and instance which I will then later use to do some stuff. purchasing.services.models_logic.py class PurchasedOrderLogic(object): @static_method def update_inventory_product_total_qty_purchased(purchased_order_class, purchase_quantity): print('----') print(purchased_order_class) print(purchase_quantity) print('----') apps.py from django.apps import AppConfig from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from purchasing.models import PurchasedOrder from purchasing.signals import update_inventory_product_total_qty_purchased class PurchasingConfig(AppConfig): name = 'purchasing' verbose_name = _('purchasing') def ready(self): post_save.connect(update_inventory_product_total_qty_purchased, sender=PurchasedOrder) What am missing? I'm not sure even if the signal is running? -
Unwanted Text Included When Rendering Multiple Plots Using Bokeh with Django
When I render more than one plot using Bokeh and Django it would appear I am rendering the dictionary or the list text itself along with my two graphs. I have read through the documentation and have searched here on Stack Overflow and have even found one item that is central to what I believe is happening Bokeh plot tag rendering issue However, this user is clearly using Flask and Jinga where I am using Django and DTL, so I am not able to apply this particular solution. I have tried to adapt it to a Django view, but have not been successful thus far. MY VIEW>>>> def test_html(request): plot1 = figure() plot1.circle([1, 10, 35, 27], [2, 0, 45, 0], size=20, color= "blue") plot2 = figure() plot2.circle([1, 10, 35, 27], [3, 25, 3, 44], size=20, color= "blue") plots = [plot1, plot2] script, div, = components(plots) return render(request, 'test_html.html', {'script': script, 'div':div}) MY TEMPLATE>>> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.css"/> <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.css"/> <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.1.0.min.css"/> <title>Bokeh</title> </head> <body> <h1>My Chart <h1> {{div | safe}} </body> <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-1.1.0.min.js"></script> <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.1.0.min.js"></script> <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.1.0.min.js"></script> <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-api-1.1.0.min.js"></script> {{script| safe}} </html> Right now I am seeing … -
When asking for authorization to access the drive, all works well except it just doesn't redirect
I'm using pydrive to upload a pdf file to a google drive, all is working super well, except there's one very unpleasant issue. When I click in allow, all works well in the background, but it just doesn't redirect anywhere. If I click again, it redirects but also gives an error. I'm not sure if there's any code showing that could help. I use this for redirect_uri: gauth.flow.redirect_uri = "http://localhost/accounts/oauth_validator" This works btw, it works when I'm not asking for consent, it only doesn't work when asking for consent. Is there any settings that I'm missing? -
how to create a django project in windows command promt, i am getting an error of "the system cannot find the the path specified"
while creating a django project in windows command promt i created a directory using mkdir djproject ->my directory name then to create a project using cd project -> my project name it showing "the system cannot find the path specified" (myproject) C:\Users\USER>django-admin --version 2.2.1 (myproject) C:\Users\USER>mkdir djproject (myproject) C:\Users\USER>cd djproject1 The system cannot find the path specified. -
how to check if two variable are same or not by using if or statement
in the below code , am trying to check if posted content have any keyword as "whatis" or "what" , everything works , but when I put if statement it show syntax error def addsearch(request): addsearch = request.POST.get('searchcontent') wordlist = re.sub("[^\w]", " ", addsearch).split() s = ''.join(wordlist) question = re.findall('whatis', s)[0] q = ''.join(wordlist) question1 = re.findall('what', q)[0] q1 = "what" , q2 ="whatis" if question == q2 or question1 == q1 abc = "this is a question" return render(request, 'searchme.html', {"addsearch": addsearch, "splitcontent":wordlist,"question":question,"abc":abc}) -
I'm getting 'Social Network Login Failure' in django all-auth but can't figure out why
I tried to add social login to my django project, so I edited everything I need to change, as far as I know.. And now I just think God is punishing me.. I installed django-allauth, of course. This is what I added : AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) INSTALLED_APPS = ( # The following apps are required: 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.kakao', # For kakao-provider... ) SITE_ID = 3 # I set this by checking Site objects. # django-allauth setting LOGIN_REDIRECT_URL = 'tif:index' # 로그인 후 리디렉션할 페이지 ACCOUNT_LOGOUT_REDIRECT_URL = "tif:index" # 로그아웃 후 리디렉션 할 페이지 ACCOUNT_LOGOUT_ON_GET = True # 로그아웃 버튼 클릭 시 자동 로그아웃 urlpatterns = [ ... url(r'^accounts/', include('allauth.urls')), ... ] After migration, I made a new app in my kakao platform, set my callback uri, registered my server name, http://13.125.184.241:8080, and other minor settings. I added new app in Social Accounts/ Social Applications, filling appropriate sites. So, when I access to the site where I can login, http://13.125.184.241:8080/accounts/kakao/login/callback/, It fails at the last moment. At the last moment, after my login … -
How to return dictionary to render from views inside an on-click javascript functions?
I've tried so many things and am not winning with, hope someone can help. So i have a template 1 which is render to select checkboxes. Once the checkboxes are selected via a button, the javascript button sends this array of selected checkboxes to a views function which send this to an external function. This external function looks up the values of the selected checkboxes and saves to a database as well as return this dictionary to the view function. The task is not to send this dicitonary to render on another html template. However it is all still within the javascript on-click function and for some reason i am unable to send this dicitonary to the template (as the variable is undefined) nor to the javascript via a GET ajax function (where the error is that the url is not found to GET the variable). in views.py def curChecked(request): request.POST.get('checkbox') curArr = json.loads(request.POST['checkbox']) user_results = SessionAvg.objects.filter(user=request.session['user']) username = request.session['username'] results2 = calc(subArr,user_results, username) print(results2) currencyresults = json.dumps(results2) print(currencyresults) return HttpResponse('main_app/results.html', currencyresults) in javascript document.getElementById('results').addEventListener('click', function(){ html_table = '<thead><tr><th>Currency</th><th>Level</th><th>Unit</th><th>Flag</th><tr/><thead/>'; cols = []; var checkElements = document.getElementsByClassName('ch'); var curChecked = []; for(var i =0; i< curname.length; i++){ if (checkElements[i].checked) { curChecked.push(curname[i]); … -
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I'm getting a 'Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.'. Did I miss anything or did I oversee anything? <a class="navbar-brand" href="{% url 'blog:post_list' %}"> urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), ] views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) models.py from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() show = models.TextField(max_length=140, default='DEFAULT') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Django filter through computed value of 2 Foreignkeys
Consider the following: class Fighter(models.Model): ... #a bunch of fields class View(models.Model): fighter = models.ForeignKey(Fighter,on_delete=models.CASCADE, related_name="views") viewer = models.ForeignKey(User,on_delete=models.PROTECT, related_name="viewed") #User.viewed.all() returns all View objects of the Fighters the user viewed class Clash(models.Model): win_fighter = models.ForeignKey(Fighter,on_delete=models.SET_NULL, related_name="wins") loss_fighter = models.ForeignKey(Fighter,on_delete=models.SET_NULL, related_name="losses") The key here is fighter_quality = wins/views = Fighter.wins.all().count()/Fighter.views.all().count() I need to be able to filter this quality, for instance all Fighters where 50% < quality < 80%. I want my Postgres DB to make the work. I feel like it should be possible via Aggregate but can't figure out how... -
Where to place handler in our project
I have recently go through the Django documentation but I have a doubt that where to place this code 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, thank you for the answers -
Why 'SLUG field' is not working correctly in Django 2.0
How do I get to show the slug in the URL when a user click on one of the 'Course' on the page ? At the moment, when click on 'Course' to access the 'detail page' i receive the following error : Not Found: /subjects/1/ Please find codes below: models.py from django.db import models from django.utils.text import slugify from django.urls import reverse class Course(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Course, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('core:detail', kwargs={'slug': self.slug}) class Subject(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(max_length=250) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='subjects') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.index, name='index'), path('subjects/<slug:slug>/', views.detail, name='detail') ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Course def index(request): courses = Course.objects.all() context = {'courses':courses} return render(request, 'core/index.html', context) def detail(request, slug): subjects = get_object_or_404(Course, slug=slug) context = {'subjects':subjects} return render(request, 'core/detail.html') index.html {% for subjects in courses %} {{ subjects.name }} {% endfor%} detail.html {% for course … -
I need assistance comparing the year stored in a DateTimeField to the current year and counting the number of items that match
I have a list of procedures that have a date showing when they are due to be reviewed. I am trying to count the procedure that are due for the current year and display that number on my webpage. (For ex. if I have x number of procedures in my database that are due this year. I would like for them to be counted and have the total number stored in a variable that I can pass to my webpage and display "Procedures needing to be reviewed this year is: x") Not sure how to properly extract the year from the DateTimeField and compare to the current year from the datetime.now().year. Thanks. I have tried using .count but i get various errors depending on the variable I use. See my code for more explanation of error messages and what I have tried. views.py # gets current year and stores it in currentYear. currentYear = datetime.now().year # opmToReview = posts.objects.filter(reviewYear = 'currentYear').count() # gives error - Cannot resolve keyword 'reviewYear' into field. # opmToReview = posts.objects.filter(reviewDue = 'currentYear').count() # gives error - 'currentYear' value has invalid format. #Tried this too but, doesn't work # testing for comparing dates def opmToReview(request): count …