Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I reach Django admin model stackedinlines in html tags?
I'm using stackedinline for for creating subtopic for each cancer type, in admin everything works fine, i can add subtopic for each type of cancer directly from cancer type creat/edit page, but I cant figure out how to display subtopic related to "parent" type in html template. P.S. I'm new in programming my models.py from django.db import models from ckeditor.fields import RichTextField class CancerType(models.Model): name = models.CharField(max_length=200, blank=False) image = models.ImageField(upload_to="static/assets/images/types") description = RichTextField(default="", blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Տեսակ" verbose_name_plural = "Տեսակներ" class SubTopic(models.Model): type = models.ForeignKey(CancerType, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=False) topic = RichTextField(blank=False, null=True) def __str__(self): return self.title class Meta: verbose_name = "Ենթաբաժին" verbose_name_plural = "Ենթաբաժիններ" admin.py rom django.contrib import admin from .models import CancerType, SubTopic admin.site.register(SubTopic) class SubTopicInline(admin.StackedInline): model = SubTopic extra = 0 class CancerTypeAdmin(admin.ModelAdmin): inlines = [SubTopicInline] admin.site.register(CancerType, CancerTypeAdmin) type.html {% extends 'base.html' %} {% load static %} {% block content %} <img src="{% url 'home' %}{{ cancertype.image }}"> <h4>{{ cancertype.name }}</h4> <br> {{ cancertype.description|safe }} <br> {% for subtopic in object_list %}} {% if subtopic.type %}} {{ subtopic.title }} <hr> {{ subtopic.body }} {% endif %} {% endfor %} {% endblock %} -
how to stop run path again to join whith same path in django
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this i need help to solve this problem -
model for uploading and downloading file from specific category
I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. I'm creating a website for uploading and downloading wallpapers but I'm not able to add the category field in the model and templates from where user can upload and download wallpaper from specific category. Can someone please suggest something. -
Python cli.py execution stuck: Unable to figure out the source
I'm trying tto deploy the following Django-rest api on gcp ubuntu 22.0.4 using python 3.9. https://github.com/OkunaOrg/okuna-api The enter setup is supposed to be done and get setup using a single command : python3.9 okuna-cli.py up-full The execution seems stuck at "Waiting for server to come up..." and doesn't proceed ahead. The setup should complete by stating "Okuna is live at "domain". Another important aspect of the setup is the 5 docker containers are running and working fine when i run the py file. I'm even able to access the database after creating a superuser. The code is as follows : import random import time import click import subprocess import colorlog import logging import os.path from shutil import copyfile import json import atexit import os, errno import requests from halo import Halo handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(name)s -> %(message)s')) logger = colorlog.getLogger('🤖') logger.addHandler(handler) logger.setLevel(level=logging.DEBUG) current_dir = os.path.dirname(__file__) KOSMOS_CLI_CONFIG_FILE = os.path.join(current_dir, '.okuna-cli.json') KOSMOS_CLI_CONFIG_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.okuna-cli.json') LOCAL_API_ENV_FILE = os.path.join(current_dir, '.env') LOCAL_API_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.env') DOCKER_COMPOSE_ENV_FILE = os.path.join(current_dir, '.docker-compose.env') DOCKER_COMPOSE_ENV_FILE_TEMPLATE = os.path.join(current_dir, 'templates/.docker-compose.env') REQUIREMENTS_TXT_FILE = os.path.join(current_dir, 'requirements.txt') DOCKER_API_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api', 'requirements.txt') DOCKER_WORKER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'worker', 'requirements.txt') DOCKER_SCHEDULER_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'scheduler', 'requirements.txt') DOCKER_API_TEST_IMAGE_REQUIREMENTS_TXT_FILE = os.path.join(current_dir, '.docker', 'api-test', 'requirements.txt') CONTEXT_SETTINGS = … -
Where to verify the settings during startup
After settings.py executes, I need to check to make sure all the settings were found from the .env variables, and error out if they are not. Where's the appropriate place to put that logic? Right in settings.py? manage.py? -
Custome route in django admin
I wanted to customize my django admin route Not from /admin to something else but to add new clickable custom route inside admin panel Currently I have created superuser using python manage.py createsuperuser command. I can login to django admin panel , but what I want is to have a custom route to be displayed in left sidebar or anywhere else after logging into django admin panel. My custom route is like localhost:8000/my-view/ and my-view should be displayed somewhere in admin panel. TIA. -
Want to make code for inactive or idle user time in Python when he did not show any movement on screen and keyboard and mouse through
I am student and I am making an app regarding tracking time activity. So please help me to give an solution. I am finding out from last 4 days regarding the hints or code . I got one solution of my friend . but i am confuse that how to use this. If i use this and store that time so how could i make an object and api so i can display this time in frontend side. import sys if sys.platform == 'win32': from ctypes import * class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_int), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) if windll.user32.GetLastInputInfo(byref(lastInputInfo)): millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0 else: return 0 else: def get_idle_duration(): return 0 if __name__ == '__main__': import time while True: duration = get_idle_duration() print('User idle for %.2f seconds.' % duration) time.sleep(0.5) I am expecting that please help me to solve my solution. I am student and I am learning this. I am expecting an output like total idle time of computer is 1 hr or 2 hr . I already made code for tracking time for task/project time. -
I cannot install Django, And give "Installation failled"
I want to install Django,But when I run pipenv install django it create virtual environment and then give Installation Failed. Before try below codes I run pip install django to install Django. And there is no issue with internet connection. How do I fix this? I tried pip install django , pipenv install django -
django.urls.base.get_script_prefix() returns incorrect prefix when executed by apache
Python-3.8/Django-3.2/Mezzanine-6.0 application tries to access incorrect pages when executed by apache. In standalone mode (python manage.py runserver) it creates correct address /admin/page_types/basicpage/2677/change/ whereas in apache mode it creates address /admin/page_types/basi/admin/pages/page/2677/change/ in the same place. It seems to be the get_script_prefix() function in django/urls/base.py that returns incorrect prefix when accessing page 2677 in apache mode. Also it seems to be running the same main thread all the time in apache mode. Could it be the main reason ? Apache configuration: [django@tkpika03p ~]$ cat /etc/httpd/conf.d/pika.conf # # VirtualHost template # Files must have the .conf suffix to be loaded. # # NameVirtualHost statements can be added to /etc/apache2/listen.conf. # # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for requests without a known # server name. # <VirtualHost *:80> ServerAdmin palvelin.hallinta@<myDomain> ServerName pikaappm.<myDomain> ServerAlias tkpika03p.ad.<myDomain> # TODO: Missä tilanteissa tänne päädytään? Jos ei löydy wsgi/django # : takaa, palautetaan 404 ja haetaan toiselta serveriltä # : Teoriassa täältä ei siis lueta mitään? DocumentRoot /srv/www/htdocs # if not specified, the global error log is used ErrorLog /var/log/httpd/pika-error_log CustomLog /var/log/httpd/pika-access_log combined # TODO: Vaihdettava debug -> warn -> info, kun kaikki toimii LogLevel warn # … -
How to fix too much time taken by python requests during get and post?
There is one website written in CakePhp and I am moving to Django. Some pages are making get/post request to another website to collect some information. CakePhp $socket = new HttpSocket(); $api_ret = $socket->get($url,$data,$this->header); Django import requests api_ret = requests.get(url,data,headers=self.header) Time taken by requests is too long compare to CakePhp. Is there anything I am doing wrong or Is there any other library that I can use ? Please Help. -
profile page of username 'admin' giving 404 error
My website is acting very weird for some reason. I have a profile page that displays information about an user. it takes username in url and pass it to view. It's working perfectly fine for all users, except for the super user 'admin'. For example, let's say there's an user with an username 'user01'. .../account/user01 will display profile page of 'user01'. But for some reason, .../account/admin leads to 404 error, and it specifies that it tried all urlpatterns including account/<str:username> [name='profile']. What makes this weirder is, when I do the exact same thing in incognito mode, .../account/admin works. Below are relevant codes: account/views.py def profile(request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404("User Does Not Exist!") return render(request, 'account/profile.html', {'user': user}) account/urls.py app_name = 'account' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'), path('signup/', views.signup, name='signup'), path('<str:username>', views.profile, name='profile'), ] -
Django migrations create object have foreign key
I have Three table one country, state and city. ` class Country(BaseModel): name = models.CharField(max_length=128) code = models.CharField(max_length=2, unique=True) isd_code = models.CharField(max_length=8) class State(BaseModel): country = models.ForeignKey("geo.Country", on_delete=models.CASCADE) name = models.CharField(max_length=256) code = models.PositiveIntegerField(blank=True, null=True) class City(BaseModel): name = models.CharField(max_length=128) country = models.ForeignKey("geo,Country", on_delete=models.CASCADE) state = models.ForeignKey("geo.State", on_delete=models.CASCADE) I have crete objecte throw migration country and state. def import_legacy_countries(apps, schema): Country = apps.get_model('geo', 'Country') for country in Country.objects.all(): country.delete() with open('legacy_data/CountryDetails.csv', mode='r') as file: # reading the CSV file csvFile = csv.reader(file) # displaying the contents of the CSV file for row in csvFile: Country.objects.create( name=row[1], code=row[2] ) def import_legacy_states(apps, schema): Country = apps.get_model('geo', 'Country') State = apps.get_model('geo', 'State') country_cache = {} missing_country_codes = [] non_unique_country_codes = [] with open('legacy_data/State.csv', mode='r') as file: # reading the CSV file csvFile = csv.reader(file) # displaying the contents of the CSV file for row in csvFile: country_code = row[1] if country_code in country_cache: country = country_cache[country_code] else: try: country = Country.objects.get(code=country_code) country_cache[country_code] = country except Country.DoesNotExist: missing_country_codes.append(country_code) except Country.MultipleObjectsReturned: non_unique_country_codes.append(country_code) State.objects.create( name=row[3], country=country ) if len(missing_country_codes) + len(non_unique_country_codes): print('Missing:') pprint(missing_country_codes) print('Non Unique:') pprint(non_unique_country_codes) raise Exception('Missing or non unique country present...') ` Now i want to add all country and state data to city … -
To create a big web app using django, what all things I should learn?
I am an intermediate django developer and I would like to more deeper concepts of django that would help me optimize queries, add mode functionalities to the app(I am a back end dev btw). I know basics of django like model designing, views, drf etc..I need more in-depth knowledge -
Heroku DNS, through cloudlfare not connecting to my domain name
Including the pictures down below, I have my code running and working perfectly fine on the website heroku generated for me, so i got a free website on freenom and sent the nameservers generated from cloudflare, and it just shows as an error on the website any ideas? Heroku CloudFlare I tried messing around with the name servers, and it just never happened to work -
How to post data to different model in django restframework
i am new to restframework .i am trying to save my post data to different model.i have no ideal how to do it or is it possible. views.py class AllAPIView(APIView): def get(self,request,*args,**kwargs): task = Task.objects.all() taskserializer = TaskSerializer(task, many=True) event = Event.objects.all() eventserializer = EventSerializer(event, many=True) context = [taskserializer.data,eventserializer.data] return Response(context) def post(self,request): taskserializer = TaskSerializer(data = request.data) eventserializer = EventSerializer(data = request.data) if taskserializer.is_valid(): taskserializer.save() return Response(taskserializer.data, status=status.HTTP_201_CREATED) if eventserializer.is_valid(): eventserializer.save() return Response(taskserializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) i am trying to do to this in a single path ,how can i differentiate my data while request? i tried by putting 2 serializer into the post function but it only save to the 1st serializer -
Why do webpages load so slowly the longer I use them?
I configured the webfront with Django and downloaded the modules using cdnjs. The contents composed inside are about 20 3d graphs of 120*50 size made with vis.js and 2d graphs made with plotly. I don't see this as the cause of the slowdown. Because when I first loaded the web page it took about 8 seconds and the next day it suddenly took about 1 minute to load. I don't know why there is such a difference. If anyone knows the cause, please let me know. When I checked with Google Developer Tools, it took a long time to load in JavaScript. When I loaded the webpage the previous day, the script that took 5 seconds to load took more than 1 minute the next day. I don't know where the web page takes to load, so I hope I get some hints. I want to know why the JavaScript loading is wrong with the time of the previous day and the next day. -
vue-for doesn't render objects in html
Hello i want to create a live search table on my django app using the vuejs cdn. On the POST side is working since it receives my API responses but when in it comes to render in vue-for it seems doesn't render and I only get is the header of table but the actual table body haven't appear in html page Here's my dashboard html file: <div id="app"class=" col-md-12 col-sm-12 py-3 px-4"> <!--Text search--> <div class="input-group"> <input @keyup="send_namerequest" v-model="search_query" type="text" class="form-control form-control-lg" placeholder="Search Bogus Client" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon2"><i class="fas fa-search"></i></span> </div> <div id="eraser" class="input-group-append" @click="remove_search"> <span class="input-group-text" id="basic-addon2"><i class="fas fa-eraser"></i></span> </div> </div> {%include "components/table.html"%} table.html <table v-show="true"id="recent" class="table p-0 w-0 table-lg table-responsive-sm table-striped table-bordered"> <tbody > <tr v-for="client in resultsobj" :key="client.name"> <td ><#client.name#></td> <td><#client.project.project_name#></td> <td><#client.reason.reason_name#></td> </tr> </tbody> </table> app.js var dash = new Vue({ el: '#app', delimiters: ["<#", "#>"], data: { haveresults: false, search_query: '', resultsobj: [], }, computed :{}, ready: function(){}, methods: { // methods function remove_search : function(){ this.search_query = ""; this.haveresults = false; }, async send_namerequest(){ const res = await axios.post('/api/search/',{ client_name : this.search_query, }) .then(function(response){ this.haveresults = true; this.resultsobj = (response.data); console.log(resultsobj) }) } //end }, }); -
Django: Insert checkbox in to word template
I am saving information from database to word. So let's say I have a context like this in views.py. context = { ... ... 'REP': repair.project, 'MAIN': repair.project } If the repair.project is "repair", then insert a selected checkbox to 'REP', then empty checkbox if "maintenance" to 'MAIN', or vice versa. No idea how to write this... Hope you can help me. Thank you! -
tutorial shows to use "python3 manage.py runserver", but gives "Python was not found..." error
I tried "python3 manage.py runserver", but it gave me this error. Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. details: My version is 3.11.0, I have anaconda and pycharm downloaded, but I used pycharm to try and do the manage.py thing, my interpreter is correct, and using python command in command prompt shows the details, meaning I do have python I'm a new coder, and I was watching a tutorial from a 3.7.2 user, and he told me to use "python3 manage.py runserver" but it gave me an error. On his screen, he gets a link to the django website, but I don't. -
how to troubleshoot django 'internal server error'
a similar question was asked 7 years ago, but the answer/comments were not that helpful and maybe not current. I'm developing a new website and relatively new to django. At times django provides a very detailed error response (very helpful) but other times it simply says 'internal server error' (less helpful). why is this and what is a good method for troubleshooting 'internal server error' errors? -
Django - model fields properties won't update
auth_id = models.CharField('something', max_length=14, unique=True, null=True, blank=True) name = models.CharField('something', max_length=64) email = models.EmailField('something', unique=True) class Meta: verbose_name = 'something' def __str__(self): return self.name I'm currently updating the properties of auth_id and email. None of the solutions I search worked. Whenever I run the command py manage.py migrate only the max_length is updated in the database. null & blank for auth_id and unique for email are not reflected on the database. I'm using postgres. -
How to get the first record of a 1-N relationship from the main table with Django ORM?
I have a Users table which is FK to a table called Post. How can I get only the last Post that the user registered? The intention is to return a list of users with the last registered post, but when obtaining the users, if the user has 3 posts, the user is repeated 3 times. I'm interested in only having the user once. Is there an alternative that is not unique? class User(models.Model): name = models.CharField(max_length=50) class Post(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', related_query_name='posts') created = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'created' ordering = ['-created']` I already tried with selected_related and prefetch_related, I keep getting multiple user registrations when they have multiple Posts. user = User.objects.select_related('posts').all().values_list('id', 'name', 'posts__title', 'posts__created') This does give me the answer I want, but when I change the created field to sort by date, I don't get the newest record, I always get the oldest. user = User.objects.select_related('posts').all().values_list('id', 'name', 'posts__title', 'posts__created').distinct('id') -
Render a Django view with data classified in a one to many relationship
I have a one to many relationshiop: class SessionGPS(models.Model): start_timestamp = models.IntegerField() end_timestamp= models.IntegerField() class GPSData(models.Model): longitude = models.DecimalField(max_digits=15, decimal_places=13) lat = models.DecimalField(max_digits=15, decimal_places=13) session_new = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps") Each SessionGPS entry has multiple GPSData entries. A session is composed of a set of GPS coordinates. This set is in the model GPSData. I need to query SessionGPS based in start and end timestamps: def date_search(request): data = request.body.decode("utf-8") start=int(datetime.datetime.strptime(request.POST['start'], '%Y-%m-%d').timestamp()) end=int(datetime.datetime.strptime(request.POST['end'], '%Y-%m-%d').timestamp()) res = GPSData.objects.filter(session_new_id__inicio_sesion__gte=start,session_new_id__fin_sesion__lte=end) res = serializers.serialize("json", res) return HttpResponse(res, content_type='application/json') In this way I get all GPSData between the timestamps but are not classified by session, they are merged. I need to get the query like this: session 1 ->> all GPSData of that session 1 session 2 ->> all GPSData of that session 2 So in the template I can render like this: For GPSData in session 1 do something For GPSData in session 2 do something etc. I tried to return multiple queries to the view but it didn't worked. Thanks for any help. -
How can I add a Logout POST function to my HTML template that is written in vue?
I made my basic logout function here in my user's views. class SignOutView(View): def get(self, request): logout(request) return HttpResponseRedirect(reverse("home")) I called it in my user’s URLs. path( 'signout/', view=views.SignOutView.as_view(), name='signout', ), If I had a normal HTML template, I would call it normally with {% URL:users:logout %} But, what I have is an HTML from vue: const menu = `<MenuItems> <MenuItem> <a href="auth/logout"> Sign Out </a> </MenuItem> </MenuItems> ` My current logout is a href that makes a GET, but I want to change it, I want to add a POST here. I am looking for doing something like: <script type="text/javascript"> // get the anchor with dom and make the post </script> I am currently logging in and getting the csrf token. -
How to work with users on the Ory Hydra network in the Django system?
In my project, I use Django (as a backend development tool for multiple applications on the same network) and Ory Hydra (as a ready-made network for user authorization with the ability to use all applications from this network). Hydra is a tool thanks to which it is possible to work effectively with users, but it is important to transfer data about users locally from the applications that it uses. Below are the connection settings for the Django with Hydra add-on # Add import os to the beginning of the file import os import environ env = environ.Env() ... # We need to change a couple of settings here TEMPLATES ... # This tells django to use `mysite/templates` dir # for searching templates 'DIRS': [os.path.join(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', # Add this line to enable context processor # and have variables like `login_url` available # in templates 'django_ory_auth.context.processor', ], }, But as far as I understand, the server simultaneously creates all users from Hydra in the Django database in all networks at the same time, which significantly loads the database, although it may never use this particular application. How can I configure the system …