Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Django handling long request in another request?
Issue about django handling a long request(50sec) in another request(3sec). I have a POST request will return some infomation for user, in this request will call another api in the same app and it will query database and generate pdf report then upload to s3, it will cost about 50sec. How can I let first request return infomation to user and generate pdf api run in background? I have done some research, found Celery may be can handle this task, is this recommend? or anyone have advice? Thanks in advance!!! -
Django 3.0 update a model inside of a detailview
I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view. I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated. the model: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) the view class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm notescount = Project.objects.annotate(num_notes=Count('notes')) documentscount = Project.objects.annotate(num_documents=Count('project_documents')) todoscount = Project.objects.annotate(num_documents=Count('todo_group')) def form_valid(self, form): project = get_object_or_404(Project, id=self.kwargs.get('pk')) theform = form.save(commit=False) theform.project = project form.save() return super(CompanyProjectsDetailView, self).form_valid(form) the form class ProjectStatusForm(forms.ModelForm): class Meta: model = Project fields = ['status'] labels = {'status': 'project status'} widgets = { 'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}), } On the page I use this code to add the form <form action="" method="post"> {% csrf_token %} {{ … -
Deploying Django project on Window server with Nginx and Waitress issue
Basically, I follow all of the instructions from here: [https://github.com/Johnnyboycurtis/webproject#nginx-and-waitress] All things were going fine, the Django project was successfully deployed. But the problem that I faced was after I close the cmd of the running script of waitress (runserver.py): #runserver.py from waitress import serve from webproject.wsgi import application # documentation: https://docs.pylonsproject.org/projects/waitress/en/stable/api.html if __name__ == '__main__': serve(application, host = 'localhost', port='8080') the website stopped working immediately. After I run the runserver.py from cmd again, the website was back to work but stopped if I close my cmd again. The question is how do I keep my website alive without the cmd to running waitress, any help was appreciated. -
Direct assignment to the reverse side of a related set is prohibited. Use images.set() instead while using create()
I am building a simple images blog app, And I build two models and one with Parent ForeignKey. I made the serializer but when I try to create a new instance then it is keep showing me Direct assignment to the reverse side of a related set is prohibited. Use images.set() instead. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializer.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): return Gallery.objects.create(**validated_data) Then I also tried creating both model's instances separately. def create(self, validated_data): new_data = Gallery.objects.create(poll=1, images=validated_data["images"]) return new_data But it also showed me the same error it showed me before. I am new in Django-Rest-Framework, I have tried many times but it is still not creating. Any help would be much Appreciated. Thank You in Advance -
django getting declared with a lazy reference error
ı am developing a django project.After I deployed my project on aws,at first everything was fine.But after that have to create model.After migrations operand I get this error raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'psycholog.customusermodel', but app 'psycholog' isn't installed. How can I fix that? -
Fetch API post data is not transferring data to views.py in Django
I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API but it is not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong. views.py def home(request): if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) index.html <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" id="in3" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </div> </div> </form> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val = document.getElementById("value"); const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; form.addEventListener("submit", (e) => { e.preventDefault(); const newform = new FormData(); newform.append("dropdown_val", dropdown_val.value); newform.append("val", val.value); newform.append("csrfmiddlewaretoken", csrf); fetch("", { method: … -
Auto-update views.py
I created a function for editing tables but it is done by url address "get/by/int:pk/" and I need it to be done automatically after saving in Django Admin panel. How can I do that? def obj(request, pk,): reg = Registration.objects.get(pk=pk) room = Rooms.objects.get(pk=pk) if reg.room_bool == True: room.room_bool = True room.save() if reg.room_bool == False: room.room_bool = False room.save() how can this be implemented -
error deploy django app on digitalocen app platform
i tried to deploy my Django app from git hub to digital ocean, i didn't include a Dockerfile and used a basic image from digital ocean. when the app is launce I kept getting this error in the runtime log : [CRITICAL] WORKER TIMEOUT (pid:16) [WARNING] Worker with pid 16 was terminated due to signal 9 [INFO] Booting worker with pid: 36 my run command is : gunicorn --worker-tmp-dir /dev/shm xclusive.wsgi thank you for helping -
change max header size in django
I am using Django via gunicorn and Apache. In httpd.conf of Apache I have set globally (outside virtual host blocks) LimitRequestFieldSize 32000 and this seams to work. (Ssing curl sending 31995 Bytes to a static website results in Http response 200 while sensing 31996 Bytes results in 400.) When Django should return a JSON in a header (for a download request) I got: response.headers["content-length"] : 25544 len(response.headers['json']) : 8185 For me it seams like there is still a 8 kB limit somewhere. Is there a setting for this in the Django config. (As I found out it is not DATA_DOWNLOAD_MAX_MEMORY_SIZE.) -
Setting USER in Dockerfile prevents saving file fields (eg. ImageField) in Django
I am trying to containerize Django with Dockerfile and docker-compose.yml as defined below. I built the Dockerfile as (fiifidev/postgres:test) for the compose file. Everything works fine. However anytime I try to save a model with a file field (eg. ImageField or FileField), I get Permission Error PermissionError: [Errno 13] Permission denied docker. I suspect I am not adding the appropriate permission of user creation (useradd) in the Dockerfile (not sure). But when I remove the USER everything works fine. How can I fix this any help will be much appreciated. FROM python:3.10-slim-bullseye as base # Setup env ENV LANG C.UTF-8 ENV LC_ALL C.UTF-8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONFAULTHANDLER 1 FROM base AS python-deps # Install pipenv and compilation dependencies RUN pip install pipenv RUN apt-get update && apt-get install -y --no-install-recommends gcc # Install python dependencies in /.venv COPY Pipfile . COPY Pipfile.lock . RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy FROM base AS runtime # Copy virtual env from python-deps stage COPY --from=python-deps /.venv /.venv ENV PATH="/.venv/bin:$PATH" # Create and switch to a new user RUN useradd --create-home appuser WORKDIR /home/appuser/src USER appuser # Install application into container COPY --chown=appuser:appuser . . version: "3.9" services: web: image: fiifidev/postgres:test command: sh -c … -
how to use Django F() expression in `update` for JSONField
I have around 12 million records that I need to update in my postgres db (so I need to do it in an efficient way). I am using Django. I have to update a jsonfield column (extra_info) to use values from a different column (related_type_id which is an integer) in the same model. Trying to do it with an update. This seems to be the way to do it most efficiently. Example: Person.objects.all().update(extra_info={ "type": "Human", "id": F('related_type_id') }) This errors out with : "Object of type F is not JSON serializable". I thought the F() will give back the value of that column (which should be an integer) which should be serializable. Can this be done ? Or am I trying to do it in the wrong way. I don't really want to iterate in a for loop and update each record with a save() because it will take too long. There's too many records. -
Trying to make a 'friend request' signal in django but getting FOREIGN KEY constraint failed - Django
I am trying to make a feature where a student can send a teacher friend request and if the teacher accepts it, the student should get added to a students' list present in the teacher's profile model and the teacher should get added to the teachers' list present in the student's profile. To handle and store this relationship between sender and receiver I have made a different model (Relationship) and signal. But while the operation is being carried out by the signal I get this error FOREIGN KEY constraint failed Please look at my code below and correct me on what should I do to get rid of this error. teacher's profile model (TeacherDetail) class TeacherDetail(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) student = models.ManyToManyField(CustomUser, blank=True, related_name='students') # this is the student's list student's profile (StudentDetail) class StudentDetail(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) teacher = models.ManyToManyField(CustomUser, blank=True, related_name='teachers') # this is the teacher's list model that stores the sender and the receiver (Relationship) STATUS_CHOICES=( ('sent', 'sent'), ('pending', 'pending'), ('accepted', 'accepted') ) class Relationship(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender') # the student receiver = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='reciever') # the teacher status = models.CharField(max_length= 10, choices=STATUS_CHOICES) … -
Django UNIQUE constraint fails with composite primary key
I have searched for similar cases but they do not seem to question the model.save() method. I am new to Django and, following the standard methodology, have declared a class to map it to a ddbb (autoincremental id): class Crudos(models.Model): cuenta = models.CharField(verbose_name='Cuenta', max_length=100) concepto = models.CharField(verbose_name='Concepto', max_length=100, default='indefinido') magnitud = models.FloatField(verbose_name='Magnitud') fecha = models.DateField(verbose_name='Fecha') documento = models.FilePathField(verbose_name='Documento') class Meta: unique_together = ('cuenta', 'fecha',) The view that uses this class also populates the table: for index, row in df.iterrows(): data = Crudos(cuenta=row.Cuenta, concepto=row.Concepto, magnitud=row.Magnitud, fecha=row.Fecha, documento=row.Documento) data.save() The dataframe is generated from a file and the process works without problems the first time. If I use the same file twice, then I get the error message of UNIQUE constrain failed. Models.save() should be an update instead of an insert when trying to insert a register with the same unique combination of values. It does so when the primary key is included in the data to save. The problem comes when there is a need for a composite primary key, as it is the case of the Crudo class, which is reflected by the unique_together condition. It seems Django is not able to interpret that condition as one to execute an … -
Django: Add Minus Cart Button Using JQuery
My models: class Cart(models.Model): cart_id = models.CharField(max_length=255, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: verbose_name_plural = 'Cart' def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() is_active = models.BooleanField(default=True) def total(self): return self.product.price * self.quantity def __str__(self): return self.product My views: def _cart_id(request): cart_id = request.session.session_key if not cart_id: cart_id = request.session.create() return cart_id def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) try: my_cart = Cart.objects.get(cart_id=_cart_id(request)) my_cart.save() except ObjectDoesNotExist: my_cart = Cart.objects.create( cart_id=_cart_id(request), ) my_cart.save() try: cart_item = CartItem.objects.get(product=product, cart=my_cart) cart_item.quantity += 1 cart_item.save() except ObjectDoesNotExist: cart_item = CartItem.objects.create( product=product, cart=my_cart, quantity=1, ) cart_item.save() return redirect('cart') def cart(request, sub_total=0, quantity=0, cart_items=None, sale_tax=0): try: current_cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=current_cart, is_active=True) for item in cart_items: sub_total += (item.product.price * item.quantity) quantity += item.quantity sale_tax = round((7 * sub_total)/100, 2) except ObjectDoesNotExist: pass context = { 'sub_total': sub_total, 'quantity': quantity, 'cart_items': cart_items, 'sale_tax': sale_tax, 'grand_total': sale_tax + sub_total, } return render(request, 'cart.html', context) My template portion: <tbody> {% for item in cart_items %} <tr> <td class="product-thumbnail"><a href="{{ item.product.get_url }}"><img src="{{ item.product.image_1.url }}" alt=""></a></td> <td class="product-name"><a href="{{ item.product.get_url }}">{{ item.product.product_name }}</a></td> <td class="product-price"><span class="amount">${{ item.product.price }}</span></td> <td class="product-quantity"> <div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}" /></div> </td> <td class="product-subtotal"><span … -
AssertionError while working on django rest framework
I have this error, i don't know how to fix it AssertionError: Expected view ListingView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly class ListingView(RetrieveAPIView): queryset = Listing.objects.order_by('-list_date').filter(is_published=True) serializer_class = ListingDetailSerializer look_field = 'slug' urlpatterns = [ path('', ListingsView.as_view()), path('search/', SearchView.as_view()), path('<slug>/', ListingView.as_view()) ] -
Create object and display it in same page with htmx
The function I am trying to implement is that, when the form is submitted in the create view, I would like to display the created object beneath it without the page refreshing. I know the way to implement this is through HTMX. The object that is being created is a key which is unique and gets randomly generated. However it does not work properly. Right now, first time clicking the button it creates a key and displays it but the second time it tries to show the previous key and because it already exists it is not unique and therefore it shows nothing. This is the model class Key(models.Model): key = models.CharField(max_length=10, null=False, default=get_random_string(length=10), unique=True) amount = models.IntegerField(default=1) created = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse("key", kwargs={"id": self.id }) I have two views, a create view and a detail view, I would have liked to used CBV but I can't get my head around how I would implement that, so I am sticking to function based views. Right now the views are looking like this @login_required def key_create_view(request): form = CreateKeyForm(request.POST or None) context = { "form": form, } if form.is_valid(): obj = form.save(commit=False) obj.save() kod_url = reverse('key', kwargs={'id':obj.id}) if request.htmx: … -
Getting error in Linux printing Security group in azure
I have this code and I have written it in windows. and it works fine in windows but when I run it on Linux and I have to run it on Linux as of my project needs and it does not works there and gives me the following error AttributeError: 'ServicePrincipalCredentials' object has no attribute 'get_token' from azure.mgmt.security import SecurityCenter from azure.common.credentials import ServicePrincipalCredentials import Credentials from pprint import pprint client = SecurityCenter(Credentials.credential,Credentials.subscription_id,asc_location="") for score in client.secure_scores.list(): print(score) -
How to retrieve integer from database objects
I'm fairly new to Django and try to get a database for scientific reviews up and running. One of the things I would like to show is how many reviews have been published in each year. In this example I used the following data: | year | number of reviews published | | ---- | --------------------------- | | 1999 | 1 | | 2019 | 4 | | 2022 | 5 | models.py class Review(models.Model): title = models.CharField(max_length=100,null=True) doi = models.URLField(max_length=200,unique=True,null=True) author = models.CharField("First author",max_length=100,null=True) year = models.PositiveIntegerField(null=True) views.py from django.shortcuts import render from .models import Review from django.db.models import Count def about(response): reviews_year_count = Review.objects.values('year').annotate(Count('year')) context = {'reviews_year_count':reviews_year_count} return render(response, "main/about.html", context) reviews.html <html> <body> {{reviews_year_count|join:", "}} </body> </html> output on localhost Currently: {'year': 1999, 'year__count': 1}, {'year': 2019, 'year__count': 4}, {'year': 2022, 'year__count': 5} Aim: 1, 4, 5 What I can't figure out is how to get rid of the {'year': 1999, 'year__count': } and only have the integer value there. I looked at Django documentation pages. One of the things I tried was add defer() behind reviews_year_count = Review.objects.values('year').annotate(Count('year')) but calling defer()after values() doesn’t make sense according to documentation. My aim is to use the data as … -
Why is the csrf cookie set when sending POST request to localhost:8000, but not when sending POST request 127.0.0.1:8000?
Why is the csrf cookie set when sending POST request to localhost:8000, but not when sending POST request 127.0.0.1:8000? Django then complains that the CSRF cookie is not set. (Assuming I open the frontend using localhost:3000, then same phenomenon occurs when opening the frontend script using 127.0.0.1:3000 but this time POST requests go through only to 127.0.0.1:8000). Basically, I'm interested on how to configure things in order to be able later on to serve the frontend (React in my case) and the backend (Django) from two different domains. For now I have no login feature etc. so CSRF protection makes no sense. However I'm interested, why with the current configuration, I'm not able to do cross origin requests (POST) with the CSRF token being in the header. So here is my code: Frontend: export async function post_request_to_backend_with_csrf(url : string, data: {[key: string] : string}, headers: AxiosRequestHeaders | undefined = undefined) : Promise<AxiosResponse<any, any>> { // get csrf token var csrftoken = getCookie('csrftoken'); if (csrftoken === null) { await getCSRFToken().then( (response) => { csrftoken = getCookie('csrftoken'); } ). catch((e) => console.log(e)) } var headers_arg : AxiosRequestHeaders = {'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken!, 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}; for (let key in headers) { … -
Recuperar dados do Banco de Dados com Python [closed]
Bom dia. Não consigo retornar para o templete as informações que estão no Banco de dados, ou seja quando carrego o html, não aparece as informações do bd que estão sendo chamadas. Tô fazendo essa aplicação em Python utilizando o Django. Models.py `from django.db import models cursos = ( ('1','Técnico em informática para Internet'), ('2','Técnico em Agropecuaria'), ('3','Técnico em Agroindustria') ) class Postagem(models.Model): titulo = models.CharField(max_length=100) descricao= models.TextField() imagem = models.ImageField(blank = True) cursos = models.CharField( max_length= 3, choices = cursos, ) def __str__(self): return self.titulo def __str__(self): return self.descricao def __str__(self): return self.imagem def __str__(self): return self.cursos` Views.py from multiprocessing import context from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render,redirect from .models import Postagem 'def listar(request): postagens = Postagem.objects.all() context = { 'postagens': postagens} return render(request,'post/listar.html', context)' urls.py from django import views from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.listar, name = 'listar') ] listar.html <h1> Suas postagens </h1> {{postagem.titulo}} { % for postagem in postagens % } <span> <a href="/editar/{{postagens.id}}"> {{postagens.titulo}}</a> </span> <span> <a href="/excluir/{{postagens.id}}"></a> </span> <span> <a href="/nova/{{ppstagens.id}}"></a> </span> { % endfor % } como aparece na tela: post/ -
Django deployment(Elastic Beanstalk) Following services are not running: web
Hi I got error like this: Django deployment(Elastic Beanstalk) Following services are not running: web. When trying to deploy my web app to elastic beanstalk, everything is ok, logs are clear. Can u help me? -
Problems with static files django, IIS and windows 10
Problems with static files django, IIS and windows 10 Hi I have Python 3.10.4, Django 4.0.4 and wfastcgi 3.0.0 installed. This on windows server 2016 and the latest version of IIS as of 05/20/2022. I have already run the command manage.py runserver collectstatic. Does not show static files when viewing the web application on the internet. This file is web.config which is outside the project folder. <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" /> <add name="Proyectoqr" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python35\python.exe|C:\Python35\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\proyectoqr" /> <add key="WSGI_HANDLER" value="proyectoqr.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="proyectoqr.settings" /> </appSettings> </configuration> This is the content of the web.config file in the static folder <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read"/> </handlers> </system.webServer> </configuration> I already added the virtual directory of the static folder with direction to the static folder of the project as shown in the following image. Add virtual directory image If you need more information tell me to show you the code or configuration -
Annotate a query with Django
Hello I am trying to annotate a query but it does not work ... Here is my query : animal = Animal.objects.first() test = Test.objects.filter(a=3).annotate(name=Case(When(animal in test.user.all(), then=Value('withanimal')), default=Value('notwithanimal'),)) But I got 'QuerySet' object has no attribute 'user'. I precise the field user is a ManyToManyField. Could you help me please ? Thank you very much ! -
how to assign an id to an item when clicking on a link beside it in Django?
I'm trying to assign an id to a CSV file's name so that when I click on a link beside I can access the CSV file itself on another web page to view it. but I keep getting this error 'QueryDict' object has no attribute 'objects' Note: the CSV files are taken from a form and saved in a file on the PC, I'm trying to retrieve the file from the PC itself. This is the views.py def read_datasets(request): file = request.POST.objects.get(id=id) # print(file) path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" # csv_file = request.FILES['file2'] # csv_file = request.POST.get('file2') path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) # dataframes_list_html = [] file_names = [] # file_name = csv_file.name for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) # dataframes_list_html.append(temp_df.to_html(index=False)) file_names.append(files[i]) # print(dataframes_list_html) return render(request,'blog/view_datasets.html',{'names': file_names}) def one_dataset(request): path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) return render(request, 'blog/single_dataset.html', {'dataframes':dataframes_list_html}) and the HTML File <body> {% for dataframe in dataframes %} <div id="customers"> {{ dataframe|safe }} <hr> </div> {% endfor %} </body> -
Resolving Delete event failure in Django
This is error I have been trying to solve for last 7 days. I am a newbie to Django Page not found (404) Request Method: POST Request URL: http://localhost:8000/projects/delete-project/ce4c5177-eb8f-44b9-9734-04adafd75414/ Using the URLconf defined in devsearch.urls, Django tried these URL patterns, in this order: admin/ projects/ projects/ [name='projects'] projects/ project/<str:pk>/ [name='project'] projects/ create-project/ [name='create-project'] projects/ update-project/<str:pk>/ [name='update-project'] projects/ delete-project/<str:pk>/ [name='delete-project'] This message appears after clicking the submit button on my delete-object form which correctly refers to the object being deleted name attribute...which in my mind means the object has been found in the database and is being correctly referenced. Here is the Code: url.py of the application from django.urls import URLPattern, path from . import views urlpatterns = [ path('projects/', views.projects, name='projects'), path('project/<str:pk>/', views.project, name='project'), path('create-project/', views.createProject, name='create-project'), path('update-project/<str:pk>/', views.updateProject, name='update-project'), path('delete-project/<str:pk>/', views.deleteProject, name='delete-project'), ] View Function Code: @login_required(login_url='login') def deleteProject(request, pk): profile = request.user.profile project = Project.objects.get(id=pk) if request.method == 'POST': project.delete() return redirect('account') context = {'object': project} return render(request, 'delete-object.html', context) Confirmation HTML Page <form class="form" method="POST" action="'"> {% csrf_token %} <p>Confirm deletion of '{{object}}'</p> <button class="btn btn--sub btn--lg my-md"><a href="{{request.GET.next}}">Go Back</a></button> <a href="delete-object" ><Input class="btn btn--sub btn--lg my-md" type='submit' value='DELETE' style="color: red;" /></a> </form> Create, Read, and Update …