Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with legacy database and foreign keys where id=0
I am working with data that has been migrated from a PHP-based MySQL database to Django. In this PHP database they used foreign keys where the id = 0. So naturally when I try to insert a record that references a foreign key of 0 I get the following: "The database backend does not accept 0 as a value for AutoField." Fair enough. It seems this was done to protect folks from MySQL's use of using 0 to auto generate a primary key: https://code.djangoproject.com/ticket/17713 However there appears to be a way to write a "custom backend" to work around this: https://www.mail-archive.com/django-users@googlegroups.com/msg187956.html This seems less than optimal for something that appears to have a session-based solution of setting the following in the MySQL session: SET SESSION SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; Barring switching the database or other hacks to make this work are there better options to get Django and MySQL to play together with id=0? -
OperationalError at /result unable to open database file
I have this error for 2 days now I triyed everything in the other topics nothings works for me. The code of the app was written in linux, but i got the folder and connected it to my project as an app, in this project there is 3 apps that are connecting good to the database, only this one gives an error unable to open data base. I'm using Windows on Localhost, a friend triyed on windows and it's working for him, only for me not working. Note : When I go to localhost:8000/admin I can see the model created on the database. PLEASE HELP! Django Version: 2.2.3 I have tryied to give permissions of the folder on it's proprieties to read and write, tryied to change path of DIR, I switched from sqlite3 to postgres, made full path in database and not full one, triyed all the recommandations on topics but still shows the error Settings. py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'devee', 'USER': 'postgres', 'PASSWORD': 'thepasswordichoosed', 'HOST': 'localhost', 'PORT': '5432', } } Environment: Request Method: POST Request URL: http://localhost:8000/result Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', 'account', … -
input fields not displaying on templates
i am new to django when i try to run this project i wasn't getting any input fields in my template current page was only showing the given labels i don't know where i've gone wrong can any of you guys help?? these are my models.py file from django.db import models # Create your models here. class Student(models.Model): sid = models.CharField(max_length=100) sname = models.CharField(max_length=100) sclass = models.CharField(max_length=100) semail = models.EmailField(max_length=100) srollnumber = models.CharField(max_length=100) scontact = models.CharField(max_length=100) saddress = models.CharField(max_length=100) class Meta: db_table = "student" the are my forms.py file from django import forms from student.models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = "__all__" these are my views.py file from django.shortcuts import render from student.models import Student from student.forms import StudentForm def student_home(request): return render(request, 'employee/dash.html') def add_student(request): if request.method == "POST": form = StudentForm(request.POST) if form.is_valid(): try: form.save() return render(request, 'employee/dash.html') except: pass else: form = StudentForm() return render(request, 'student/addstudent.html') template <!DOCTYPE html> <html lang="en"> <head> <title>addstudent</title> </head> <body> <a href="/home" >home</a> <form method="POST" action="/add_student"> {% csrf_token %} <label>Student ID:</label> {{ form.sid }} <label>Name :</label> {{ form.sname }} <label>Class :</label> {{ form.sclass }} <label>Email ID:</label> {{ form.semail }} <label>Roll Number :</label> {{ form.srollnumber }} <label>Contact :</label> … -
Cache manager does not delete my cache after specifying inactive time
I have a django app connected to an S3 bucket and a postgres database. To reduce egress costs by downloading s3 contents every pull, I am trying to setup a cache folder using an Nginx server. I want to download s3 objects and keep them in cache for some time till it becomes stale. I have setup nginx.conf file with: 1. send_file = off 2. tcp_push = off 3. tcp_node_delay = off (read this somewhere on stackoverflow) I have also pointed to the sites-enabled folder. Within this conf file I have set: 1. proxy_cache_path /home/clyde/Downloads/new/automatic_annotator_tool/queried_data/ levels=1:2 keys_zone=my_cache:100m max_size=1g inactive=1m use_temp_path=off; Is this enough?? I am new to Nginx and these problems are turning out to be cumbersome. I expect the cached folder to retain downloaded contents from the django application for some time and then either get deleted or resynced from the db. TIA -
Django lists url but gives 404 not found
Page not found, but correct url is listed I'm really confused here: I get this error saying page not found, then it lists the url it can't find????? What is wrong here? Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/si/project/2/ Using the URLconf defined in django_version.urls , Django tried these URL patterns, in this order: login/[name='login'] logout/[name='logout'] password_change/[name='password_change'] password_change/done/[name='password_change_done'] password_reset/[name='password_reset'] password_reset/done/[name='password_reset_done'] reset/<uidb64>/<token>/[name='password_reset_confirm'] reset/done/[name='password_reset_complete'] [name='blog-list'] create/[name='blog-create'] <int:id>/[name='blog-detail'] <int:id>/update/[name='blog-update'] <int:id>/delete/[name='blog-delete'] si/[name='project-list'] si/create_project[name='create_project'] si/project/<int:pk> [name='project_detail'] <-- is this not my url? admin/ about/ [name='about_view'] register [name='register'] ^media/(?P<path>.*)$ The current path, si/project/2/ , didn't match any of these. -
Can I print just the content of a html template in django?
I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me. I want to print this page by clicking a button. Now, I am just trying to generate the pdf first. I want just to print the content. I tried these functions. #views.py from django.views.generic.detail import DetailView from MagasinProject.views import PdfMixin from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator from django.contrib.auth.models import User from django.shortcuts import render def test_view(request): resp = HttpResponse(content_type='application/pdf') result = generate_pdf('demande/demande.html', file_object=resp) return result #urls.py from django.urls import path from . import views from django.conf.urls import url urlpatterns=[ path('demande',views.index, name='demande'), url(r'^test_view$', views.test_view), ] -
In Django, how to create self-referencing, truly symmetrical ManyToMany relationship with some additional fields under that relationship(in 2019)?
I know this type of question has been asked many times before. I’ve referred those questions and they’ve helped me to reach what I’ve implemented till now. Problem is that they don’t solve the specific problem I am facing and their solutions are at least an year old. I’m hoping that some better solution might have been discovered till now for the problem that Django has faced for years with self-referencing symmetrical ManyToMany relationship. May be there is third party library I don’t know about. I’ve a model that gives details about a stadium. Once user is on the page of stadium, there’ll be list of other stadiums which are in neighbouring vicinity to current stadium, along with their distances from current stadium. I want to implement this in django. So, suppose there are two stadiums , Stadium A and stadium B which are closer to each other. Then adding stadium B as neighbour of stadium A should automatically create stadium A as neighbour of stadium B. This is different than facebook friends or twitter followers. In facebook, symmetrical relationship is not established as long as friend request isn’t accepted by the person whom request has been sent. So, person … -
Slow Page Load Times
I have a table which is populated via a RESTful API call to a database. For one particular table column, its data is pulled by referencing an ID from the main API call and then using said ID as a parameter for a second API call. However, there may be 1,000 or more rows of data in the table, so iterating through all these rows and performing the second API call is causing very slow page load times (up to 40 seconds). Is there any way I might handle this issue? I can limit the number of records returned per query, but ideally I would include all records available. Please let me know if any other information is needed. views.py cw_presales_engineers = [] for opportunity in opportunities: try: opportunity_id = str(opportunity['id']) presales_ticket = cwObj.get_tickets_by_opportunity(opportunity_id) if presales_ticket: try: cw_engineer = presales_ticket[0]['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' connectwise_zip = zip(opportunities, cw_presales_engineers) -
Django: multiple update
I want to update multiple instances of my models. I can currently update them one by one just fine. I want to be able to update them with a PUT request to my URL: www.my-api.com/v1/mymodels/ with the request data like so: [ { "mymodel_id": "id1", "name": "foo"}, { "mymodel_id": "id2", "alert_name": "bar"} ] If I try it this way now, I receive the following Django error: Serializers with many=True do not support multiple update by default, only multiple create. For updates it is unclear how to deal with insertions and deletions. If you need to support multiple update, use a `ListSerializer` class and override `.update()` so you can specify the behavior exactly. My model has a Serializer class ModelSerializer class MyModelSerializer(ModelSerializerWithFields): class Meta: model = MyModel fields = "__all__" def to_representation(self, instance): data = super().to_representation(instance) if instance.name is None: del data['name'] return data ModelSerializerWithFields extends serializers.ModelSerializer. At which level do I need to use the ListSerializer class? ie: in ModelSerializerWithFields or in MyModelSerializer? Or somewhere else completely? If anyone has any examples of this implementation, I'd be very grateful -
Update BD with django backend and post form via ajax
Given that I have my userPersonalized model. And this has 2 fields that I want to update through a form, where they enter a numerical value and in doing so, a mathematical operation is done. Well, I want the result of that mathematical operation to update the logged-in user fields, according to the numerical value entered. I'm importing Jquery's library. Through 2 input hidden I access the 2 fields that I want to update through the mathematical operation, which I have in my javascript file where I call it through the id html file <div><form method="POST" class="form-data" action="{% url 'solit' %}"> {% csrf_token %} <h6>Tipo de peticion:{{form.petit}}</h6> <h6>Razon:{{form.razon}}</h6> <h6>{{form.solicitudes_id}}</h6> <h6>Fecha inicio:{{form.periodo_init}}</h6> <h6>Fecha fin:{{form.periodo_fin}}</h6> <h6>Introduzca dias a tomar<input id="dias" type="number" name="dias_adicion"></h6> <h6>Introduzca horas a tomar<input id="horas" type="number" name="horas_adicion"></h6> <input type="hidden" id="const_dias" name="d_pendientes" value="{{ user.d_pendientes }}"> <input type="hidden" id="const_horas" name="h_pendientes" value="{{ user.h_pendientes }}"> Recuerde, que usted dispone de {{ user.d_pendientes }} dias y {{ user.h_pendientes }} horas a compensar <br> <button type="submit" onclick="calculo()" class="boton">Guardar</button> js file ------------------------------------------------------------ function calculo() { var dias = parseInt(document.getElementById('dias').value); var horas = parseFloat(document.getElementById('horas').value); var dias_base = parseInt(document.getElementById('const_dias').value); var horas_base = parseFloat(document.getElementById('const_horas').value); dias_base -= dias; horas_base -= horas; alert(dias_base); alert(horas_base); } console.log(calculo); ajax script---------------------------------------------------- $(document).ready(function(){ var productForm = … -
How to delete first N items from queryset in django
I'm looking to delete only the first N results returned from a query in django. Following the django examples here which I found while reading this SO answer, I was able to limit the resulting set using the following code m = Model.objects.all()[:N] but attempting to delete it generates the following error m.delete() AssertionError: Cannot use 'limit' or 'offset' with delete. Is there a way to accomplish this in django? -
Django: Online Users
I am following this solution to show whether a user is online or not. But when I try to add: 'userprofile.middleware.ActiveUserMiddleware', to MIDDLEWARE_CLASSES, I get a 502. {{ profile.online }} returns false Thank you for any help. -
locale folder in the root folder is ignored
Default language is french on my website. I run django-admin makemessages -l en and then django-admin compilemessages. When I make translations in apps, it works fine. However, in the root folder, locale folder seems to be ignored. I thought it would always try to find a translation there if it doesn't find it in other places. I also tried to add LOCALE_PATHS = ['../locale'] but it doesn't fix it. -
Can't get inputs from html form
I want to create a webapp in Django that converts orders in pdf to excel file. To be more flexible i want to retrive text from pdf and pass it to form on HTML page to be editable. If everythig will be ok then i want to download excel file with data from inputs. There is several inputs (depending on how much rows is in pdf with order) and i want to pass it all to my app. But below code dont work. Only result i have is token and value from button. print(request.POST.keys()) print(request.POST['Submit']) print(request.body) <form action="extract_pdf" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Company ID</label> </div> <select class="custom-select" id="inputGroupSelect01"> {% for item in company %} <option value="a">{{item.1}}</option> {% endfor %} </select> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="company_name">Company Name</span> </div> <input type="text" class="form-control" id="name" aria-describedby="basic-addon3" value="{{info.company_name}}"> </div> </div> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="order_no">Order Number</span> </div> <input type="text" class="form-control" id="ord_no" aria-describedby="basic-addon3" value="{{info.order_number}}"> </div> </div> </div> {% for row in rows %} <div class="row"> <div class="col-sm"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="item_nr">Jeeves Code</span> </div> <input type="text" class="form-control" id="item" aria-describedby="basic-addon3" value="{{row.item}}"> … -
How can I get information from my ubuntu server?
I have a ubuntu server. This serve crawling data by apache2, python3 and django. And I start to make android with android studio. I want to get data in android app from my server. How can I get information from my ubuntu server? -
django rest framework filter_backends class called before permission_classes class
I have a DRF view-set with a custom permission and filter. In DRF's official docs it says: Permission checks are always run at the very start of the view, before any other code is allowed to proceed. But I have noticed that my filter_backend class is called before permission_class. Here is my code: # my permission from rest_framework import permissions class CompanyAccessPermission(permissions.BasePermission): message = 'Detail of company not allowed.' def has_object_permission(self, request, view, obj): print("permission") return request.user in obj.users.all() # my filter from rest_framework import filters class IsCompanyOwnerFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): print("filter") return queryset.filter(users__in=[request.user]) # my view from rest_framework import mixins, viewsets from rest_framework.permissions import IsAuthenticated from api import filters, permissions, serializers from core import models class CompanyViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated, permissions.CompanyAccessPermission) filter_backends = [filters.IsCompanyOwnerFilterBackend] queryset = models.Company.objects.all() serializer_class = serializers.CompanySerializer So when I want to retrieve a Company object the output is as follows: > filter > permission I was expecting the opposite of that. I also looked at the source code of DRF class GenericViewSet(ViewSetMixin, generics.GenericAPIView). It seems like the permission class (called in views.APIView) is called before the filter backend class (called in generics.GenericAPIViewi which inherits views.APIView). What am I missing? -
Django dynamic links using multiple fields
I have a url set up dynamically for a project using: path('project/<int:pk>', ProjectView.as_view(), name='project') How can I make this so I can use two parameters, something like this: path('project/<int:pk>/<int:category', ProjectView.as_view(), name='project') So I need to set up links to each category, so the user will see only the updates from Project A category 1 of 7. -
"Error 0x80070057: The parameter is incorrect" when unzipping files
I created a function to create multiple report pdfs with weasyprint, zip them together and download the zip file. When trying to extract the folder on Windows 10 with the in-house zip program i get this error: "An unexpected error is keeping you from copying the file. [...] Error 0x80070057" I can skip the error and the files get extracted. In the best case scenario I'd like to prevent this error though. def get_all_shareholder_reports(request): current_shareholders = list(models.objects.all()) zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "a") as zip_file: for shareholder in current_shareholders: pdf_file_handle = io.BytesIO() context_dict = get_report_details(pk=shareholder.shareholder_id) html_string = render_to_string('tempalte.html', context_dict) html_handler = HTML(string=html_string, base_url=request.build_absolute_uri()) html_handler.write_pdf(target=pdf_file_handle) pdf_file_handle.seek(0) pdf_string = pdf_file_handle.getvalue() pdf_file_name = 'Shareholder_Report_' + pdf_file_name = 'Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename, context_dict['shareholder'].surname, datetime.datetime.now().strftime( "%d_%m_%Y_%H:%M:%S")) zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string) zip_buffer.seek(0) response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip' return response -
How do I check if a many-to-many relationship exists in a Django template?
In this code example, "teaches_for" is the name of a many-to-many field that relates a Performer model to a School model. I want to include this particular block only if at least one relationship between a Performer and a Teacher model exists. Here's my non-working code: {% if performer.teaches_for.exists %} <h3>{{performer.first_name}} teaches at these schools...</h3> <ul> {% for school in performer.teaches_for.all %} <li><a href="/schools/{{school.id}}">{{ school.name }}</a></li> {% endfor %} </ul> {% endif %} The line that's wrong is {% if performer.teaches_for.exists %}. What can I replace it with which will be True if at least one relationship exists, but False otherwise? -
Django - Getting value from dropdown menu + button
I've done some searching already. I have a program which will do some analysis based on a given country. The HTML form is: <p>Select a country:</p> <select form="countrySelection" id="countrySelect" required> <option value=""></option> <option value="BELGIUM">Belgium</option> <option value="FRANCE">France</option> <option value="ITALY">Italy</option> </select> <form action="/analysis" id="countrySelection" method="GET"> <br> <input class="button" name="countrySubmit" type="submit" value="Start"> </form> In my urls.py I have: path('', views.index, name='index'), path('analysis/', views.run, name='run'), I want to get the value of the dropdown menu (BELGIUM/FRANCE/ITALY) upon clicking the button and then send it to the view run: def run(request): country = ... [...] return HttpResponse("Completed.") I have tried to use "request.GET.get('country') and other methods with no luck. -
How to upload and retrieve multiple photos in Django
I have a gallery page in which i want to display all actor/actress/movie/event photos.I get the photos on daily basis. I want to store the images in static media section. Here I have 2 questions. 1) What is best method to store and retrieve the gallery images in django? (Each movie/event/actor/actress may have multiple images) 2) How the folder structure should be in terms of SEO? like date/actor/{1,2,3} or eventname/{1,2,3} Using image filed I was able to upload and display single image. None of the articles showing how to upload multiple images. -
How to implement views.py in django for the structure multiple slug
I have path('<bloger_slug>-<category_slug>-products/', product_list, name='product_list'), how to make views.py for this url -
'WSGIRequest' object is not subscriptable in django
I'm getting this error in the below function in my views.py file. I don't know what 'WSGIRequest' is or why it's throwing an error. Here the settings.MEDIA_ROOT means it will list all the files in that directory def run_existing_query(request): context = {} print(settings.MEDIA_ROOT) context["download"] = "" context["list_of_queries"] = os.listdir(settings.MEDIA_ROOT) if request.method == "POST": MODULE_DIR = 'settings.MEDIA_ROOT' py_file = glob.glob(os.path.join(MODULE_DIR, request['selected_query']+'.py')) module_name = pathlib.Path(py_file).stem module = importlib.import_module(module_name) qe = module.QueryExecutor() #Query executor is Class name context["download"] = "Hello" return render(request, "run_existing.html", context) Why am I getting this error? -
How to copy a model instance to another model based on attribute value in Django
I want to copy a model instance from my Tasks class into my CompletedTasks class if and only if the progress attribute in my Tasks object is set to "completed". The I want to delete the object from the Tasks class. How do i set it up to automatically do this when a user edits a task and inputs completed for progress I tried a few different methods, but I am not exactly sure how to go about this. The function completedTasks(self,id) below is what I currently have, but it doesn't do anything. class Tasks(models.Model): progress = models.ForeignKey(Progress, max_length=20, on_delete=models.CASCADE) def completedTasks(self, id): instance = Tasks.objects.get(pk = id) if(instance.progress == "completed"): temp = CompletedTasks() temp = instance temp.save() instance.delete() class CompletedTasks(Tasks): -
why Django suit is not loading style
so i have installed django suit theme from their documentation as instructed but when i load their theme its not loading the style and its looking just like a skeleton a pic of the admin panel theme any one knows how can i fix it or even a recommendation of a better theme would be accepted my project apps.py: from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig): layout = 'horizontal'