Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JavaScript tag at the end of a base.html file structure
I am developing a website using Django. I am using Template Inheritance in order not to repeat code (like navbars for example) in several html child files. Part of the code I do not want to rewrite is that where I embed JavaScript: <script src="whatever"></script> It is also known that this code is better placed at the end of the body in a .html file, since this would avoid locking additional resources from being downloaded more quickly. So my question is: How should I do to tell my base.html template that the script code shall be at the end of the body in every child html file? -
How to get entry using primary key from another model in Django?
I have 2 models, "Listing" and "Watchlist". Watchlist has a primary key that is referencing Listing. For every "Watchlist" object (that has the same user X) I want to get the according "Listing" entry in form of a QuerySet. I really struggle with this, because I don't know how to incorporate a for-loop into a queryset request. ``` class Watchlist(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="watchlists") user = models.ForeignKey(User, on_delete=models.CASCADE) -
How can i call django view from jQuery Datatables?
I'm using datatables and I'm trying to add some buttons with actions to them. I want to call django view function, but I'm not sure how to achieve this inside of jQuery Datatables. When I have django templates it's clear I can just say <a href="{% url 'feedback:useredit' user.id %}" class="btn text-secondary px"-0> <i class="far fa-edit fa-lg"></i> and this redirect me to "useredit" view function in django. But this don't work without the django template and inside of jQuery's Datatables. Can you guys give me some hint how to achieve this? $(document).ready(function() { var data; fetch("http://192.168.2.85:8000/fetchapi/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: data.employees, deferRender: true, scrollY: false, scrollX: false, scrollCollapse: true, scroller: true, "columns": [ { data: "id" }, { data: "first_name" }, { data: "last_name" }, { data: "email" }, { "data" : null, render: function ( data, type, row ) { return '<button class="btn-view" type="button">Edit</button>'; } }, { "data" : null,render: function ( data, type, row ) { return '<i class="fa fa-plus-circle" aria-hidden="true"></i>'; } }, ], "order": [[1, 'asc']] } ) }) } ); this is the whole jQuery code, but I think I need to implement the url to … -
how to make query from datetime filed smaller than current datetime
in my django website i need to make query based on datetime filed that are smaller than now this is my query in views.py : meetings=Meeting.objects.filter(date_time__lt=datetime.now()).filter(Q(members_email__icontains=str(request.user.email))|Q(host=request.user)) and this is datetime filed in models.py : date_time = models.DateTimeField(null=True,blank=True) but it returns nothing i don't know how to solve this problem any suggestion? -
Im not receiving the email verification in order to activate the user created
Please I've created an authentication system where a user can login with both username and email address. The account is deactivated when it is created. I want the user to confirm his email before the account is activated. I used the django email verification but although the user is created successfully, I dont receive the email. Please help. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) backend.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.db.models import Q UserModel = get_user_model() class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get( Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) except MultipleObjectsReturned: return User.objects.filter(email=username).order_by('id').first() else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None forms.py from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django import forms from django.dispatch import receiver from django.db.models.signals import pre_save from .models import CustomUser from django_email_verification import send_email from django.views.generic.edit import FormView class RegisterForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'password1', 'password2') @receiver(pre_save, sender=CustomUser) def set_new_user_inactive(sender, instance, **kwargs): if instance._state.adding is True: instance.is_active … -
Stop Django background-task from deleting completed_task model
On django-background-tasks==1.1.11 (Django==2.2, Python 3.6.9), I have this problem where everytime I run python manage.py migrate, the table background_task_completedtask gets deleted. This breaks my background tasks. So far I have found a way to reverse it, as it is a separate migration from the initial one, meaning I can just python manage.py migrate background_task 0001_initial to restore it, but this does mean it will still be removed next migration. Any ideas for a more permanent solution? -
Django crud operations for cronitor column
I need to edit or add rows in database using django where the time column is cronitor(eg: 30 3 * * *) string element, and I want to create a UI for this cronitor expression management more easy way. Like options like Day , month,year user can easily do the changes in cronitor expression in a drop down menu. -
Django search only gets saved locally
So I have a website where I compare clothing from multiple sites (https://www.casualspotter.com/). I recently implemented a search function. But the searches only get saved to my database (postgresql) when I test locally. Am I missing something? Model: class Search(models.Model): search = models.CharField(max_length=500) created = models.DateTimeField(auto_now=True) def __str__(self): return '{}'.format(self.search) class Meta: verbose_name_plural = 'Searches' views.py: from . import models def new_search(request): search_item = models.Search() if request.method == 'POST': #print(request.POST) search_item.search = request.POST.get('search') search_item.save() form in base.html: <div class="navbar" id="searchcontainer"> <form method="post" action="{% url 'new_search' %}" class="row search-input" id="demo-2" autocomplete="off"> {% csrf_token %} <input style="color: white" class="col-lg-12" type="search" name="search" placeholder="Search.."> </form> </div> urls.py: urlpatterns = [ path('new_search', views.new_search, name='new_search') ] -
How can you output something when login is completed? Django allauth
I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django allauth with their default themes? I've tried doing: {% if request.user.is_authenticated %} But the problem with this code is that the message appears each time, even when you reload the page. -
Handling static data with webserver but use Django file field
I have a model with an FileField type column. On calling API, I perform necessary checks and then create the model object. As per the documentation: Most larger Django sites use a separate Web server – i.e., one that’s not also running Django – for serving static files. This server often runs a different type of web server – faster but less full-featured. The documentation says I serve static files using a web server. What to be done for receiving static data is uncommented. What should be my approach? Should I use the Django app server and upload files? Or is there any way for my webserver to handle this? What is the scale at which a processor/memory load difference will become significant? Serving static content through Django involves a lot of overhead (loading the static file, processing python bytecode, passing through WSGI, etc) that is totally unnecessary for static content. (Reference) P.S: I use Nginx and Gunicorn. -
Installing django requirements on Ubuntu 20.10 crashes on uwsgi
I have huge problem installing django project on ubuntu. I was trying to use conda, venv but still get error which occurs while running setup.py install for uwsgi ... error. I really know that I should attach error here, but I think it's too long, so Im gonna upload it on pastebin: https://pastebin.pl/view/7eb0d970 If somebody could take a look and provide some tips I will be very grateful -
httplib2 :- argument should be integer or bytes-like object, not 'str'
I am using Google Indexing API, and I am getting this error argument should be integer or bytes-like object, not 'str' I am implementing the API on the Django server when I run it on my local machine it runs just fine. but when I put it on pythonanywhere it is giving me the above error. I don't know what's the reason for this error. here is the function def demo(request): context = {} if request.GET: link = request.GET.get('link') key = request.GET.get('key') if link and key: context = { 'link': link, 'key': key, } try: key = json.loads(key) except: return render(request, 'google_api_demo/index.html', context) scope = [ "https://www.googleapis.com/auth/indexing" ] endpoint = "https://indexing.googleapis.com/v3/urlNotifications:publish" credentials = ServiceAccountCredentials.from_json_keyfile_dict(key, scopes=scope) http = credentials.authorize(httplib2.Http()) content = bytes(str({ "url": f"{link}", "type": "URL_UPDATED", }), encoding='utf-8') response, content = http.request(endpoint, method="POST", body=content) context['response'] = response context['content'] = content return render(request, 'google_api_demo/index.html', context) return render(request, 'google_api_demo/index.html', context) -
How can i show data of a object attribute in html table?
I have a object attribute in a table with one attribute(quantity) which show the number of a product in a store. To show the data of that object in oracle a create a function in body which is getvalue() . The function works nice in oracle and everything, but i cant use that function when i need to display the data of that object in a website. cursor.execute("SELECT rednibroj, brojfakture, quantity, cena, pdv ,napomena FROM stavkafakture" This is in django that im executing this query, the data of quantity comes like this: <cx_Oracle.Object MASTER.QUANTITYat 0x41642e50> Because quantity is the name of the object. Does anyone know how can i get the data of quantity in html table? -
Django admin changelist view title
How can I pass filter value to change list view title? I have admin page for reports, and I want to store date in the title, so it looks like this : "Reports summary for day 24-01-2021" and I want to get date from list filter reports__report_date class AdminReportsProxy(admin.ModelAdmin): """Admin model, that creats site of reports summary""" model = ReportsProxy actions = None search_fields = [ "first_name", "last_name", ] list_display = [ "get_salesman", "get_number_of_meetings_today", "get_number_of_meetings_tomorrow", "get_number_of_sales", "get_number_of_recommandations", "get_net_sales", "get_report_date", "edit_report", ] list_filter = [ ("reports__report_date", DateRangeFilter), NetSalesOrder, ] def changelist_view(self, request, extra_context=None): extra_context = {'title': f'Reports summary for day:{}'} return super(AdminReportsProxy, self).changelist_view(request, extra_context=extra_context) -
How to write CSV file to zip on the fly
def download_csv(self, prepared_data): file_name = self.get_file_name(self.request.query_params.get('model'), 'csv') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) writer = csv.writer(response) writer.writerow(prepared_data.get('labels')) for data in prepared_data.get('data'): writer.writerow(data) return response This is the original code for extracting data from the website in CSV format. Now I need to add some limitations and if the limit is exceeded create a zip file containing CSV files. For example, if the limit is 10 and I have 23 rows of data, a zip file will contain 3 CSV files. I am trying to implement this code: def download_csv(self, prepared_data): file_name = self.get_file_name(self.request.query_params.get('model'), 'csv') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) from io import StringIO limit = 2 if len(prepared_data.get('data')) > limit: temp_file = StringIO() comp_file = zipfile.ZipFile(temp_file, 'w') for _ in range(int(len(prepared_data.get('data'))/limit)): writer = csv.writer(response) writer.writerow(prepared_data.get('labels')) for data in prepared_data.get('data'): writer.writerow(data) comp_file.writestr(data=writer, compress_type=zipfile.ZIP_DEFLATED) comp_file.close() writer = csv.writer(response) writer.writerow(prepared_data.get('labels')) for data in prepared_data.get('data'): writer.writerow(data) return response but it fails with the error "path should be string, bytes, os.PathLike or integer, not _csv.writer" All I need to accomplish is, to get CSV files to write to zipfile. I'd be sincerely grateful for any help or hint. Thanks -
deploying with django-background-tasks
I ran into an issue when deploying my django app using django-background-tasks. I have a tasks.py file which has some functions with a @background decorator and I call them with the schedule settings from the PROJECT urls.py. After deploying I want to start the processing of the tasks by: python3 manage.py process_tasks but get the following error message: 1235, "This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'" Googling let's me find that mariadb does not want this. Is there an other/better way to start the processing of the background tasks? -
TemplateDoesNotExist at, Source does not exist
I'm building a blog website using django. While trying to list the blogs by categories i get this error as TemplateDoesNotExist. Here's my directory stucture: blogs/models.py: class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(editable=False) def save(self, *args, **kwargs): self.slug = f'{slugify(self.title)}--{uuid.uuid4()}' super(Category, self).save(*args, **kwargs) def __str__(self): return self.title def blog_count(self): return self.blogs.all().count() class Blog(models.Model): title = models.CharField(max_length=150) content = models.TextField() publishing_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='uploads/', blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, related_name='blogs') def save(self, *args, **kwargs): self.slug = f'{slugify(self.title)}--{uuid.uuid4()}' super(Blog, self).save(*args, **kwargs) def __str__(self): return self.title blogs/views.py: class CategoryDetail(ListView): model = Blog template_name = 'categories/category_detail.html' context_object_name = 'blogs' def get_queryset(self): self.category = get_object_or_404(Category, pk=self.kwargs['pk']) return Blog.objects.filter(category=self.category).order_by('-id') def get_context_data(self, **kwargs): context = super(CategoryDetail, self).get_context_data(**kwargs) return context blog/urls.py: app_name = 'blogs' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('detail/<int:pk>/<slug:slug>', views.BlogDetail.as_view(), name='detail'), path('category/<int:pk>/<slug:slug>', views.CategoryDetail.as_view(), name='category_detail'), ] phleeb/setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Traceback: Traceback (most recent call last): File "E:\ProIde\1 - Django Developer Path\phleeb\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\ProIde\1 - Django Developer Path\phleeb\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "E:\ProIde\1 … -
How does Django generate constraint names in migrations?
I have a Django model which is using the Django unique_together constraint. class MyModel(models.Model): field_1 field_2 class Meta: unique_together = ("field_1", "field_2") At some point after this constraint was created on MyModel, a migration was created to rename MyModel to MyCoolModel. Some time after that the renaming migration was squashed into the original migration that created the constraint. Now where I previously had 2 migrations. create_my_model_with_constraint rename_to_my_cool_model I only have one: create_my_cool_model_with_constraint Later I want to adapt the existing unique_together constraint in line with the following model change: class MyCoolModel(models.Model): field_1 field_2 field_3 class Meta: unique_together = ("field_1", "field_2", "field_3") I create a migration for this change which has the following SQL output: BEGIN; ALTER TABLE "models_mycoolmodel" DROP CONSTRAINT "models_mycoolmodel_field_1_field_2_ca69545b_uniq"; ALTER TABLE "models_mycoolmodel" ADD CONSTRAINT "models_mycoolmodel_field_1_field_2_field_3_aedebc1b_uniq" UNIQUE ("field_1", "field_2", "field_3"); COMMIT; This change applies fine to my local db (which has been created since the migration squashing event), but when deployed to production the migration errors because the constraint "models_mycoolmodel_field_1_field_2_ca69545b_uniq" does not exist. Instead the same constraint is called models_mymodel_field_1_field_2_7d93nd0q_uniq. My question is what has caused the differing constraint names between my local env and production? My suspicion is that by squashing the table name change migration into the initial … -
Filter Objects that are related to an object by another relationship
class Shipping (models.Model): phone_number = models.CharField(max_length=14) email = models.EmailField() class Package(models.Model): name = models.CharField(max_length=30) supplier = models.ForeignKey( Supplier , on_delete=models.DO_NOTHING) to = models.ForeignKey(Shipping, default=None, on_delete=models.CASCADE ) I have these Django models and as you see every package has shipping(to) and a supplier who is a user. How can I filter Shipping objects that are related to the package with a specific supplier in my views? I want to be able to get all Shipping objects a supplier has ever send packages to. -
Setting calendar availability in Django [closed]
I received a coding assessment where I am to build a doctor appointment app. But I am having issues with one of the user stories: As a doctor, I can block off periods of availability in my calendar I don't know how to go about that, I have also checked various libraries, I couldn't wrap my head round it. Any idea how I can go about it? -
django-oauth-tookit Introspect
According to DOT documentation, to make sure the access token is a valid token in the auth server we have to make a 'POST' request like the following: POST /o/introspect/ HTTP/1.1 Host: server.example.com Accept: application/json Content-Type: application/x-www-form-urlencoded Authorization: Bearer 3yUqsWtwKYKHnfivFcJu token=uH3Po4KXWP4dsY4zgyxH What I don't understand is the difference between 'bearer' token and the 'token', any clarification on this? I tried making the call using Postman but it always shows: active: false. -
Django app getting server error 500 on local host when Debug = False
My django app works properly (without any errors) when Debug = True in settings.py, but when I switch it to Debug = False I get Server Error (500). Plus I get: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. http://127.0.0.1:8000/favicon.ico 404 Not Found My settings.py file: """ Django settings for zeynab_web project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku import dj_database_url from decouple import config import cloudinary_storage # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '---' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False import logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': … -
How to get postgress username in pghistory event table in django-pghistory?
I am using django-pghistory 1.2.0 to keep my changes using postgres triggers. It works fine for CRUD operation for both ORM and raw sql. My model: @pghistory.track( pghistory.AfterInsert('after_insert'), pghistory.AfterUpdate('after_update'), pghistory.BeforeDelete('before_delete'), obj_fk=None ) class TestModel(models.Model): int_field = models.IntegerField() char_field = models.CharField(max_length=16) My event table "testmodelevent": int_field char_field pgh_id pgh_created_at pgh_label id pgh_context_id 1 | c1 | 1 | 2021-01-26 11:33:32 | after_insert | 22 | I pghistory_context table, the metadata column contains value of the django application user like this. id created_at updated_at metadata 96885fd7-0d9b-4560-99fa-f87b3166de89 | 2021-01-26 12:07:09 | 2021-01-26 12:07:09 | {"url": "/lapp/test-model", "user": 1} Apart from that I also want to add pgh_username column to my event table "testmodelevent" which will be the username of my postgres database. int_field char_field pgh_id pgh_created_at pgh_label id pgh_context_id pgh_username 1 | c1 | 1 | 2021-01-26 11:33:32 | after_insert | 22 | | <my-postgres-db-username> How could i achieve this? -
After deploying my Django App I am getting error code=H10?
After deploying my django add I am getting error. Everything was successful but when I try to open my site http://blogs2read.herokuapp.com/ it gives error. my github repo - https://github.com/AdityaKomawar/blog-app My error log after running heroku logs --tail 2021-01-26T08:50:13.916191+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-01-26T08:50:13.916192+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-01-26T08:50:13.916192+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-01-26T08:50:13.916192+00:00 app[web.1]: File "/app/blog_project/wsgi.py", line 16, in <module> 2021-01-26T08:50:13.916193+00:00 app[web.1]: application = get_wsgi_application() 2021-01-26T08:50:13.916193+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2021-01-26T08:50:13.916193+00:00 app[web.1]: return WSGIHandler() 2021-01-26T08:50:13.916194+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ 2021-01-26T08:50:13.916194+00:00 app[web.1]: self.load_middleware() 2021-01-26T08:50:13.916195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 40, in load_middleware 2021-01-26T08:50:13.916195+00:00 app[web.1]: middleware = import_string(middleware_path) 2021-01-26T08:50:13.916195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string 2021-01-26T08:50:13.916196+00:00 app[web.1]: module = import_module(module_path) 2021-01-26T08:50:13.916196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-01-26T08:50:13.916196+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-01-26T08:50:13.916197+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-01-26T08:50:13.916197+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-01-26T08:50:13.916197+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2021-01-26T08:50:13.916198+00:00 app[web.1]: ModuleNotFoundError: No module named 'whitenoise.middlware' 2021-01-26T08:50:13.919553+00:00 app[web.1]: [2021-01-26 08:50:13 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-01-26T08:50:14.031329+00:00 app[web.1]: [2021-01-26 08:50:14 +0000] [8] [ERROR] Exception in worker process 2021-01-26T08:50:14.031330+00:00 app[web.1]: Traceback (most … -
Pynetdicom with Tkinter or Django
I was wondering if someone could give me some pointers on how I might be able to incorporate pynetdicom with Tkinter or Django. As a bit of a newbie I'm in over my head on this, but thought it would be fun to see this project come to life, I just don't know how/where to start. I've used the basic examples from Pynetdicom and am able to use the C-FIND function connecting to Orthanc Server which prints back the Metadata. I've also used C-GET and have imported test dicom exams to my directory. I've built out a Tkinter window with a search function, however I'm not sure how I would be able to query patients, select a study and import the images. I would like to use either Tkinter or Django to do this. ae.add_requested_context(PatientRootQueryRetrieveInformationModelFind) assoc = ae.associate('MY_IP', MY_PORT) # Create our Identifier (query) dataset ds = Dataset() ds.QueryRetrieveLevel = 'PATIENT' ds1 = ds.PatientID = [] #<--------- How to query an ID in the tkinter search field? if assoc.is_established: # Send the C-FIND request responses = assoc.send_c_find(ds, PatientRootQueryRetrieveInformationModelFind) for (status, identifier) in responses: if identifier: print(identifier) # Release the association assoc.release() else: print('Association rejected, aborted or never connected') Image of …