Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing request.user to custom save method gives error
In my views.py: (...) count.save(request_user = request.user) models.py: class Count(models.Model): def save(self, *args, **kwargs): print(kwargs['request_user']) if self.accesses.count() == 0: AccessRecord.objects.create(user = kwargs['request_user'], count = self) super().save(*args, **kwargs) This gives me a key error: KeyError: 'request_user'. Why does it happen? The print() statement works fine and shows the user object. The problem can't be on the AccessRecord model because i have other files creating objects and none of them fail. Is there a problem on passing the user over kwargs? -
Can i render a view while task currently executing?
Let's imagine I have this view in views.py: def wait_and_print(request): print(5) time.sleep(90) return render(request, 'view.html') I want to display view.html before the time.sleep(90) task completes. I've read about synchro-asynchro tasks but I can't seem to understand quite well how to perform this operation. Thanks, -
Pass a static asset to an include in Django Templates
I want to pass a static asset to an include i'm using. The include is formatted like so: {% include "image_set.html" with img_source=image %} and I want to pass a static asset: {% static 'background.png' %} to the image source, but I cant nest tags. -
DJANGO - models - inheritance structure for 3 level model for "equipment management" app
I'm trying to built an "equipment management" app. The app should have 3 layers/views as follow: Layer 1: Equipment type, describing the types of equipment I own, for example: Chainsaws Welding Machines Asphalt cutters and so on... This is the model I've already created: class EquipmentType(models.Model): type = models.CharField(max_length=100, unique=True) date_posted = models.DateTimeField(auto_now_add=True) image =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type') LAYER 2: SINGLE ITEMS - For every equipment type I can have multiple items. for example for Chainsaws I will have a corresponding list view as: LIST OF CHAINSAWS: Chainsaw 1, brand x, model 101 Chainsaw 2, branx x, model 200 Chainsaw 3, branx x, model 200 Chainsaw 4, brand y, model 445 and so on.... With the corresponding model: class EquipmentItem(models.Model): type =models.ForeignKey(EquipmentType, on_delete=models.SET_NULL, null=True) brand =models.CharField(max_length=100) model_type =models.CharField(max_length=100) registration_number =models.CharField(max_length=100) active =models.BooleanField(default=True) Finally Layer 3: Where the problem begins. Layer 3 Should be EquipmentSpecs, and, as the name suggests, it should render back the technical specs for every equipment type. Certainly we could start the model with: class EquipmentSpec(models.Model): type = models.OneToOneField(EquipmentType, on_delete=models.SET_NULL, null=True) Because for every type of equipment (say chainsaws) I want one and one only spec model. At the same time the model defined for specs can have multiple … -
Django 1.11: disable cache for authentificated users
We have a legacy application written in python 2.7 and django 1.11 (and no resources to migrate). Also it uses grappelli for authorization. We tried to add Edit links for some pages (each of the pages displays detailed info on a Round object) that should be visible only for authorized users with rights to edit a Round ( APPNAME | round | Can change round in the grappelli web interface). In the template, the permission is checked like so: {% if perms.round.can_change_round %} &emsp;<a href="{{link_to_change_round}}" class="stuff-only-link">{% trans 'Edit' %}</a> {% endif %} The problem occurs when the following events take place in a short time interval: A user which has the permission to edit a Round visits a page - and sees the Edit link. A user which has no permission to edit a Round (e.g. anonymous user) visits the same page - and also sees the link! Revelant settings (settings.py) are: CACHES = { 'default': { # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } SOLO_CACHE = 'default' SOLO_CACHE_TIMEOUT = 5*60 When I change cache to dummy, the problem disappears. Thus, it seems to be an obvious solution to totally disable caching for authorized users. To be more precise: a) If … -
Querying One-To-Many Relationships in Django and then aggregate
I am learning Django on a peculiar project whereby I am tracking football/soccer player statistics to view in a bootstrap Dashboard. Any help would be very much appreciated. I am able to loop over each player, I am also able to loop over their history (separate model) but I am unable to group each player to their history and display on one page while doing other calculations. I am also unable to group players by their club or category. There are 3 models: Players, Category, Club, Timestamp. Each unique player has a one-to-many relationship with Category, Club, and Timestamp. Each player will eventually have millions of timestamps which will act as a history for the player's performance (score, value, etc). I'd like to easily work out things like: Did the player X score increase compare to 24hr/7 days/30 days ago? List all players and their timestamps from category (or team) X. What is the total score of each player in category X (based from the latest timestamp record) I've started with = Player.objects.all() or Timestamp.objects.all().order_by('-timestamp') but I am unsure how to do set this up so that I can do the above, within one view. Models: class Category(models.Model): name = … -
django celery not sending data
I'm trying to create a task that sends an email to a user automatically when the manu_date in my model is due in 7 days. I'm using celery tasks to for this, however, I'm not receiving any email, I have some orders in my database with due manu_date in coming 7 days. After I run celery -A dash beat -l info , I'm getting writing entries..... and Scheduler: Sending due task celery_test (accounts.tasks.check_for_orders) requests. from celery import shared_task from time import sleep from django.core.mail import send_mail from celery.decorators import periodic_task from .models import Order @shared_task def check_for_orders(): orders = Order.objects.all() now = datetime.datetime.utcnow().replace(tzinfo=utc,second=00, microsecond=00) week_old = now - datetime.timedelta(week=1) for order in orders: if order.manu_date.date() == week_old.date(): send_mail('Manufacturing Reminder', '{{Order.id}} is due {{manu_date}}', 'dummyguy1680@gmail.com', ['dummyguy1680@gmail.com'] ) return None from __future__ import absolute_import, unicode_literals from django.conf import settings from celery.schedules import crontab import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dash.settings') app = Celery('dash') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') app.conf.beat_schedule = { … -
Updating fields like "quantity" with F() expressions on django administration page
class Product(models.Model): name = models.CharField(max_length=255, default="Product's name") price = models.PositiveIntegerField(default=0) quantity = models.PositiveIntegerField(default=0) def __str_(self): return self.name How can i make the update for quantity field on django administration page using the += operation or F() expression rather than replacing the value? I can probably make another page with a form with the same model and have it's own dedicated "update" view. but i'm wondering if it can be done on the admin page instead -
Django, how to filter a form based on another one
I have the following django app structure: models.py class CodiceCommessa(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) class Informazioni_Generali(models.Model): codice_commessa= models.CharField('Codice', unique=True, max_length=5) data_registrazione=models.DateField() forms.py class CodiceCommessaForm(forms.ModelForm): class Meta: model = CodiceCommessa fields = "__all__" views.py def altri_costi_commessa(request): cod=[] if request.method == 'POST': year = request.POST['year'] if request.method == 'POST': form = CodiceCommessaForm(request.POST) if form.is_valid(): cod = form.save() else : form = CodiceCommessaForm() In my template I have set the form. All works, but I want that, when I select a year, automatically django show me only the codice_commessa that match the year in the field data_registrazione. Is it possibile to get it? -
Correct way to "Specifying where the content will be inserted" in django el-pagination
in home_page.html <section class="news_list"> {% paginate 2 news_list %} <ul id="wookmark1" class="tiles-wrap">> {% include page_template %} </ul> <div class="load-more"> {% show_more '<button type="button">Load More Articles</button>' '' %} </div> </section> {% endblock content %} {% block extra_js %} <script type="text/javascript" src="{% static 'el-pagination/js/el-pagination.js' %}"></script> <script> $.endlessPaginate({ contentSelector: '.tiles-wrap', }); </script> {% endblock %} in articles.html {% show_current_number as num %} {% if request.is_ajax %}{% paginate 2 news_list %}{% endif %} {% for article in news_list %} <li {% if num > 1 %}style="opacity:0;{% endif %} "> <a href="{% pageurl article %}"> {% if article.thumb_image %} {% image article.thumb_image width-400 %} {% else %} {% image article.image width-400 %} {% endif %} <h2 class="news-list-title page-{{ num }}">{{ article.title }}</h2> <p class="list-excerpt">{{ article.excerpt }}</p> </a> </li> {% endfor %} It works correctly until the last page, then it shows the show more button without any more pages and when u press it javascript throws 404 error at http://127.0.0.1:8000/?page=6&querystring_key=page -
How can i implement reset password using OTP in django?
I'm trying to implement password resetting option in my django project. I found django's inbuilt password resetting functionality in which the reset mail included a link which contains uidb64 and token . But i want to include an OTP instead this link in the password reset mail. Any help would be appreciated. -
getattr(): attribute name must be string in django?
from Django.db import models # Create your models here. class postingmodel(models.Model): Post_Title=models.CharField(max_length=20) Post_Content=models.TextField(max_length=500) datetime=models.DateField(auto_now_add=True, blank=True) img=models.ImageField(upload_to='static', height_field=400, width_field=400) Here, I created models Django-admin couldn't save that post and show error like this getattr(): attribute name must be a string in Django -
Why do I get "Failed to load resource: the server responded with a status of 404 ()" of my CSS file in Django?
So I have this Django application perfectly working in Ubuntu server, but keep getting the error above. WHAT'S REALLY STRANGE is that it started to fail loading at some point. So (though this may be a vague expression) the upper part of my css file, which was written some time ago is well-applied to the page. However from some point in the file, nothing is applied and I started to get the error. Let me show you the code. everyday.css #today { font-size: 30px; font-weight: bold; } .keywordInputs { width: 125px; background-color: #f6f5f1; /* padding-left: 10px; */ } .keywordInputs:focus{ background-color: #f6f5f1; border: #9300d3 solid 1px; } .kw12 { margin-right: 20px; } .everyday-img { width: 100%; height: auto; } .img-col { padding: 2.5px; } .calendar-img { width: 50px; height: auto; } So in the code above, when the page is loaded, the settings up until .kw12 is applied, but the rest down below isn't. I swear the path is 100% correct, I've done python manage.py collectstatic command, but I keep getting the error. What do you think is the problem? For your info, this is my template. {% extends 'main/base.html' %} {% load static %} {% block css %} <link rel="stylesheet" … -
Cannot install requirements for the django on centos
Stuck on installing the requirements for the Django project. Below is the output I am seeing. Tried to install mysql and it gives the same output Installing collected packages: mysqlclient, mysql, boto, future, django-ses, django-appconf, django-ipware, django-axes, Pillow, jmespath, docutils, python-dateutil, botocore, s3transfer, boto3, django-jsonfield Running setup.py install for mysqlclient ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-rw907hj3/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-a268bv6l-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/MySQLdb gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(2,0,1,'final',0) -D__version__=2.0.1 -I/usr/include/mysql -I/usr/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-rw907hj3/mysqlclient/setup.py';f=getattr(tokenize, … -
How not to set always DJANGO_SETTINGS_MODULE?
I have project with difference settings for prod and local how to set default settings(local for example). So that after some time I go to the project and I would not have to set the settings again -
Django redirect doesnt work after posting JSON data
Return redirect doesn't work in an else statement after receiving json data. The same redirect works in an other if statement. In the terminal I can see the GET request for the url I want to redirect to, that is why I found this strange.The print statement works perfectly in else, only redirect fails. My code so far: views.py (please let me know if the other views are necessary to answer the question) def data_type_error_handling(request): '''handles all the possible choices after data_type_errors ''' if '_skip' in request.POST: return redirect('data_validation') elif 'first_load' in request.session or '_refresh' in request.POST or request.method == 'GET': print("data_load vagy refresh") error_list = request.session['error_list'] errors = json.dumps(error_list, indent=4, sort_keys=True, default=str) if 'first_load' in request.session: del request.session['first_load'] return render(request, "upload/data-type-correction.html", {"error_list": errors}) else: raw_data = request.body.decode('utf-8') data = json.loads(raw_data) print(data) return redirect('data_validation') return redirect('data_validation') works in the first if statement, but not in else, it stays on the same page where I clicked on the button. urls.py from django.urls import path from . import views urlpatterns=[ path('data-upload', views.data_upload, name='data-upload'), path('upload-failed', views.data_upload, name='upload-failed'), path('upload-successful', views.data_upload, name='upload-successful'), path('data-type-correction', views.data_type_error_handling, name ='data-type-correction'), path('data-validation', views.data_validation, name ='data_validation'), ] data-type-correction.html {% extends "base.html" %} {% block title %} Data type error correction {% … -
Django rest framework unique together error message not displayed anymore
I worked with django rest framework a lot and everything worked fine until today. The same function suddenly returns something different. I have a unique together on my client model with name and company. I recently created a mixin called AutoCompany which automatically sets the company on the client. My client model: class Client(AutoCompany): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=155) description = models.TextField(blank=True) class Meta: constraints = [ models.UniqueConstraint(fields=["name", "company"], name="Name and company"), ] AutoCompany class AutoCompany(models.Model): company = models.ForeignKey("company.Company", models.DO_NOTHING) def save(self, *args, **kwargs): company = apps.get_model("company.Company") try: self.company except company.DoesNotExist: self.company = get_request().user.company self.after_company_set() return super().save(*args, **kwargs) def after_company_set(self): pass class Meta: abstract = True So previously when I created a client with the same name for the same company I got a 400 response with this error: The fields name, company must make a unique set. But now I just get a 500 response with a python error. It seems like the error is not caught anymore. Now I just get: django.db.utils.IntegrityError: (1062, "Duplicate entry 'test-cafd0ed10f9f4865a1d56abb67daa831' for key 'Name and company'") Does anybody know why this change occurred? -
uploading csv file django using a form
I am working on a school management project and want to upload a CSV file and save it either by overriding the current data or updating it in the database. but it's not being added in the database. Also, I like to add more fields so if possible using dynamic(i.e. by loops) so I don't have to change it later. models.py class Student(models.Model): registration_number = models.CharField(max_length=200, unique=True) firstname = models.CharField(max_length=200) surname = models.CharField(max_length=200) date_of_birth = models.DateField(default=timezone.now) current_class = models.ForeignKey(StudentClass, on_delete=models.SET_NULL, blank=True, null=True) date_of_admission = models.DateField(default=timezone.now) parent_mobile_number = models.CharField(max_length=15) address = models.TextField() class StudentBulkUpload(models.Model): date_uploaded = models.DateTimeField(auto_now=True) csv_file = models.FileField(upload_to='students/bulkupload/') forms.py class StudentBulkUploadForm(forms.ModelForm): class Meta: model = StudentBulkUpload fields = ("csv_file",) views.py def uploadcsv(request): if request.method == 'GET': form = StudentBulkUploadForm() return render(request, 'students/students_upload.html', {'form':form}) # If not GET method then proceed try: form = StudentBulkUploadForm(data=request.POST, files=request.FILES) if form.is_valid(): csv_file = form.cleaned_data['csv_file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'File is not CSV type') return redirect('students:student-upload') # If file is too large if csv_file.multiple_chunks(): messages.error(request, 'Uploaded file is too big (%.2f MB)' %(csv_file.size(1000*1000),)) return redirect('students:student-upload') file_data = csv_file.read().decode('utf-8') lines = file_data.split('\n') # loop over the lines and save them in db. If error, store as string and then display for line in lines: fields … -
Mozzilla Pontoon on Google Compute Engine Invalid HTTP_HOST header
I'm triyng to install Mozzilla Pontoon on a Google Compute Engine instance. I'm running it using docker-compose. The problems comes when I try to build the project with the following command: sudo make build SITE_URL=IP Where IP is the external ip address of the Compute Engine instance. I get the following error: the image has been taken from my localhost where I'm doing the tests. In the locahost I put as IP address 127.0.0.1 Any suggestion on how to properly configure the SITE_URL??? Cheers -
ModuleNotFoundError: No module named 'name_of_project' in django when running on herohu
I am trying to host my django application on heroku for the first time and i am successfully able to deploy it but i am facing an application error and is showing me this image of my heroku webpage and when i check the logs using heroku logs --tail its showing me this error log details. In it what it shows ModuleNotFoundError: No module named 'twitter_project' here 'twitter_project' is the name of my project. I did pip install django-heroku and pip install gunicorn and imported import django_heroku at the top of settings.py and added django_heroku.settings(locals()) at the end of settings.py, added a Procfile which contains this web: gunicorn twitter_project.wsgi and the requirements.txt is also complete and have added django-heroku==0.3.1 and gunicorn==20.0.4 as well, I don't know what I am doing wrong. I don't if I have something wrong with my static files. -
How to restrict django's PasswordResetView from redirecting?
Hi I am using Django to make an web app. I wanted to know how can I stop Django's built in PasswordResetView from redirecting to PasswordResetDoneView once the email is inputted by the user. I just want to show a small popup in the bottom of the screen saying email has been sent. Well that I can do with js but I am not able to stop from redirecting hence making the popup useless. I tried the success_url to none and "" but it throws an error saying improperly configured url. Please answer if you know how to do this -
How to change content type in django restframework api from json to multipart/form-data or form data
How to change content type in django restframework api and how to change the set content type in serializer and viewset for multipart/form-data or form data from rest_framework import serializers,routers from .models import * from django.contrib.contenttypes.models import ContentType -----------------------Serializer---------------------- enter code here class filedataSerializer(serializers.ModelSerializer): class Meta: model=filedata fields='all' -----------------------Viewset-------------------------- enter code here class filedataViewsets(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset=filedata.objects.all()enter code here serializer_class=filedataSerializer -
CSS synax not working after json code added - VSCode
I used these lines of code to get back HTML syntax but now CSS syntax is not working. "files.associations": { "**/*.html": "html", "**/templates/**/*.html": "django-html", "**/templates/**/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "emmet.includeLanguages": { "django-html": "html", }, Any suggestions -
How to add subdoain in google cloud DNS?
I have a compute engine running in google cloud. I linked this compute engine with a domain like example.com but I want to host another web apllication on the same compute engine and access it via subdomain like app.example.com, so can anyone tell me how I can link or add a new subdomain to same compute engine. -
How to display Recent view product in Django?
I am new to Django, and I am looking for this answer. Please let me know how I can solve this issue. Suppose, if a user visits on my website and he clicks on any product then that product should be shown in recent view on his PC/Laptop, suppose if a user exit from website and after 2-3 hours he/she visit again then previous views product should be shown in his recent viewed product. and I want to do this without logging in a user, please let me know how I can do it. if anybody has code for this please submit here or explain the process.