Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i using the setting of CKEDITOR_CONFIGS in class ckeditor?
i have already set CKEDITOR_CONFIGS in settings.py but when i try to use <td><textarea class="ckeditor" name="remark" id="test1" cols="30" rows="10"></textarea></td> both are different style how can i make ckeditor in class using the style i have set in CKEDITOR_CONFIGS -
How to create key to get a request to Django API?
I am creating a database with Django, and I am accesing it with Excel and Apps Script. I can't log in into my superuser account (the only account I'll be having). Therefore, I want to know if there is a way to set a key, or a password, passed through an HTTP header, that I can use to access my API. Currently I only have one API get method, but I'll have more create, update, etc., and I want to be able to use the same key for these as well. It is a really simple Django application deployed in heroku, so I am not using django-REST-framework, nor graphene-django. So if the solution can come without installing anything else, it would be nice. However, if this is not possible, it is better if the solution comes through graphene-django, since I have used it before, and I am more familiar with it. It is important to notice that both the excel file and the apps script are private, since I am using django as a database manager for a small, personal project. Thank you very much in advance! -
How do i change what django looks for in .filter()?
take this example code: from .models import Employees filters = { "name" : request.GET.get("name"), "work_place" : request.GET.get("work_place_filter") } for index, item in enumerate(filters): key = list(filters.keys())[index] value = filters[item] flykninger = Employees.objects.filter(key = value) what im trying to do here is to change what key the filter() function compares the value to if the input fields are not None. But whenever i try to run my own code that includes this snippet, i get Cannot resolve keyword 'key' into field. Choices are: alder... How do i do this? is there another way to do it that i'm not aware of? Thanks -
Is it possible to edit the page_obj before passing template?
I can catch <class 'django.core.paginator.Page'> in get_context_data function of django view class. What I want to do is alter the showing item and get it back to <class 'django.core.paginator.Page'> again. django.core.paginator.Page source code is here. https://docs.djangoproject.com/en/4.0/_modules/django/core/paginator/ I found it has object_list,so I try to change def get_context_data(self): temp = super().get_context_data() print(type(temp['page_obj'])) #<class 'django.core.paginator.Page'> new_object_list = [] for t in temp['page_obj'].object_list:## I can iterate the item here. # make new_object_list here temp['page_obj'].object_list = new_object_list print(temp) # nothing changes return temp However object_list doesn't change. -
no module error on python when I connect EC2 with ssh
I am a junior(more like kindergarten to be specific) web developer and I get some project which already exists. it is deployed on EC2 and I had to deal with some python files. I wanted to execute python files, So I connect project with ssh via key files. and I tried to execute python files but I couldn't and get a message like this. ModuleNotFoundError: No module named 'bs4' Well, I thought I could run a file because modules are already downloaded on EC2server?? how can I solve this and run python file on ssh? ps. when I make a new python file and run print("pypy") It runs OK thx for reading, your help will be appreciated. -
How to host multiple docker apps on one AWS Lightsail instance
Is it possible to host multiple docker services in one lightsail instance? I want to deploy an NGINX proxy, Django Web App, and Strapi server in the same instance. My project is developed using docker-compose. What is the recommended way in this scenario? Thanks in advance. -
If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import
i got:django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'bookstore.urls' from 'C:\blog\bookstore\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. my urls.py in blog is: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin', admin.site.urls), path('' , include('bookstore.urls')) ] my code in view.py is: from django.http import HttpResponse from django.shortcuts import render def home(request): return HttpResponse('Home Page') def users(request): return HttpResponse('users Page') def info(request): return HttpResponse('info Page') my code in bookstore.urls.py is: from django.urls import path from bookstore import views URLPatterns = [ path('home/' ,views.home), path('users/' ,views.users), path('info/' ,views.info), ] and thank you for your help -
Show MQTT data in django template
I'm using paho-MQTT and I'm able to receive messages. When I receive a message, I want to display the data in a template, but am unable to do so. Below is the code I have. import paho.mqtt.client as mqtt import json def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("mhub/hr") def on_message(client, userdata, msg): x = (msg.payload) print(x) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("mqtt.eclipseprojects.io", 1883, 60) I have been following the tutorial. How can I show new data from MQTT in the html template I have created? -
Getting redirected to wrong url in django
I am trying to send an account verification email and redirect to the login page def signup(request): custom_user_id = ''.join(random.choices(string.ascii_uppercase+string.digits,k=10)) if request.method=="POST": form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = form.cleaned_data['username'] user = Account.objects.create_user(user_id=custom_user_id,first_name=first_name,last_name=last_name,email=email,username=username,password=password)#this method is present in models.py file user.save() """ User activation mail """ current_site = get_current_site(request) mail_subject = "Please activate your fundaMental account" message = render_to_string('account_verification_email.html',{ 'user':user, 'domain':current_site, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject,message,[to_email]) send_email.send() It is supposed to redirect to '127.0.0.1:8000/account/login/?command=verification&email=+email' but instead it gets redirected to '127.0.0.1:8000/account/signup/account/login/?command=verification&email=+email' return redirect('account/login/?command=verification&email='+email) else: form = RegistrationForm() context = { 'form':form, } return render( request,"signup.html",context) Here is my urls.py file from django.urls import path from . import views urlpatterns = [ path('signup/',views.signup,name='signup'), path('login/',views.login,name='login'), path('logout/',views.logout,name='logout'), path('activate/<uidb64>/<token>',views.activate,name='activate'), ] Here is my project level urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('account/',include('account.urls')), ] -
AttributeError: 'ForeignKey' object has no attribute 'choice_1'
Why this error when trying to migrate this portion of the model Vote: choices=[election.choice_1, election.choice_2] models.py class Election(models.Model): custom_user = models.ForeignKey(CustomUser) vacant_office = models.CharField() choice_1 = models.CharField() choice_2 = models.CharField() class Vote(models.Model): custom_user = models.ForeignKey(CustomUser) election = models.ForeignKey(Election) vote = models.CharField( choices=[election.choice_1, election.choice_2]) A better way? -
Django Stripping Blanks In Between Words When Generating Blanks
I am working on a Hangman game using Django and I'm having some trouble generating the blanks from the words if the answer is two words, such as a first and last name. It seems to be something with Django stripping spaces and I have tried playing around with some solutions I found elsewhere, but unsuccessfully. Here I've changed admin.py1 Here I've created a fields.py 2 Where I probably am lost is how I'm linking it back in models.py or displaying it in the template. My logic is solid, I can replicate outside of Django, so it is something model related. Any help or guidance would be greatly appreciated! -
django templatees dissapearing on refresh
I have constructed a news aggregator website which shows 10 headlines with corresponding images, scraped from https://thestar.com ( The Toronto Star ) , using bs4. Here's a photo for reference: However, the major problem is, Everytime i refresh the page, all of the elements dissapear, As seen in the photo below : Anyone know what the problem is? Here is the element where my variables are stored: <div class="col-6"> <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center> {% for n, i in toronto %} <img src="{{i}}"> <strong><h5>{{n}}</h5></strong> <hr> {% endfor %} <br> </div> and here's my views.py file : from django.shortcuts import render import re import json import requests from bs4 import BeautifulSoup import itertools # Getting news from The Toronto Star toi_r = requests.get("https://www.thestar.com/?redirect=true") toi_soup = BeautifulSoup(toi_r.content, 'html.parser') toi_headings = toi_soup.find_all('h3') toi_headings = toi_headings[0:10]# removing footers toi_news = [] for th in toi_headings: toi_news.append(th.text) #Getting news from the NY Times ht_r = requests.get("https://www.nytimes.com/") ht_soup = BeautifulSoup(ht_r.content, 'html.parser') ht_headings = ht_soup.findAll('h3') ht_headings = ht_headings[0:8] + ht_headings[10:12] + ht_headings[19:21] ht_news = [] for hth in ht_headings: ht_news.append(hth.text) # Getting Images from The Toronto Star tor_r = requests.get("https://www.thestar.com/") data = re.search(r"window\.__PRELOADED_STATE__ = (.*)", tor_r.text) data = json.loads(data.group(1)) def find_images(d): if isinstance(d, dict): for … -
Django Python3 can't open file 'manage.py': [Errno 2] No such file or directory
I am sure this question has already been asked several times but I find myself unable to make migrations and have tried numerous commands to go to the right directory yet I have been unsuccessful. This is my tree as per the image below: Could someone tell me the right command to make my migrations ? -
Why is Django is not loading my template view but it once was
My view was running fine until Ill tried to override an admin view. Which i eventually got to work. However in the process I broke the path to my view that was working. The admin view had nothing to do with my originally working view. Now I copied my view into every possible level of my project structure. Yet the django template loader fails to find my order_input.html The error shows the correct path to my order_input.html. I made copies of order_input.html at every single possible level of my project... but django still cant find it. APP - URLS.PY from django.conf.urls import url from . import views urlpatterns = [ url(r'^hw/$', views.helloworld, name='helloworld'), url(r'^order_input/$', views.order_input, name='order_input'), url(r'^time/$', views.today_is, name='time'), url(r'^$', views.index, name='index'), ] SETTINGS.PY # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # 'django.contrib.staticfiles', 'import_export', 'hw_app', ] PROJECT URLS.PY urlpatterns = [ url('r', include('hw_app.urls')), url('admin/', admin.site.urls), path('clearfile', views.clearfile), path('readfile', views.readfile), path('writefile', views.writefile), path('helloworld', views.helloworld), path('order_input', views.order_input), path('ajax_view', views.ajax_view), ] -
How do I use start-app template context in a template file?
I have the current setup for a Django app template which I pass to start-app like so: python3 manage.py start-app --template template/ myapp With a directory structure like this: template/ templates/app_name/ page.html ... app.py app.py uses the template context passed when start-app is run, and works fine! # app.py from django.apps import AppConfig class {{ camel_case_app_name }}Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = '{{ app_name }}' However, I'm trying to get similar behaviour out of page.html, to no avail. {% extends "{{ app_name }}/otherpage.html" %} {% block content %} <p>Hello from {{ camel_case_app_name }}!</p> {% endblock %} If I run start-app like normal, the template is copied over and the app name is not inserted. If I try to run start-app with --extension py,html I don't get the expected behaviour either, because the template is rendered. Is there a way to convert the {{ app_name }} calls in page.html without attempting to render the entire template? -
Django Admin filter_horizontal using wrong primary key and causing constraint violation
Here is the related models: Service order Item: class ServiceOrderItem(models.Model): id = models.AutoField(primary_key=True, verbose_name="ServiceOrderItem ID") service_order = models.ForeignKey(ServiceOrder, on_delete=models.RESTRICT) service = models.IntegerField(choices=settings.SERVICE_TYPE_CHOICES) notes = models.TextField(blank=True) in_service_date = models.DateTimeField(null=True, blank=True, default=None) cost = models.FloatField() term = models.IntegerField() active = models.BooleanField(default=True) leases = models.ManyToManyField( to="Location", symmetrical=True, null=True, blank=True, default=None, ) def __str__(self): return f"Item {self.pk} in Service Order {self.service_order.pk}" Location: class Location(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) common_name = models.CharField(max_length=200, verbose_name="Location") parent_location = models.ForeignKey("self", blank=True, on_delete=models.RESTRICT, null=True, default=None) used_slots = models.IntegerField(default=1) slot_index = models.IntegerField(default=1) company = models.ForeignKey(Company, on_delete=models.RESTRICT) location_type = models.IntegerField(choices=settings.LOCATION_CHOICES) city = models.ForeignKey(City, on_delete=models.RESTRICT, null=True, blank=True) county = models.ForeignKey(County, on_delete=models.RESTRICT, null=True, blank=True) address_line = models.CharField(max_length=200, blank=True) location_point = models.PointField(default=None, null=True, blank=True) zipcode = models.CharField(max_length=30, blank=True) def __str__(self): return f"{self.get_full_location()}" def get_description_for_admin(self): if self.county is not None: return f"{self.city.name}, {self.county.state.name}" elif self.parent_location is not None: return self.parent_location.get_description_for_admin() else: return None def get_description_for_device(self): result = "" if self.location_type in (8, 6, 5): result = f"{self.parent_location.get_description_for_device()}{self.common_name}" elif self.location_type in (1, 9) or (self.location_type == 2 and self.city is not None): result = f"{self.county.state.abbreviation}-{self.city.name}-" else: if self.parent_location is not None: result = self.parent_location.get_description_for_device() return result def get_full_location(self): result = f"{self.common_name}" if self.parent_location is not None: result = f"{self.parent_location.get_full_location()}-{result}" return result admin item: class ServiceOrderItemAdmin(admin.ModelAdmin): list_display … -
Django synchronous function: wait for one session to finishing using function
In my django server, I have a function that handles a request from a user. When multiple users are sending requests from within their respective sessions at the same time, the function processes the requests within their own sessions so it happens in parallel. But I want to ensure that when I have multiple requests from multiple users, they are handled one by one rather than simultaneously. Basically, I don't want this function to be a session instance but a global function that only one user can use at a time. How can I solve this problem? This is an open-ended question so as long as we are using Django in the implementation I don't have any more constraints. -
settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value
i develop an app on heroku server when i finishing setting up my AWS RDS POSTGRESQL and run my migrations and migrate successeful without any error. its throws me an error. the error settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value. i did'nt run heroku run python manage.py migrate which i think is not the problem. I'm using heroku server and i setup everything its needs for aws rds for postgresql. i get this error in production server not on localhost, because its working perfect on localhost. Database configurations in settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '5432', } } is anybody who face the same problem before me please. Thanks -
Error: the following arguments are required: new (How to Build an E-commerce Website with Django and Python)
I am trying to start this tutorial... I had to pip install a few packages and adjust requirements.txt a bit. Now, I'm trying to rename the project and I am getting an error "manage.py rename: error: the following arguments are required: new". Any help will be much appreciated. https://www.youtube.com/watch?v=YZvRrldjf1Y&t=1485s&ab_channel=freeCodeCamp.org import os from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Renames a Django project' def add_arguments(self, parser): parser.add_argument('current', type=str, nargs='+', help='The current Django project folder name') parser.add_argument('new', type=str, nargs='+', help='The new Django project name') def handle(self, *args, **kwargs): current_project_name = kwargs['current'][0] new_project_name = kwargs['new'][0] # logic for renaming the files files_to_rename = [f'{current_project_name}/settings/base.py', f'{current_project_name}/wsgi.py', 'manage.py'] for f in files_to_rename: with open(f, 'r') as file: filedata = file.read() filedata = filedata.replace(current_project_name, new_project_name) with open(f, 'w') as file: file.write(filedata) os.rename(current_project_name, new_project_name) self.stdout.write(self.style.SUCCESS( 'Project has been renamed to %s' % new_project_name)) -
use pytesseract with Django
i want to do text recon from image with Django and Pytesseract what i want is that, a user should upload a picture from the browser and press on a button so that the choosen image should be turned into text.. i have tried this function in a single file: import pytesseract pytesseract.pytesseract.tesseract.cmd = r"C:Program files\Tesseract-OCR\tesseract.exe" def ocr_core(filename) text = pytesseract.image_to_string(filename) return text #test the function on an image in images folder print(ocr_core('images/test4.jpeg')) this work fine in the terminal. but now i want to use this function in My django view file by calling the file where the function is written or by doing it directly in the view.. pls i don't know if my explanation is good..if yes, pls i need help -
Django-cart object always empty
I am developing ecommerce web application using Django. After I have implemented a footer, pagination and a search bar, "Add to cart" button stopped working. My only guess was that there was a cache issue, therefore I have added @never_cache decorator above the cart/checkout views however, the button still did not work and while inspecting, the cart object is empty even after pressing the button. I am not sure what is the reason behind it. main.html In this template I have written JS logic for cart, nav bar and a search bar. <!DOCTYPE html> {% load static %} <html lang="en"> <head> <title>Eshop</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken'); function getCookie(name) { // … -
Django Rest custom serialize field
My models.py is as follows: class ExampleClass(models.Model): TYPES = ( (0, "Amount"), (1, "Value"), ) type = models.IntegerField(choices=TYPES, default=0) type_value = models.FloatField() and I want to serialize it to looks like that: "example": { "Amount": 10.0 # "type": type_value } How can I get this custom serialisation? -
TemplateSyntaxError at / 'for' statements should use the format 'for x in y'
I am trying to run a concurrent loop in my index.html file, however i am getting this error: TemplateSyntaxError at / 'for' statements should use the format 'for x in y': for i, n in zip(images, toi_news) Here's my html code : <div class="col-6"> <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center> {% for i, n in zip(images, toi_news) %} <strong><h5>{{n}}</h5></strong> <img src="{{i}}"> <hr> {% endfor %} <br> </div> Anyone know how to correct this issue? -
How to change display value for one to one field in django admin?
I'm looking to change the display value for a one to one field in the django admin dashboard. I want to prefix the user's name to the one to one field. I'm able to successfully do it for a foreign key like this: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'audio_module': return AudioModuleChoiceField( queryset=AudioModule.objects.filter(is_deleted=False).order_by('user__last_name') ) return super().formfield_for_foreignkey(db_field, request, **kwargs) However, I don't see any options in the docs to override a formfield_for_onetoone. Currently, my form field looks like this: audio_module has a FK to my user table. Like I said above, I'd like to prefix the user's name in front of the audio module in the dropdown so it'll be easier to identify audio modules for specific users. i.e. John Doe - audio module 2 How do I achieve this? -
Django Crontab keeps stating module not found
Every time I try to run python manage.py crontab add or run my testing script I get this: File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_crontab' Settings: INSTALLED_APPS = [ 'django_crontab', 'rest_framework', 'prices.apps.PricesConfig', 'meters.apps.MetersConfig', 'devices.apps.DevicesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'accounts', ] . . . CRONJOBS = [ ('0 22 * * *', 'website.cron.delete_old_registration') ] . . . cron.py: import datetime from .models import Register def delete_old_registration(): today = datetime.date.today() filter_old_date = today - datetime.timedelta(days=14) registrations_old = Register.objects.filter(date__lte=filter_old_date) registrations_old.delete() Banging my head here cause I've reinstall django-crontab and followed the instructions multiple times.