Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest freamwork comment
I have two questions about creating messages about products. My first question is why do I have to provide the user and product fields in Insomnia. Because in the creation function, I specified how the user and the product should be stored in the database. My second question is why should I use valve because if I don't use it, it gives me the following error: Field 'rate' expected a number but got <BoundField value=5 errors=None>. class CommentProduct(APIView): serializer_class = CommentSerializer def post(self, request, *args, **kwargs): product = Product.objects.get(id=kwargs['pk']) serializer = self.serializer_class(data=request.POST) if serializer.is_valid(): Comment.objects.create(user_id=request.user.id, product_id=product.id, comment=serializer['comment'].value, rate=serializer['rate']) return Response(serializer.data) return Response(serializer.errors) -
How to fetch object in create method?
Need help on fetching the value in my view method. Hello! I'm trying to fetch the value of my requesterid. I want to create a condition that if requesterid is equal to a certain value, it will allow the create method. I don't know how I will access the variable. Can someone help me on this? I have this in my code so far, but it says that "Error": "'Request' object has no attribute 'requesterid'" Here's my views.py class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer def create(self, request, *args, **kwargs): if request.requesterid.userroleid == 3: write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) instance = self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.instance.requestid, "Parts ID": [p.partsid for p in write_serializer.instance.parts.all()]},headers=headers) raise ValidationError("Sorry! Your role has no permission to create a request.") Here's my models.py class userTable(models.Model): userid = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) username = models.CharField(max_length=50, null=False, unique=True) userroleid = models.ForeignKey(roleTable, on_delete=models.CASCADE) class roleTable(models.Model): roleid = models.IntegerField(null=False, primary_key=True) role = models.CharField(max_length=255, null=False) class requestTable(models.Model): rid = models.AutoField(primary_key=True) requesterid = models.ForeignKey(userTable, on_delete=models.CASCADE) (...) -
Django - how to update multiple rows using a checkbox
I want to update a boolean to 'True' in bulk for all the rows in a table. I want to update the age of which the people have a qualified age using a form checkbox for multiple rows The code is Class Age(models.Model) Name = models.CharField(max_length=100) age = models.IntegerField() qualified_age = models.BooleanField(default='False) Views.py def Home(request): context = [] list = Age.objects.all() if request.method == 'POST': list_data = request.POST.getlist('instance') for data in list_data: Age.objects.filter(id=data).update(qualified_age=True) return redirect(Home) context{ list:'list', } return render(request, 'index.html', context) Index.html <tr> <th> Change Bool Value </th> <th> Names </th> <th> Ages </th> </tr> <form method='post', action=' '> {% for data in List %} <tr> <td> <input type="checkbox", value=" {{data.id}} ", name="instance"> </td> <td> {{data.Name}} </td> <td> {{data.age}}</td> </tr> {% endfor %} </input type="submit", value="Update"> </form> I want to update all the rows all at once but it's not working... Could anyone please assist...¿ -
Is is possible to use ThreadPoolExecutor inside django views?
I have a view that has to cooperate with another service and thus make a bunch of requests to that third-party service. In my project I use Django==1.1.16 and python 3.6 Is is possible to use ThreadPoolExecutor from concurrent.futures inside a django view to concurrently make a bunch of requests to another service and take advantage of this I/O operation inside my view? Any tips or advices? Celery is not an option in that case. Out simple infrastructure do not support that. -
POST json object but QueryDict is empty
I want to post an obj to Django server, but the QueryDict is always empty. Client side: function makeRequest (method, url, data, datatype) { function msg (err, datums) { if (err) { throw err; } console.log(datums); } var xhr = new XMLHttpRequest(); xhr.open(method, url,true); // X-CSRFToken xhr.setRequestHeader('X-CSRFToken', csrftoken); xhr.setRequestHeader("Content-Type", datatype); xhr.onload = function () { msg(null, xhr.response); }; xhr.onerror = function () { msg(xhr.response); }; xhr.send(data); } var params = { "range":"Sheet1!A4:C4", "majorDimension": "ROWS", "values": [ ["Hello World","123", "456"] ], } makeRequest('POST', "http://127.0.0.1:8000/update_student/1/",JSON.stringify(params) , 'application/json'); Server side: def update_student(request,pk): if request.method =="POST": print("update_student entered") breakpoint() return HttpResponse("a post method", status=200) else: return HttpResponse("This should be a POST method", status=400) I checked the payload when the post is sent, it's not empty. -
Selecting HTML datalist option does not trigger search event
I am developing a search engine for a website; now it's working fine and responding to input search keywords with no issues in its interaction with the (Django-based) local web server. The problem (well there are actually two, but I'm presenting only one here) is with the datalist. When I select an option from the list, although it goes into the search input field, nothing happens until I click the submit button. I have written an event listener for each option, but I'm clearly missing something (important). Here's my minimal working code: HTML <form id="search-form" action ="{% url 'search' %}" method='POST'> {% csrf_token %} <input id="enter" type="search" list="options" name="query" /> <datalist id="options"> <option class="option" value="Happy"> <option class="option" value="Puzzled"> </datalist> <button id="go" type="submit"><strong>&#x1F50E;&#xFE0E;</strong></button> <button id="reset" type="reset"><strong>X</strong></button> </form> JavaScript <script> const searchForm = document.getElementById('search-form'); const enter = document.getElementById('enter'); let options = document.querySelectorAll(".option"); options.forEach((item, index) => { item.addEventListener("click", () => { return searchForm.action; }) }) </script> Maybe the event should be something else; I've tried "keydown" and clicking twice but nothing has worked. Your help would be most appreciated. -
media files stores files in MEDIA_ROOT, but serves them from app folder
I'm having trouble bending the media_root to my will. When I try to serve an image, a suffix is appended to the file path, more precisely, it tries to point to an app (yoga) even though I want it to point to BASE_DIR / media. For example it will give me this: http://localhost:8000/yoga/media/images/satori.jpg But the media folder is (auto-generated) one folder up from that in the dir hierarchy. I've been wracking my brain, because I just can't see where that "yoga/" line is appended to the path, and I don't understand why or how it got there, lest of course we consider, that the model that it stems from lives inside the yoga app directory. Here's what I think might be relevant. Please let me know if you want to see more of the goods. Tree: . ├── boofers.txt ├── db.sqlite3 ├── dos_env ├── manage.py ├── media ├── static ├── yoga └── yoga_dos In settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' in the model @ yoga/models.py: ex_img = models.ImageField(upload_to='media/images', blank=True, default='yogapose.jpg') -
How to make collections like Instagram saves posts in custom collections in django
I am currently working on a social media website with Django , here I can like, comment and save posts without having to go to a post's detail page {can do it like Instagram allows user} , now having the ability for a user to save certain posts , I want to allow the users to save those posts into their own custom collections {for example if user likes a post with cats in it they can make a collection name "cats" and save post there } I want to know how I would go about doing that , please explain some logic and if possible can you guide me to some code snippets or a blogpost thank you -
Django HttpResponse attachment filename when non-english character occurs the file downloads improper
I am downloading a file from a django server and it downloads correctly when the filename consists of all english characters like "ready.csv". However, i am having difficulties when the filename contains other than english characters like "ılgaz.csv". It downloads the file as "download.csv". response=HttpResponse(content_type='text/csv') response['Content-Disposition']="attachment; filename=" + str(filename) + "_" + str(datetime.datetime.now()) + ".csv" This is how i create my response object. -
xhr always send request without payload (django
The QueryDict is always a emptye dictionary. Client side: function makeRequest (method, url, data, datatype) { function msg (err, datums) { if (err) { throw err; } console.log(datums); } var xhr = new XMLHttpRequest(); xhr.open(method, url,true); // X-CSRFToken xhr.setRequestHeader('X-CSRFToken', csrftoken); // xhr.setRequestHeader('Content-Type', datatype); xhr.setRequestHeader("Content-Type", datatype); xhr.onload = function () { msg(null, xhr.response); }; xhr.onerror = function () { msg(xhr.response); }; xhr.send(data); } var params = 'orem=ipsum&name=binny'; makeRequest('POST', "http://127.0.0.1:8000/update_student/1/",params , 'application/x-www-form-urlencoded'); Server side: def update_student(request,pk): if request.method =="POST": print("update_student entered") breakpoint() return HttpResponse("a post method", status=200) else: return HttpResponse("This should be a POST method", status=400) I observe the breakpoint() line, and discover the request didn't send anything. What's wrong? Thanks:) p.s. I hate django. HOw can disable the stupid csrf_token when I'm developing. -
Serializer for Recursive Comment in Django
models.py class Comments(models.Model): content = models.CharField(max_length=500) sub_comment_id = models.ForeignKey('self', related_name='sub_comments', null=True, blank=True, on_delete=models.CASCADE) author_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_comments', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_comments', on_delete=models.CASCADE) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) is_sub = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.content what can i do for showing all recursive comments in Comment Serializer? i use django rest framework-recursive but does not work -
A few generic views under one URL
I'm facing a issue with setting up a few generic views on this same certain URL. I would like to have a modeled my API as below: GET /cars/ <- car list POST /cars/ <- add new car GET /cars/uuid/ <- get particular car PUT /cars/uuid/ <- edit particular car DELETE /cars/uuid/ <- delete specific car So finally my issue is that the first include in urlconfig is able to perform the HTTP method, on rest of them I'm always getting "Method Not Allowed:". In above example it's occurs for PUT and DELETE. Is it possible to resolve URL as above or should I add prefixes like /cars/get/uuid? urls.py urlpatterns = [ path('', CarListApi.as_view(), name='list'), path('', CarCreateApi.as_view(), name='create'), path('<uuid:uuid>/', CarDeleteApi.as_view(), name='delete'), path('<uuid:uuid>/', CarUpdateApi.as_view(), name='update'), path('<uuid:uuid>/', CarDetailApi.as_view(), name='detail'), ] partial views.py class CarUpdateApi(generics.UpdateAPIView, generics.GenericAPIView): permission_classes = (IsOwnerOrReadOnly,) lookup_field = 'uuid' http_method_names = ['delete', 'get', 'post', 'put'] @extend_schema_serializer(component_name="CarUpdateInputSerializer") class InputSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ['plate', 'make', 'model', 'uuid'] @extend_schema(request=InputSerializer, responses={201: InputSerializer}) def put(self, request, uuid): serializer = self.InputSerializer(data=request.data, context={'request': request}) if serializer.is_valid(raise_exception=True): car = car_update(serializer.validated_data, uuid) return Response(self.InputSerializer(car).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CarDeleteApi(generics.DestroyAPIView, generics.GenericAPIView): http_method_names = ['delete', 'get', 'post', 'put'] @extend_schema_serializer(component_name='CarDeleteInputSerializer') class InputSerializer(serializers.ModelSerializer): class Meta: model = Car … -
The field returns null even though it contains a value
When creating a new object (music track), I specify the name of the playlist in one of the fields. However, after saving the data from the form, the value of the playlist field in the frontend is null, although there is a value in this field in the admin panel. I do not understand how I can get the name of the object (playlist) that I specify when creating, for some reason it is always null in the frontend. my models: class Composition(models.Model): title = models.CharField(max_length=500) artist = models.CharField(max_length=500) playlist = models.ForeignKey('PlayList', on_delete=models.CASCADE, blank=False) time_length = models.DecimalField(blank=True, max_digits=20, decimal_places=2) audio_file = models.FileField(validators=[validate_is_audio]) cover_image = models.ImageField() def save(self, *args, **kwargs): if not self.time_length: # логика для получения длины музыкального трека audio_length = get_audio_length(self.audio_file) self.time_length = audio_length return super().save(*args, **kwargs) class PlayList(models.Model): name = models.CharField(max_length=500) my views def addSong(request): form = AddCompositionForm() if request.POST: form = AddCompositionForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) playlist = form.cleaned_data.get('playlist') music_playlist = PlayList.objects.get_or_create(name=playlist) instance.playlist = music_playlist[0] instance.save() return redirect("music_player:home_page") return render(request, 'addSong.html', { 'form': form }) my frontend function const setSRC = () => { player.src = `{{ MEDIA_URL }}/${musics[compositionIndex].audio_file}` song_title.textContent = musics[compositionIndex].title artist.textContent = musics[compositionIndex].artist music_img.setAttribute('src', `{{ MEDIA_URL }}/${musics[compositionIndex].cover_image}`) if (musics[compositionIndex].playlist != null) { // … -
Django's static file (.js) is not displayed on frontend
This is my folder structure in my react.js app. I have set NO router to display worker.js file on frontend. The file is just there with no further settings. And yet, since its in "public" folder, I can display it on my frontend like this My question is, how can I achieve same thing with Django? ***I tried different urls, different paths to see my file on my frontend but nothing worked ***... I also tried to set path/router for worker.js both in django and react side but then its rendered as html... I need it to be seen as js file. I need to achieve this because I'm using that react app's production folder in my Django app as template and need that worker.js file to be reachable in that same link you see in the image. My settings.py file: ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "settledhead/build/static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "settledhead/static_root") ... And this is how react's production folder looks like in my django app -
in Django make calculate remaining dates
I have this code for calculate remaining days. The result in first field works great. But How can I get all result for others fields in same first one. I have tried but, I do not know how to make it. Any idea please any help would be greatly appreciated here iterate through ending date Django part {% for obj in obj %} </td> <td class="end-dates"> <div id="end_date"> {{obj.date_end|date:"M d Y"}} </div> </td> {% endear %} script part <script> function func (){ var endDate = document.getElementById('end_date').innerHTML; console.log(' end date :', endDate) const EndDatesAll = document.getElementsByClassName('end-dates'); const currentEndDateCount = EndDatesAll.length console.log(EndDatesAll.length) var today = new Date().getTime(); var date2 = new Date(endDate).getTime(); var diff = Math.floor( date2 - today); days = Math.floor(diff / (1000 * 60 * 60 * 24)); hours = Math.floor(diff / (1000 * 60 * 60)); mins = Math.floor(diff / (1000 * 60)); secs = Math.floor(diff / 1000); dd = days; hh = hours - days * 24; mm = mins - hours * 60; ss = secs - mins * 60; console.log(currentEndDateCount) document.getElementById('remaining-days').innerHTML = days; } func(); </script> -
How to solve this error "django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field."
` Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/Users/mihirshah/Desktop/picalert/create_area_api/views.py", line 17, in get_queryset return self.queryset.filter(user=self.request.user) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1420, in filter return self._filter_or_exclude(False, args, kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1438, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1445, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1532, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1562, in _add_q child_clause, needed_inner = self.build_filter( File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1407, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1217, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1709, in names_to_path raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'user' into field. Choices are: created_at, created_by, created_by_id, desc ription, end_date, id, start_date, title ` create_area_api/serializers.py ` from rest_framework … -
Django Test | How to pass a a dictionary containing a dictionary value through clients.post
I have a dictionary A that contains a single value that is also a dictionary B B = {"k1": "v1", "k2": "v2", "k3": "v3"} A = {"User": B} This type of dictionary is used in one of my views function def views_function(request): # request.data is a dictionary containing a single value that is also a dictionary. Just like A I'm trying to write a unit test for views_function from django.test.TestCase. from django.test import TestCase class test_cases(TestCase): def setUp(self): self.B = {"k1": "v1", "k2": "v2", "k3": "v3"} self.A = {"User": self.B} self.url = reverse("views_function_url") def test_views_function(self): response = self.client.post(url, self.A, format="json") But clients.post seems unable to take A as an input. When I print A inside test_views_function it shows the proper dictionary. def test_views_function(self): B = {"k1": "v1", "k2": "v2", "k3": "v3"} A = {"User": B} print(A) # {"User": {"k1": "v1", "k2": "v2", "k3": "v3"}} response = self.client.post(url, A, format="json") But when I add a print statement to views_function for some reason only the last key of B is there def views_function(request):{"User": "k3"} print(request.data.dict()) # {'User': 'k3'} -
How do i stop dark mode from flickering when page is refreshed
I'm having a difficulty in stopping my night mood from flickering whenever a user refresh page or try navigating to their timeline, the dark mode flicker making it not look professional even though I check some solution on here that said I should put the dark mode function at the top of my base HTML for it to be the first to load, which didn't work in my case and I was wondering what seem to be problem or what could I do, can any one be of help. {% load static %} <!DOCTYPE html> <html lang="en"⚡> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Favicon --> <link href="{% static 'images/logot.png' %}" rel="icon" type="image/png"> <link href="https://fonts.googleapis.com/css2?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/@trevoreyre/autocomplete-js/dist/style.css"/> <!--AMP--> <!-- Basic Page Needs ================================================== --> <title>Fassfy</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- icons ================================================== --> <link rel="stylesheet" href="{% static 'css/icons.css' %}"> <!-- CSS ================================================== --> <link rel="stylesheet" href="{% static 'css/uikit.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="{% static 'css/tailwind.css' %}"> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> <link rel="stylesheet" href="{% static 'cropperjs/dist/cropper.min.css' %}"> </head> <body> {% if request.user.is_authenticated %} <div class="container" id="id_loading_spinner" style="display: none"> <div class="d-flex flex-row mx-auto flex-grow-1 justify-content-center"> <div class="spinner-border text-primary" role="status"> … -
502 Bad Gateway (13 permission denied) Nginx + Gunicorn
I am trying to deploy a simple hello-world Django site to EC2 (Ubuntu 22.04) using Gunicorn and Nginx. Nginx and Gunicorn services are both reporting as running successfully, and the .sock file has been created seemingly without issue. Gunicorn configuration file: [Unit] Description=gunicorn daemon After=nextwork.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/sites/mysite-main ExecStart=/home/ubuntu/.local/share/virtualenvs/mysite-main-_EzVOJAm/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/sites/mysite-main/mysite-main.sock myapp.wsgi:application [Install] WantedBy=multi-user.target Nginx configuration: server { listen 80; server_name <domainname>.com <ipaddress>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/sites/mysite-main; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/sites/mysite-main/mysite-main.sock; } } Permissions on the .sock file, as well as both the "sites" and "mysite-main" directories are ubuntu:www-data. I attempted to try moving it out of the ubuntu user's home directory into a more "common" location in case it was permissions on the home directory stopping it, but was unable to even get the .sock file to generate in that case, probably due to my unfamliarity with how this works. It looks like this is one of the most queried problems of all time, but I've tried every solution I could find to no avail. Any help would be greatly appreciated. Thanks in advance! -
Get Choice Description in queryset.value_list django
I have a model and within it I have IntegerChoice Class (Gender) When I get field value with values_list() I don't want to get value as a number (1 or 2) but as a label string (Female or Male) class Policy(models.Model): class Gender(models.IntegerChoices): MALE = 1, _("Male") FEMALE = 2, _("Female") maca = models.CharField(max_length=100, db_column="Maca", null=True, blank=True) Policy.objects.all().values_list("maca", "gender") -
Multiple file environment variable in django project without docker
In the open source project that I am planning to develop, Docker is used to use several env files, but I have to run the project without Docker. Does anyone have a solution? I also added this part of the code to the settings import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # Take environment variables from .env file environ.Env.read_env(os.path.join(BASE_DIR, '.env')) But still it gives the following error The SECRET_KEY setting must not be empty. -
How to know which extension is chaning the code in VSCode
I have this code in VSCode: import django from models import Product The problem is that when I save the file, VSCode change the code (somehow trying to beautify it): from models import Product import django I had this Prettier extension, and I disabled it, but I still got the problem. -
How can I use addEventListener to multiple buttons which are displayed with a for loop?
I have a page that displays social media posts from users and all posts have an Edit button. When the Edit button is clicked on, a form with a textarea pre-filled with the current content and a submit input is displayed. The problem is that regardless of which post's Edit button I click, always the first post is changing. I guess I should add an "id" somewhere to track which post is being edited but I couldn't figure out how to do that. Or is there another solution? views.py: def index(request): post_list = AllPost.objects.all().order_by("date").reverse() paginator = Paginator(post_list, 10) # Show 10 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "posts": post_list, "page_obj": page_obj }) def edit(request, id): if request.method == "POST": new_content = request.POST["new_content"] updated_post = AllPost.objects.filter(id = id) updated_post.update(content = new_content) return JsonResponse({}, status = 201) return JsonResponse({"error": "Bad Request"}, status = 400) index.html: {% for post in page_obj %} {{ post.full_name|upper }}<br> <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> {% if post.user == user %} <button class="btn btn-sm btn-outline-primary" id="edit">Edit</button> {% endif %} <div id="content">{{post.content}}</div> <form action="{% url 'edit' post.id %}" method="post" id="edit_post" style="display: none;"> {% csrf_token %} <div class="form-group"><textarea … -
When does using sqlite become a bottleneck?
I am currently working my way through the Udemy course Python Django - The Practical Guide by Academind, and during the deployment section the author mentions that one deployment consideration is the choice of database. He states that for larger sites with a larger volume of requests, using a sqlite database (the default when using Django) can become problematic and can slow down the site. However, he does not go on to explain this in a quantitative way. Is there some value, or perhaps a rule of thumb, by which you could draw a line between those sites for which a sqlite database is adequate, and those for which it is not? Thanks -
Run scarpy project from djnago views,py
I am building a scraper which will extract email ids from website urls , and i want this to integrate this to my Django views.py module. I have my project structure as follows : emails emails -init.py -asgi.py -settings.py -urls.py e_scrapy (django-app) email_scrapper //scrapy project spiders --init__.py -email_extraction.py init.py items.py middlewares.py pipelines.py settings.py scrapy.cfg __init__.py admin.py apps.py models.py tests.py urls.py //manually added views.py my email_extraction.py have this code:: import scrapy from scrapy.spiders import CrawlSpider, Request import re from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import openpyxl from time import sleep import xlsxwriter from bs4 import BeautifulSoup import os from selenium import webdriver from pathlib import Path from tldextract import extract class EmailExtractor(CrawlSpider): name='emailex111' def __init__(self,filename): self.queries=[] self.emaillist=[] self.row=0 self.write_wb=xlsxwriter.Workbook('emails_list.xlsx') self.sheet=self.write_wb.add_worksheet('sheet1') self.filename=filename wb=openpyxl.load_workbook(self.filename) self.save_file=self.filename+"_emails.txt" sh=wb.active for i in range(1,sh.max_row+1): cell_obj=sh.cell(row=i,column=1) tsd, td, tsu = extract(cell_obj.value) search_query=td + '.' + tsu #pass_val='"@'+str(search_query)+'" Email Address' self.queries.append(search_query) def start_requests(self): WINDOW_SIZE="1920,1080" path="C:/Users/iamfa/OneDrive/Desktop/SCRAPY/email_extraction/email_extraction/spiders/msedgedriver.exe" options=webdriver.EdgeOptions() #options.add_argument("--headless") #options.add_argument("--window-size=%s" % WINDOW_SIZE) options.add_argument('--ignore-ssl-errors=yes') options.add_argument('--ignore-certificate-errors') options.add_experimental_option('excludeSwitches', ['enable-logging']) browser=webdriver.Edge(options=options,executable_path=path) url_list=[] for query in self.queries: # iterate through queries url="https://www.bing.com/search?q=%40"+str(query)+"+%22Email+Address%22" try: browser.get(url) links=browser.find_elements(By.TAG_NAME,'cite') for link in links: url_list.append(link.text) except: continue resultno=0 for results in url_list: if resultno==5: break try: resultno+=1 yield SeleniumRequest( url=results, callback=self.parse, wait_until=EC.presence_of_element_located( (By.TAG_NAME, …