Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
send a variable to multiple pages with return render django
I want to send a variable when the user is connected (connect = true ) on the connect method, to change the navbar , what im trying to do is send the variable to all the pages on my project, this way i can check with a condition. Is there a way to do it with return render , I checked on the internet , but find nothin helpfull. -
django rest Error - AttributeError: module 'collections' has no attribute 'MutableMapping'
I'm build Django app, and it's work fine on my machine, but when I run inside docker container it's rest framework keep crashing, but when I comment any connection with rest framework it's work fine. My machine: Kali Linux 2021.3 docker machine: Raspberry Pi 4 4gb docker container image: python:rc-alpine3.14 python version on my machine: Python 3.9.7 python version on container: Python 3.10.0rc2 error output: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.10/site-packages/django/test/runner.py", line 728, in run_tests self.run_checks(databases) File "/usr/local/lib/python3.10/site-packages/django/test/runner.py", line 665, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/check.py", line 63, in handle self.check( File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return … -
Django: organizing models in a package after migration
I have a models.py file with models in it. Now I want to reorganize these models into a package as described in an official documentation. Can I do it with the existing models? How does it affect previous migrations? -
Should I put my user profile models in the same app that handles account signup and login
In my django project I have an app called "accounts" that handles sign up and logins. Upon authentication, It redirects to 3 other apps depending on the type of user. The profiles of each user type is different and I don't know where to put the user profile models. Should I put them in the "accounts" app or in the other 3 apps? I currently have them inn their individual apps but I want to know what the better way to do it is. -
How i can access user which is logged in now to receiver function [duplicate]
so i want to create object from last_action on save of each models(Cars,Books,Carrots), but as far as i know instance is only passing attributes of sender model. So now i want to as well use user which is logged in, but i do not know how to pass it to my object, because sender model does not have it. How can i access to user and pass it to my object? signals.py @receiver(post_save,sender=Cars) @receiver(post_save,sender=Books) @receiver(post_save,sender=Carrots) def Save_last_editor(sender,instance,**kwargs): last_action.objects.create(item=instance.item,user = ???) models/items.py class Items(models.Model): name = models.CharField(max_length=30, unique=True) models/carrots.py class Cars(models.Model): name = models.CharField(max_length=30, unique=True) item = models.ForeignKey('Item', on_delete=models.PROTECT) models/carrots.py class Books(models.Model): name = models.CharField(max_length=30, unique=True) item = models.ForeignKey('Item', on_delete=models.PROTECT) models/last_action.py class LastAction(models.Model): item = models.ForeignKey('Item', on_delete=models.PROTECT) user = models.ForeignKey('User', on_delete=models.PROTECT) last_update = models.DateField(auto_now_add=True) -
How to enable page refreshing favicon in browser tab?
Do you know any methods, statements, events to trigger the page reloading favicon? I got <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" type="image/png" href="myfavicon.ico" /> ... </head> <body> ... </body> </html> Of course i can press F5 to reload the page, but it is undesirable, like as using <form> </form> tags or <input> </input> etc. How to trigger loading favicon, without page reloading? -
How to integrate google calendar in my website?
I am trying to access and show the google calendar of any user (after login) in my website using django. User can change the calendar from the website and it should be visible in google calendar. I dont want to make user calendar public. (Ref) This is what I did. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) now = datetime.datetime.utcnow().isoformat()+'Z' page_token = None calendar_ids = [] while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: print(calendar_list_entry['id']) if "myorganization" in calendar_list_entry['id']: # print(calendar_list_entry['id']) calendar_ids.append(calendar_list_entry['id']) page_token = calendar_list.get('nextPageToken') if not page_token: break print(calendar_ids) for calendar_id in calendar_ids: count = 0 print(calendar_id) eventsResult = service.events().list( calendarId = calendar_id, timeMin = now, maxResults = 5, singleEvents = True, orderBy = 'startTime').execute() events = eventsResult.get('items',[]) # return calendar_ids,events response = JsonResponse(events,safe=False) # print(eventsResult) if not events: print('No upcoming events found') # print(events) print("-----------------------------------") I am able to get all the events of user's calendar. Now I want to show this calendar to the user. I trying to show these events using FullCalendar. document.addEventListener('DOMContentLoaded', function … -
How to troubleshoot a droplet on digital ocean that has a docker-django container running in it
I deployed my django docker via GitHub actions to Digital Ocean by following this tutorial and here is the code that was deployed. How can I see the logs of the droplet since I am not able to see my Django live on the link. I navigated to the digital ocean and I am able to open the console, but I am not sure how can I diagnose the issue from here. -
application error deploy using flask, heroku
successfully deployment app After successfully app deploy and when I click view then getting this error and in logs file not understand what is the problem. please help me out. enter image description here logs -
How To Fix create() takes 1 positional argument but 5 were given In python django
I'm Creating Login & Register Form In Django. I got an error create() takes 1 positional argument but 5 were given. code: def register(request): if request.method=="POST": username=request.POST['username'] name=request.POST['name'] email=request.POST['email'] password=request.POST['password'] user_create = User.objects.create(username,name,email,password) user_create.save() messages.success(request, " Your account has been successfully created") return redirect("/") else: return HttpResponse("404 - Not found") html https://paste.pythondiscord.com/amoturoqop.xml -
Django: STATIC_ROOT STATIC_ROOT can't join with BASE_DIR path
I set up my STATIC_ROOT like this STATIC_ROOT = os.path.join(BASE_DIR,'/vol/web/staticfiles') print('this is base_dir') print(BASE_DIR) print("this is static_root") print(STATIC_ROOT) When I run python manage.py runserver it print out this: this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles this is base_dir F:\7.Django\BLOG_PROJECT\src_blog this is static_root F:/vol/web/staticfiles When I run python manage.py collectstatic. Sure! It set my STATIC_ROOT AT F:/vol/web/staticfiles. I noticed that it print out the separate folder symbol different '/' and ''. I use windows os btw. Also don't know why it seems my app run settings 2 times. This is my settings ├── settings <br /> | ├──__init__.py <br /> | ├──base.py <br /> | ├──dev.py <br /> | ├──prod.py <br /> and my settings\__init__.py file contain: import os from dotenv import load_dotenv load_dotenv() # you need to set "ENV_SETTING = 'prod'" as an environment variable # in your OS (on which your website is hosted) if os.environ['ENV_SETTING'] =='prod': from .prod import * else: from .dev import * from .base import * -
Exception for 'NOT LIKE' in Oracle_SQL
in a database are many tables with the name 'D_...'. In a search query, all tables with 'D_%' should be ignored, except one. How do I handle this exception? many thanks Exception for 'NOT LIKE' in Oracle_SQL -
Sort django queryset using string field alphabetically
I want to sort users from model with their last names. I am using User.objects.filter(is_active=True).order_by('last_name') Still there is no luck. Pls suggest some solution. -
sender and instance arguments of post_save signal in Django
I'm confused with Django's post-save signal documentation: sender The model class. instance The actual instance being saved. Is "sender" the class of the model instance being saved? Is "instance" an instance of the sender model ? i.e. if I registered a signal receiver to receive post_save signals from the User model using signal.connect(), would "sender" be the User model and "instance" be the instance of the User model being saved ? -
How to set the global WEB_IMAGE and NGINX_IMAGE environment variables
I am following this tutorial and it says Set the global WEB_IMAGE and NGINX_IMAGE environment variables (export WEB_IMAGE = ? what exactly and where? on my local machine or in the droplet?) Add environment variables to a .env file (I created a .env file on the root directory and it is accessble by the Django settings - so this is done) Set the WEB_IMAGE and NGINX_IMAGE environment variables with so they can be accessed within the Docker Compose file I am not sure how to do these steps, can someone please explain? I am on ubuntu 20.04 -
Using filter__in via Foreignkey relationship returns en empty queryset
I'm trying to use the queryset category_filter as a filter__in // Django doc for another query qs_poller. However, the query returns an empty set. # View def render_random_poller(request): if request.user.is_authenticated: category_filter = Category.objects.filter(usercategoryfilter__user=request.user) # Returns <QuerySet [<Category: Sports>, <Category: Lifestyle>, <Category: Environment>]> qs_poller = Poller.objects.filter(poller_category__category__in=category_filter).order_by('-created_on')[:100] # Returns an empty set, although the database holds 5 entries matching the category_filter # Models class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) class Poller(models.Model): created_by = models.ForeignKey(Account, on_delete=models.SET(get_deleted_user)) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) class Category(models.Model): category = models.CharField(max_length=30) -
i have Erroor "Related Field got invalid lookup: icontains" when i try filter on views.py from models.py
here, on views.py I want to filter 'language' from the models.py but it said there is Errror. " raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains" i dont know why just'language' has problem but not when i try to filter 'genre','title', i dont see the Error on the terminal what can be the solutions? here is the models.py from django.db import models from django.urls import reverse import uuid class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): return self.name class Language(models.Model): name = models.CharField(max_length=200, help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)") def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), … -
I want to create multiple objects with single foreign key relation
I need to add multiple skills for one candidate. As now i am getting the error cannot assign multiple instances to skill models class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE,related_name="skills",) skills = models.ForeignKey("jobs.Skill", on_delete=models.CASCADE) ---------- class CandidateSkillSerializer(serializers.ModelSerializer): class Meta: model = CandidateSkill fields = ["id", "candidate", "skills"] -
Adding validator to a model field via __init__ of the class model results in duplication of error messages
I have a model like this: class Permission(models.Model): slug = models.CharField('Метка', unique=True, max_length=255) @staticmethod def slug_field_validator(value): raise ValidationError('Error message') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.get_field('slug').validators.append( self.__class__.slug_field_validator) This results in duplication of error messages in admin interface. What am I doing wrong ? -
How to know blank and non blank fields after a django ajax form submission?
I have a modelform which allows a some non required fields. Where I am stuck is figuring out a way that will allow me to exactly know which field came with data, and which did not so while creating my model instance I won't miss any user data inputted. at beginning I thought of serializing the form by using serializeArray then get the non empty value and add it in the form.serialize() but this prevents the form from being valid. Here is the see question. Is there any way to know this even if it is before processing the ajax or in the django view itself ? Thank you in advance. Code: function CreateIssueAjax(e) { e.preventDefault(); const role = this.getAttribute('role'); const _form = $("#CreateIssueForm"); var formString = _form.serializeArray(); console.log(formString) function sendKwargs(arr) { let kwargs = {} arr.forEach(el => { if (!(el.value === "") | (!(el.name === 'csrfmiddlewaretoken'))) { kwargs[el.name] = el.value } }); return kwargs; } console.log(sendKwargs(formString)); var myData = _form.serialize(); console.log(myData); myData['kwargs'] = JSON.stringify(sendKwargs(formString)); $.ajax({ url: "/create-issue/", type: "post", data: myData, datatype: 'json', success: function (data) { console.log("success"); // add to ui function after success // alert the user(alertify.js) }, }); } def createIssue(request): form = CreateIssueForm(request.POST or None) … -
django.template.exceptions.TemplateDoesNotExist: templates/index.html Error
I am making a Django authentication program but keeps on giving me this error. django.template.exceptions.TemplateDoesNotExist: templates/index.html Error. PLS help me coz I have spent hours trying to solve this problem. Views.py from django.http import HttpResponse def home(request): return render(request, "authentication/index.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.home, name = "home"), path('signin',views.signin, name = "signin"), path('signout',views.signout, name = "signout"), ] Settings """ Django settings for gfg project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-tqa6(3cnb_f@3u(56)mu9z%d2c548xypd-@%6i&60@)mxbs$k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'gfg.urls' TEMPLATES = … -
Logging SQL with Django logging configuration. The logger always trying to connect with the public schema
The following is the logging configuration for our Django application logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(name)-12s %(lineno)d %(module)s %(levelname)-8s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 100MB 'backupCount': 10, 'formatter': 'verbose', 'filename': 'log_files/acme-slcms.log', 'encoding': 'utf-8', }, 'mail_admins': { 'level': 'CRITICAL', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django': { 'propagate': True, 'level': 'DEBUG', 'handlers': ['file'], }, 'django.db.backends': { 'propagate': False, 'level': 'DEBUG', 'handlers': ['file'], } } }) We have added the django.db.backends logger to print the queries generated by the application. But from the output, it seems the logger is connecting to the public schema 2021-10-06 13:37:39,704 django.db.backends 123 utils DEBUG (0.089) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname = 'public' AND pg_catalog.pg_table_is_visible(c.oid); args=None After implementing the log, we are not seeing any queries other than this. The application is actually using another schema for storing and retrieving data and is using django-tenant as part of the homegrown … -
Return JSONResponse before updating database in django, python2
Im having a project running on python2.7. The project is old but still its necessary to update the database when a request is received. But the update process takes time and ends up with a timeout. Is there anyway return JsonResponse/Httpresponse, before updating the database so that timeout doesn't occur. I know its not logical to do so, but its a temporary fix. Also, i cant use async since its python2 -
Django and Django rest framework
I was following a resource https://blog.learncodeonline.in/how-to-integrate-razorpay-payment-gateway-with-django-rest-framework-and-reactjs Instead of using reactjs for the front end. How can i make the frontend using Django templates? Please help. Thank you. -
Showing multi-dimensional data in django
Hej! I have some multidimensional data in my django project, e.g. a status of an institution (containing e.g. a year to differ them). Every institution can have multiple status from different years. Also I have multiple institutions and want a table/list of them. Is there a possibility to show show those multi-dimensional data for each institution? Or maybe the newest? I couldn't find it in the docs. # models.py class StatusOfPlants(models.Model): """status (phases) of plants""" class StatusChoices(models.TextChoices): PLANNING = "planning", _("in foundation") IN_OPERATION = "in_operation", _("in operation") plant = models.ForeignKey( Plant, on_delete=models.PROTECT, related_name="status_of_plant" ) status = models.CharField( max_length=20, choices=StatusChoices.choices ) year_valid_from = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) year_valid_to = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) def __str__(self): return f"{self.status}" In the admin area can the multi data be added. I'm just wondering about the presentation in the view when I want more than just a list of the status 'names' in one field. Hope it is clear what I'm talking about and someone has an idea how to solve that! Thanks in advance :)