Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django admin class model issue
class TheList(admin.ModelAdmin): list_display = ['name', 'age'] actions = None I want to see a list in admin panel as readonly. If I use the below method it will show a list of objects which then need to be clicked on in order to display the name and age. readonly_fields = ['name', 'age'] I have tried using the below admin functions which didn’t fix the problem: has_delete_permission has_add_permission The list is still editable I tried using this with list_display: has_change_permission that made the class not viewable in admin panel I want it to be like list_display but readonly, is that even possible? -
Make another dataframe from pandas or make another table
mates, tried for 3 days to deal it with my own but unsuccesfully... I have these models: A patient: class Patient(models.Model): <...> hist_num = models.IntegerField(validators=[MinValueValidator(0)], primary_key=True) <...> def __str__(self): return f"{self.first_name} {self.last_name}" Group of labaratory Analysis: class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) # analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" An analysis (haemoglobin and etc.): class AnalysisType(models.Model): a_name = models.CharField(max_length=16) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) analysis_group = models.ManyToManyField(AnalysysGroup) And a patient analysis: class PatientAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1) analysis_data = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) I try to get a table with all analysis of my patient per day and sort by analysis types. My query seems like this analysis_qs = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date').distinct() df1 = pd.DataFrame(analysis_qs.values('analysis_type','analysis_date','analysis_data')) <...> return df1.to_html() And gives me: Result of {{df1 | save} I want to see sth like ideally + measurments | Data | Haemoglob| Red blood| Leuc | | -------- | -------- | -------- | -------- | | Data | Result | Result | Result | | Data | Result | Result | Result | -
Secure Django REST Api with react and keycloak
I'm new to the world of keycloak. I have a little trouble understanding some things. I understood well how to authenticate with React and get a JWT token. However I would like to protect a Django API with this JWT Token retrieved with React. And I don't see how to do it. The resources are scarce or from several versions. I am with Keycloak 20. Thx in advance. -
ImportError: cannot import name 'views' from project (C:\django_projects\project\project\__init__.py)
This is my first Django project. I tried to execute the code available at: https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ Just made few changes such as removed staff module and modified the file names. The tree structure of my project is shown below: c: manage.py project asgi.py settings.py urls.py wsgi.py __init__.py media static templates sudent_information_system admin.py │ Admin_Views.py │ apps.py │ base.html │ contact.html │ forms.py │ login.html │ models.py │ registration.html │ Student_Views.py │ tests.py │ views.py │ __init__.py │ ├───migrations │ __init__.py │ ├───templates │ home.html │ └───__pycache__ admin.cpython-37.pyc apps.cpython-37.pyc models.cpython-37.pyc __init__.cpython-37.pyc The code in urls.py is as follows: The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from . import views from . import HodViews, StudentViews urlpatterns = [ path('admin/', admin.site.urls), path('', include('sudent_information_system.urls')), path('', views.home, name="home"), path('contact', views.contact, … -
AxiosError: Request failed with status code 403 - login and token
auth.js export async function loginUser(data) { const response = await axios.post( 'http://10.0.2.2:8000/api/rest-auth/login/', { username: data.username, password1: data.password, }, { headers: { "Content-Type": "application/json", } } ); console.log(response.data) LoginScreen.js import { useState } from 'react'; import LoadingOverlay from '../../components/ui-components/LoadingOverlay'; import AuthContent from '../../components/auth-components/AuthContent'; import { loginUser } from '../../util/auth'; function LoginScreen() { const [isAuthenticating, setIsAuthenticating] = useState(false); async function loginHandler(username, password1) { setIsAuthenticating(true); await loginUser(username, password1); setIsAuthenticating(false); } if (isAuthenticating) { return <LoadingOverlay message="Logging you in..."/> } return <AuthContent isLogin onAuthenticate={loginHandler}/>; } export default LoginScreen; setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } I've tried logging into both the REST API and Postman, and everything works fine - it returns the token to me once the right credentials are issued. But when I try to send the request via the login form from react native to django via axios, it gives me the error 403 forbidden by axios. On the contrary, the registration makes me carry it out both via REST API and via the registration form (React Native) and returns the token. -
Is it possible to calculate direction in Postgis & Django (GeoDjango)?
Is it possible to calculate direction to detect if users are moving in "similar" direction having a few of their last coordinates(Points) using PostGIS + Django (https://docs.djangoproject.com/en/4.1/ref/contrib/gis/)? I could't find information about this feature. -
Trying to get ForeignKey's names instead of pk in a QuerySet Django
Im trying to make a complex queryset and I want to include my ForeignKeys names instead of pk. I'm using ajax to get a live feed from user inputs and print the results on a DataTable but I want to print the names instead of the pk. Im getting a queryset and when I console.log it, sensor_name is not in there. My models are like this: class TreeSensor(models.Model): class Meta: verbose_name_plural = "Tree Sensors" field = models.ForeignKey(Field, on_delete=models.CASCADE) sensor_name = models.CharField(max_length=200, blank=True) class TreeSensorMeasurement(models.Model): class Meta: verbose_name_plural = "Tree Sensor Measurements" sensor = models.ForeignKey(TreeSensor, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) soil_moisture_depth_1 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_2 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_1_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_moisture_depth_2_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_temperature = models.DecimalField(max_digits=15, decimal_places=2) And my view looks like this: field_list = Field.objects.filter(user=request.user) tree_sensors = TreeSensor.objects.filter(field_id__in=field_list.values_list('id', flat=True)) Tree_Metrics = request.GET.getlist("Tree_Metrics[]") if Tree_Metrics is not None: for array in Tree_Metrics: From_T.append(array.split(',')[0]) To_T.append(array.split(',')[1]) try: statSensors = (TreeSensorMeasurement.objects .filter(sensor_id__in=tree_sensors.values_list('id', flat=True)) .filter(datetime__date__lte=To_T[0]).filter(datetime__date__gte=From_T[0]) .filter(soil_moisture_depth_1__lte=To_T[1]).filter(soil_moisture_depth_1__gte=From_T[1]) .filter(soil_moisture_depth_2__lte=To_T[2]).filter(soil_moisture_depth_2__gte=From_T[2]) .filter(soil_temperature__lte=To_T[3]).filter(soil_temperature__gte=From_T[3]) .order_by('sensor', 'datetime')) TreeData = serializers.serialize('json', statSensors) except: TreeData = [] The code above works correctly but I cant figure out the twist I need to do to get the TreeSensors name instead of pk in the frontend. An example … -
Registration form is not submitting
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django. This is the registration form <h1>Register</h1> <div> <form method="POST" action="{% url 'register' %}"></form> {% csrf_token %} {{ form.as_p}} <input type="submit" value="register" /> </div> Below is the views.py ` def register_page(request): form = CustomUserCreateForm() if request.method == 'POST': form = CustomUserCreateForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() login(request, user) return redirect('login') page = 'register' context={'page':page, 'form':form} return render(request, 'login_register.html', context) ` The forms.py ` class CustomUserCreateForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'name', 'password1', 'password2'] ` Its not throwing any error, rather just not submitting. I tried changing the input to button feature but it is still not working. Any Ideas?