Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-crontab job not running on developement server
I have the following task in cron.py. from coreapp.models import Event, User def update_survey_summary(): print("starting") u = User.objects.get(email="admin@email.com") e = Event( creator=u, title="Some event", location="Some location", hosted_by="Admin" ) print("saving...") e.save() And here are crontab config in settings.py: CRONJOBS = [ ('*/5 * * * *', 'coreapp.cron.update_survey_summary') ] INSTALLED_APPS = [ "django_crontab", ... Basically, the idea is to insert a record every 5 minutes. But nothing happens, and if use python manage.py crontab run <hash>, the job runs successfully and indeed does insert a record in the database. What am I missing? -
Django login integration with Microsoft AD
I successfully managed to integrate Microsoft Azure AD login on my Django site, but how do i make it such that users are always logged out after the browser is closed (i.e. have to login using Microsoft AD each time they access the site)? I dont know how to integrate Django sessions with request.identity_context_data -
How to fix AttributeError at /login/ 'NoneType' object has no attribute 'lower'
I am trying to create a login form in Django. In that form, there are 2 fields, username, and password for login. Now I have used lower() at the time of getting the username. Have a look at the code below. I have used lower() because if an user enters the upper case letter they don't have to face any problem. Here is the code def loginForm(request): page = 'login' if request.user.is_authenticated: #if user is already login, restricted to visit the login page again return redirect('home') if request.method == 'POST': username = request.POST.get('username').lower() password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request,'User does not exist') user = authenticate(request,username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request,'Invalid Username or Password') context = {'page':page} return render(request, 'base/register_login.html',context) here is the SS of the error.. Screenshot of the error in the code Kindly let me know how can I solve this error.. -
Submit a form only once in Django
I am trying to make the user submit a form only once. I have a /dashboard page which is shown after submitting the /petform. But, I want the user to submit the form only once after logging in and other times it should redirect to the /dashboard directly (or show a message that "form already submitted"). models.py class PetFormData(models.Model): abstract = True name = models.CharField(max_length=100) age = models.IntegerField() breed = models.CharField(max_length=100) amount_spent = models.CharField(max_length=100, choices=AMOUNT_CHOICES) pincode = models.CharField(max_length=15) services_required = models.CharField(max_length=100, choices=SERVICE_CHOICES) auth_user_email = models.ForeignKey(User, on_delete=models.CASCADE) form_submitted = models.BooleanField(default=False) views.py @login_required def showformdata(request): form = PetForm(request.POST) if request.method == 'POST': if not PetFormData.form_submitted and user == PetFormData.auth_user_email: PetFormData.form_submitted = True print(PetFormData.form_submitted) if form.is_valid(): user = request.user nm = form.cleaned_data['name'] age = form.cleaned_data['age'] breed = form.cleaned_data['breed'] am_sp = form.cleaned_data['amount_spent'] pin = form.cleaned_data['pincode'] ser_req = ','.join(form.cleaned_data['services_required']) model_pet_form = PetFormData(name=nm, age=age, breed=breed, amount_spent=am_sp, pincode=pin, services_required=ser_req, auth_user_email=user) model_pet_form.save() print(session_data) return redirect('/dashboard') else: print(PetFormData.form_submitted) return HttpResponse('Form already submitted', content_type="text/plain") else: form = PetForm() return render(request, 'petform.html', {'form': form}) -
How to overwrite Django Admin result_list?
Django newbie here.. I am working on a projects that I need to do search in Django Admin Panel. I have a model named SearchModel and it has colums named "id", "word" and an object called Desert and this object has '1' as id I have another model named Result000 ('000' refers to the first three letters of md5 of Desert). It has columns named "id", "word_id", "score", "title" and has an object named "Sahara Desert" whose "word_id" is the same as the id of the "Desert" object in the first table. No ForeignKey or any other relation types between those table's items here's the question: When I search for Desert in SearchModel's search field. I want to list all objects in table Result000 which have same word_id as id of "Desert" object in SearchModel When I search for Desert in SearchModel's search field. I want to list all objects in table Result000 which have same word_id as id of "Desert" object in SearchModel here's my current code: # root/admin.py class BookAdmin(admin.ModelAdmin): def __init__(self, model, admin_site): self.list_display = [field.name for field in model._meta.fields] self.search_fields = [field.name for field in model._meta.fields] self.temp_model = "SearchModel" self.temp_term = "" self.word_id = None self.search_term … -
CSRF verification failed. Request aborted. After deploy to cloud
I wrote a Django application and after I developed put it to a Docker container and deploy it to Google Cloud Run. The server is OK and run but when I want to type something in the forms and submit it I got this error: Forbidden (403) CSRF verification failed. Request aborted. What's the problem with it? Should I add something besides the csrf_token? Here's my views.py: from django.shortcuts import render, redirect from . models import Action ##from django.core.mail import send_email def index (request): actions = Action.objects.all() return render(request, 'index.html', {"actions": actions}) def uj_szemely (request): if request.method == "GET": return render(request, 'uj_szemely.html') elif request.method == "POST": surname = request.POST.get('surname') lastname = request.POST.get('lastname') whatdo = request.POST.get('whatdo') done = request.POST.get('done') created = request.POST.get('created') deadline = request.POST.get('deadline') if done == 'on': done = True else: done = False formaction = Action(surname=surname, lastname=lastname, whatdo=whatdo, done=done, created=created, deadline=deadline) formaction.save() return redirect('fooldal') def fooldal (request): return render(request, 'fooldal.html') My models.py: from pyexpat import model from django.db import models class Action (models.Model): surname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) whatdo = models.TextField() done = models.BooleanField(default=False) created = models.DateField(auto_now_add=True) deadline = models.DateTimeField() I also have a contact page on the website and the contact's form is giving the same … -
Change layout of django-filter form
I am currently working on my first bigger django project and I am facing issues regarding the layout of my data filters made with django-filters. The default layout of the django-filter form is a vertical list (see image), but I need to make it horizontal, consisting of two rows (labels/fields). What is the (best practice) way to edit the layout? Is there a way I can access every Label/Field-Item of the form from within the template, so I can use Bootstrap5 Grid? One restriction is, that my template will be used by differents models/filters, so I need to configure the layout dynamically. Every hint is very much appreciated :) Thank you! My template (relevant section) <form method="get" class="form"> <button type="submit" class ="btn btn-primary">Filtern</button> {% crispy filter.form %} </form> my django-filter filter class class EquipmentFilter(FilterSet): class Meta: model = Equipment fields = {'name': ['icontains'], 'description': ['icontains']} my model class Equipment(models.Model): """Device that can execute a measurement""" name = models.CharField("Name", max_length=50) description = models.CharField("Description", max_length=100) configuration = models.JSONField("Configuration", default=dict) equipment_category = models.ForeignKey("EquipmentCategory", on_delete=models.CASCADE, verbose_name="Equipment Category") -
How to Solve IImportError in Django?
I'm new to django and I'm facing some difficulties in creating a user from the AbstractUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my Owner model from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import CASCADE, BooleanField from user_app.forms import LoginForm class user_type(AbstractUser): is_user = models.BooleanField('Is user', default=False) is_police = models.BooleanField('Is police', default=False) is_insurance = models.BooleanField('Is insurance', default=False) is_rto: BooleanField = models.BooleanField('Is rto', default=False) class Owner(models.Model): user_id = models.AutoField(primary_key=True) login_id = models.ForeignKey(LoginForm, on_delete=models.DO_NOTHING) user_name = models.CharField(max_length=255) aadhar_number = models.CharField(max_length=16) photo = models.FileField() mobile = models.IntegerField() licence = models.CharField(max_length=10) address = models.TextField() state = models.CharField(max_length=10) district = models.CharField(max_length=10) city = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() and there another import error occurred in forms.py. this is my form.py from django import forms from user_app.models import user_type class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control" } ) ) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": "form-control" } ) ) class Meta: model = user_type fields = ('username', 'email', 'password1', 'password2', 'is_user','is_insurance', 'is_police', 'is_rto') and when I'm running this project using 'python manage.py runserver' then it shows File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py", line 7, in <module> from user_app.forms … -
facing problems with psycopg2 django
My python version is 3.10 and postgre version is 14 I am working on django, there I got an issue that is: my settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } when I write this command; python manage.py runserver it says, Error loading psycopg2 module: No module named 'psycopg2' then I run the command to install psycopg2 pip install psycog2 successfully installed the psycopg2 but after I run the python manage.py runserver it shows the error; AssertionError: database connection isn't set to UTC I found the solution that downgrade your psycopg2 version to 2.8.6 So I uninstall and run the command again; pip install psycopg2==2.8.6 but after that, it shows the error when I run the server Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found. please help me with that I am new to python thanks in advance -
add django_contrab schedules returns "Unknown command: 'crontab'"
I have configured django-crontab accordingly in my newly installed WSL2, ubuntu. And, when I did run python manage.py crontab add it worked just fine yesterday. Today, I tried to run the command again, and it returns: Unknown command: 'crontab' Type 'manage.py help' for usage CRONJOBS = [ ('*/5 * * * *', 'coreapp.cron.update_survey_summary') ] INSTALLED_APPS = [ "django_crontab", "drf_spectacular", "rest_framework", .... # coreapp.cron.update_survey_summary from coreapp.models import Event, User def update_survey_summary(): u = User.objects.get(id=6) e = Event( creator=u, title="Event ", location="Algeria", hosted_by="Admin" ) print("saving...") e.save() One other thing is that the django app would run successfully with python3 manage.py runserver. Which I find weird. -
Django DateInput widget format
I am trying to change the date format from mm/dd/yyyy to dd/mm/yyyy in a DateInput widget. I am trying to change the format the following way. class Meta: model = Patient fields = '__all__' widgets = { 'date_of_birth': widgets.DateInput( format='%d-%m-%Y', attrs={'type': 'date', 'class': 'form-control'}) } I noticed that if I don't include the 'type': 'date' attribute the date is interpreted in the correct format, but in that case the widget isn't displayed but just a text-field. So you have to write the date manually (including /). I have also tried changing the settings.py the following way which also didn't help. LANGUAGE_CODE = 'en-GB' TIME_ZONE = 'CET' USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = ('%d/%m/%Y') -
What is the best practice in handling multiple database aggregations and pagination
I have a REST service(the Project uses django and DRF) which serves data from a MSSQL database. One of the models stored inside the DB are invcoies which looks like this: class Invoice(models.Model): id = models.IntegerField(primary_key=True) customer = models.ForeignKey('project_models.Customer', on_delete=models.CASCADE,related_name='invoices') material = models.ForeignKey('project_models.Material', on_delete=models.SET_NULL) quantity = models.FloatField() revenue = models.FloatField() invoice_date = models.DateField() I want to expose some aggregated data for these invoices per material like: Sum of revenue for the current year Sum of revenue for the past year Sum of revenue for the past year up to todays date (e.g. today is 2022-03-02, Sum would be from 2021-01-01 to 2021-03-01) To solve this I could execute a query with minimal aggregation(e.g.revenue sum per day) and iterate over the result set to create a list of entries which contains all necessary informations. However as there are lots of materials this solution can lead to performance issues. This problem would normally be solved by paginating the queryset. Seeing as I still fetch and calculate as well as iterate over all the data of the DB it seems to be not the best solution. Therefore my question is: what would be a the best approach to aggregate multiple data while still … -
How to restrict cache data from google search in Django project?
i am built a django project and i used redis cache in my project but if i type in google search bar cache : my site domain name google listing all my cache json object data i don't have idea how it is there any way to restrict ? Thankyou in advance. -
Sum of two calculated annotation in django
.annotate( waste=Sum("processings__chunks__waste"), completed_waste=models.Task.get_completed_waste_annotation(), tooling_time=Sum("processings__chunks__tooling_time"), completed_tooling_time=models.Task.get_completed_tooling_time_annotation(), processing_time=Sum("processings__chunks__processing_time"), completed_processing_time=models.Task.get_completed_processing_time_annotation(), total_time=F("tooling_time") + F("processing_time"), completed_total_time=F("completed_tooling_time") + F("completed_processing_time"), ) I've this annotate, the problem is in the last two fields total_time and completed_total_time, when one of the fields tooling_time, processing_time is None, I get None in both of the fields. -
How to show user's information (special ID, firstName, lastname) in another template after successfully form submission in Django
How to show user's information (special ID, firstName, lastname) in another template after successfully form submission in Django. I have a form to ask users information(general information, Education, experience) and I give random unique test_id. After user submitted form succesfully, I have to show his/her test_id to memorize. I didn't have an idea about view form. My solution is a bit stupid My model: class UserForm_uz(models.Model): test_id = models.CharField(default=random_string,max_length=5,editable=False,unique=True) rasm = models.ImageField(upload_to='media/rasmlar',null=True,blank=True) jobName = models.ForeignKey( Job, on_delete=models.CASCADE ) lastName = models.CharField(max_length=200) firstName = models.CharField(max_length=200) middleName = models.CharField(max_length=200,blank=True,null=True) birthData = models.DateField() nation = models.CharField(max_length=50,blank=True,null=True) My view: class FormAfterView(View): def get(self,request): obj = UserForm_uz.objects.all().last() test_id = obj.test_id firstName = obj.firstName lastName = obj.lastName return render(request,"formafter.html",{"test_id":test_id,"firstName":firstName,"lastName":lastName}) -
djagngo get all .objects.filter() with condtion
I Have a table Batch with many columns Column Type Comment id bigint(20) Auto Increment start_date datetime(6) NULL acerage double batch_health int(11) NULL stage varchar(100) NULL expected_delivery_date datetime(6) NULL current_pdd double NULL historic_pdd double NULL current_gdd double NULL historic_gdd double NULL sub_farmer_id int(10) unsigned NULL batch_status varchar(100) commodity_id int(10) unsigned NULL commodity_variety_id int(10) unsigned NULL farm_id bigint(20) NULL created_at datetime(6) created_by_id int(10) unsigned NULL updated_at datetime(6) updated_by_id int(10) unsigned NULL actual_produce double NULL actual_yield_per_acre double NULL expected_produce double NULL historical_yield_per_acre double NULL sop_adherence double NULL end_date datetime(6) NULL batch_median_health int(10) unsigned NULL batch_name varchar(200) NULL commodity_name varchar(200) NULL pending_tasks int(10) unsigned NULL pest_attack varchar(500) NULL when I trying to get the object from this table like this Batch.objects.filter(farm_id = farm_id, batch_status='completed') farm_id variable is already defined then I should all the data column for that Batch But I am not getting ALL all columns I am getting an only batch name as an output (2706) Papaya | 2021-03-18 (2707) Papaya | 2021-03-18 How can I get all the columns in dict ?? and so that I can use this in the filter of batchyield batch_id Is a foreign key in batchyield which is batch table ID and get batchyield all … -
how can I check that societies name contain city or locality name and update the society name?
I have data of societies in my database but there are some societies that contain city names and locality names. I want to check whether the society name contains the city name and locality name and remove them or update the society name. models\locality.py class Society(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. locality = models.ForeignKey('Locality', models.DO_NOTHING, db_column='localityId', blank=True, null=True, related_name='society_set') # Field name made lowercase. dot_com_database_id = models.IntegerField(db_column='dotComDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'societies' models\society.py class Locality(models.Model): name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(db_column='createdAt', auto_now_add=True) # Field name made lowercase. updated_at = models.DateTimeField(db_column='updatedAt', auto_now=True) # Field name made lowercase. city = models.ForeignKey('City', models.DO_NOTHING, db_column='cityId', blank=True, null=True, related_name='locality_set') # Field name made lowercase. connect_database_id = models.IntegerField(db_column='connectDatabaseId', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'localities' It will clear your doubts: Iterate through societies that do have names and for each society. If the issue of appending city & locality exists for the society. Remove city name & locality name from society's name and update society name. e.g. Society … -
ImportError at libGL.so.1: cannot open shared object file: No such file or directory
I was using python-poppler 0.2.2 in a django project. It worked in Local Server but when it is hosted in Azure Linux based app service, it is getting a error like ImportError at libGL.so.1: cannot open shared object file: No such file or directory Tried installing apt install libgl1-mesa-glx, sudo apt-get install python3-opencv -
Render formset in template django and create table
How to create this table used modelformset_factory Table: In view I create standard formset: def studentTeacherFees(request, *args, **kwargs): ... FeeFormSet = modelformset_factory(Fee, fields=('is_paid',), extra=0) ... In template 'my_template.html' i try used this: ... <form class="form validate-form" id="Career" method="POST" enctype="multipart/form-data"> <span class="form-title"> {% translate "Info" %} </span> {% csrf_token %} <legend class="border-bottom mb-4">{% translate "Update Info" %}</legend> <ul> {{ formset.management_form }} {% for form in formset %} {{ form.id }} <li> {{ form.instance.student.get_full_name }} {{ form.is_paid }}</li> <br> {% endfor %} ... -
How to test uploadfile in django
I have an uploadform and I want to test it. But there is a problem. def test_if_can_upload_file(self): with open('app_blog/tests/test.txt') as file: self.client.post(reverse('csv_blog'), {'attachment': file}) test_file = file.read() self.assertEqual(test_file, 'test file') When I test it, there is an error: self.assertEqual(test_file, 'test file') AssertionError: '' != 'test file' + test file Why is my file shown like it is empty? Actually it is not empty.Or maybe I test my form in a wrong way? form class UploadBlogForm(forms.ModelForm): file = forms.FileField() class Meta: model = Blog fields = 'file', view def upload_blog(request): if request.method == "POST": upload_file_form = UploadBlogForm(request.POST, request.FILES) if upload_file_form.is_valid(): blog_file = upload_file_form.cleaned_data['file'].read() blog_str = blog_file.decode('utf-8').split('\n') csv_reader = reader(blog_str, delimiter=":::", quotechar='"') -
Error opening files with Diacritic letters
I use {% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}">{{i.file.name}}</a></p>{% endfor %} To open attached files to my post. Problem is, when I try to open PN/pravokutne_pločice.jpg I get error: “C:\inetpub\media\PN\pravokutne_plo” does not exist Raised by: django.views.static.serve I figured out it's because of diacritic letters. On my 'base.html' I have . Django setting 'LANGUAGE_CODE = 'hr-BA''. Is there something I can add to be able to open those files which names contain diacritic letters? -
Django static files are broken
I'm trying to add a background picture to the hero section in Django, But whenever I open that URL: http://127.0.0.1:8000/static/img/bg.png it says 'img\bg.png' could not be found I also attempted to open other urls, but they are broken. #settings STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = 'E:\coding\django\pawnhost\static' #urls from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include("core.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #html <section class="Hero"> ... </section> #CSS (base.html) {% load static %} <style> .Hero { background-image: url({% static 'img/bg.png' %}); } </style> -
Flitering django queryset based on ManyToManyField
In my Request model, there is a field requested_to which is a ManyToManyField requested_to = models.ManyToManyField(OrganizationUser) I want to filter queryset of Request model where a organization_user is not in requested_to -
DJango Query Issue
I am making a Blog website where my blog post model is related to User model using many-to-many relation for the likes. Now I am querying the DB for getting the likes count for each specific post. This is the Query that I have written -> posts = Post.objects.select_related().prefetch_related('images_set','comments_post').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now When I see the actual Query that is being made to the DB and the result It all looks fine and the No of queries are also made to DB are fine. I am getting a column named 'LIKES__COUNT'. Now I am unable to use this column name in my template. Can anyone help me out on how to use this in the template? This is the result That I am getting from the DB. -
How to switch wagtail homepage depending on user logged in status
I have previously been using path("", include(wagtail_urls)) for my home_page url which displays the template at home/home_page.html correctly I wish to however display different pages depending on whether a user is logged in or not so have changed this to: def logged_in_switch_view(logged_in_view, logged_out_view): '''switches views dependedn on logon status''' def inner_view(request, *args, **kwargs): if request.user.is_authenticated: return logged_in_view(request, *args, **kwargs) return logged_out_view(request, *args, **kwargs) return inner_view urlpatterns = [ path("", logged_in_switch_view( TemplateView.as_view(template_name="home/home_page.html")), TemplateView.as_view(template_name="home/not_authenticated.html")), name="home"), ] With this approach (directly specifying the template rather than using wagtail_urls) the home page does not display correctly when logged in, in that all the wagtail tags in the html e.g. the blog posts are not displaying home_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block content %} <main class="container"> {% for post in page.blogs %} {% with post=post.specific %} <div class="col-md-8 mx-auto px-auto"> <div class="row border rounded overflow-auto flex-md-row mb-4 shadow-sm position-relative "> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong> <div class="mb-1 text-muted">{{ post.date }}</div> <h3 class="mb-0">{{ post.title }}</h3> <p>{{post.intro}}</p> </div> <div class="col-auto my-auto py-2 px-2 d-none d-lg-block"> <a href="{% pageurl post %}" class="stretched-link"> {% with post.main_image as main_image %}{% if main_image %} {% image main_image min-250x250 …