Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send email with django and AWS SES signature V4
I have a django project and recived an email informing that I should change my ses signature from v2 to v4. I created a new IAM user following this tutorial https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html and attach this politics: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ses:*" ], "Resource": "*" } ] } I´m using this lib https://pypi.org/project/django-ses/, but got this erro message "An error occurred (SignatureDoesNotMatch) when calling the GetSendQuota operation: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details." Someone can help to send an email? -
EmptyPage at / That page contains no results
Iam getting this error when Iam trying to navigate to the last page how shall I solve it? Nad Iam a self taught programmer this is really stopping me to learn to code Please help me to deal with this error. This is my home.html: {%extends "blog/base.html"%} {%block content%} {%for post in posts%} <article class="media content-section"> <img class = "rounded-circle aritcle-img" height = 80px width = 80px src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'post-posts' post.author.username%}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}" >{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {%endfor%} {% if is_paginated%} {% if page_obj.has_previous %} <a class = 'btn btn-outline-info mb-4' href="?page=1">First</a> <a class = 'btn btn-outline-info mb-4' href="?page={{ page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {%if page_obj.number == num %} <a class = 'btn btn-info mb-4' href="?page={{ num }}">{{ num }}</a> {%elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class = 'btn btn-outline-info mb-4' href="?page={{ num }}">{{ num }}</a> {%endif%} {% endfor %} {% if page_obj.has_previous %} <a class = 'btn btn-outline-info mb-4' href="?page={{ page_obj.next_page_number }}">Next</a> <a class = 'btn btn-outline-info mb-4' href="?page={{ page_obj.paginator.num_pages }}">Last</a> … -
Javascript can't parse the json properly
I'm trying to parse json with xhr. I've done xhr file for two pages and every page takes different data from xhr file. If the parser can't find the proper id in html template it can't handle the remaining part. Here's js const xhr = new XMLHttpRequest() method = 'GET' xhr.responseType = 'json' function buildTable(data){ } xhr.open(method, requestURL) xhr.onload = function() { if (xhr.status > 400){ console.error(xhr.error) }else{ console.log(xhr.response) document.getElementById('name').innerHTML = xhr.response.name document.getElementById('status').innerHTML = xhr.response.status .... buildTable(xhr.response.history) document.getElementById('description').innerHTML = xhr.response.description } } xhr.send() and here's the django template {% extends 'base_dashboard.html' %} <div class="wrapper"> {% include 'sidebar.html' %} <div id='name'></div> <div class="" id="status">In Progress</div> <div class="col-xs-12" id='description'></div> </div> {% load static %} <script src="{% static '/js/xhr_dashboard.js' %}"> </script> {% endblock content %} JSON example name: "myname" description: "This is the test description" status: "2" -
Save Django forms from 2 different models into third model
I new-ish to Django and need some help with Django Forms. I'm building a poll like app to learn, but I would like to have the poll questions come from one model, while the answer choices from other model. However I have issues getting that data back to the CBV using forms. class RiderModel(models.Model): full_name = models.CharField(max_length=500) number = models.IntegerField() def __str__(self): return self.full_name class QuestionModel(models.Model): category = models.ForeignKey(CategoryModel, on_delete=models.CASCADE, default=1) question_text = models.TextField() def __str__(self): return self.question_text class UserVoteModel(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) event = models.ForeignKey(GameModel, on_delete=models.CASCADE) question = models.ForeignKey(QuestionModel, on_delete=models.CASCADE) answer = models.ForeignKey(RiderModel, on_delete=models.CASCADE) In the CBV I have this function to get the data to template, but not sure how to get this data back into the UserVoteModel def get_queryset(self): event = self.kwargs['short_name'] category = GameModel.objects.filter(short_name__iexact=event)[0].question_category return {'questions': QuestionModel.objects.filter(category=category), 'riders': RiderModel.objects.all()} Thank you in advance for your help. -
{"message":["This field is required."],"status_code":400} error when posting requests in python to a Django rest framework
Hi I have a code to post json data to a url but I am getting {"message":["This field is required."],"status_code":400} this as response. Even though i have no message fields in my code or data. import requests import json from urllib3.exceptions import InsecureRequestWarning refreshurl = "/api/login" refreshheader = { "accept": "application/json", "content-type": "application/json", } refreshfields = { "username": " ", "password": " " } #api call for refresh token access_token_response = requests.post(refreshurl, headers=refreshheader, json=refreshfields, verify=False) myaccesstoken = access_token_response.json()["access"] #api call for accesstoken url2 = "https://google.com/upload_data" #dummy url header2 = { "accept": "application/json", "content-type": "application/json", "Authorization": "Bearer {}".format(myaccesstoken)", } fields = { { "name":"alia","id":"GSHBA678","status":"active","zipcode":56839}, } #api call to upload data requests.packages.urllib3.disable.warnings(category=InsecureRequestWarning) response = requests.post(url2, headers=header2, json=fields, verify=False) print(response.text) print(response.status_code) Instead of Bearer if i put token in JWT it is giving me {"message":["Authentication credentials were not provided"],"status_code":401}. I have no idea how to solve this. Any help would be appreciated. Thanks . -
How can I optimize the function given below so that number of hits to the database are reduced?
I have this function def get_lesson_posts(self): learning_units = self.get_learning_units() comments = [] for unit in learning_units: if unit.lesson is not None: lesson_ct = ContentType.objects.get_for_model(unit.lesson) title = unit.lesson.name try: post = Post.objects.get( target_ct=lesson_ct, target_id=unit.lesson.id, active=True, title=title ) except Post.DoesNotExist: post = None if post is not None: comments.append(post) return comments There is a for loop iterating on each unit and creating a content type object (lesson_ct) which is then used to get a post from the Post table. Now I think on each iteration a database query is executed by the Post model to get a post object. The problem is I am not able to think of a better method to get the Post object without making queries on each iteration. I need help in writing the function properly so that I can reduce the number of queries being executed. For reference I am posting the Post model and Lesson Model below. class Post(ForumBase): title = models.CharField(max_length=200) target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj', on_delete=models.CASCADE) target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) target = GenericForeignKey('target_ct', 'target_id') class Lesson(models.Model): # Lesson name name = models.CharField(max_length=255) # Markdown text of lesson content description = models.TextField() Please tell me if more information is required. Thanks -
502 Gateway Error + cannot detect my postgres
I am trying to docker up my django application using this tutorial. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ Technically, I have 2 problems: Cannot connect to the database 502 gateway error Everything seems to work until i get this error: nginx-proxy | nginx.1 *1 connect() failed (111: Connection refused) while connecting to upstream, client: 138.75.155.194, server: www.hello.com, request: "GET /favicon.ico HTTP/2.0", upstream: "http://172.25.0.2:8000/favicon.ico", host: "www.hello.com", referrer: "https://www.hello.com/" Also, it seems that my web server is unable to detect my postgresql database as it prompts a "waiting for postgres" due to the entrypoint.sh i have provided. I have configured my database using this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Been stuck with this for a few days! I will attach my code here: When I run netstat plant: Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 637/systemd-resolve tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 840/sshd tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 27204/postgres tcp 0 0 127.0.0.1:35449 0.0.0.0:* LISTEN 19618/containerd tcp 0 0 174.138.34.252:22 138.75.155.194:52289 ESTABLISHED 740/sshd: root@nott tcp 0 1080 174.138.34.252:22 222.186.30.112:13146 ESTABLISHED 16139/sshd: [accept tcp 0 356 174.138.34.252:22 138.75.155.194:52288 ESTABLISHED 32641/sshd: root@pt tcp6 0 0 :::22 :::* LISTEN 840/sshd docker-compose file: version: '3.8' services: web: container_name: tinkertinc build: context: ./hello_main dockerfile: Dockerfile.prod … -
Including Modified Django Package in Project
I am trying to figure out how to include a modified package into a Django 2.2 project. The package has been modified. A few skins have been added to the editor. That is, it is no longer the same package that is installed when one does pip install <package>. My understanding is that it now needs to be added to source control and probably added to the project directory, instead of being located within a virtual environment's directory. The question is what is the way go about this situation most efficiently. Should I add the package to the project's directory or is there a way to somehow manage this through pip and requirements.txt? -
How to add two views in same urls in Djnago?
I'm Using Django framework as a backend, PostgresSQL for DB and HTML, CSS, Javascript for frontend. I am making a website and function like down below. User click to add the product (click on button "choose product")(Index.html) User directed to next page (listitem.html) where user can select the product. After choosing product from (listitem.html) (click on button "Add product") After that user redirected to main page which is (index.html) and the choosen product as shown to user. Now all the codes work fine. The data is fetched properly but not on the page what I wanted too. The Codes Goes here: urls.py urlpatterns = [ path('base/', views.base, name='base'), path('index/', views.build, name='index'), path("add-to-cart-<int:pro_id>/", AddToCartView.as_view(), name="addtocart"), path("my-cart/", MyCartView.as_view(), name="mycart"), ] views.py class AddToCartView(TemplateView): template_name = "status.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get product id from requested url product_id = self.kwargs['pro_id'] # get product product_obj = Product.objects.get(id = product_id) # check if cart exists cart_id = self.request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id = cart_id) this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj) if this_product_in_cart.exists(): cartproduct = this_product_in_cart.last() cartproduct.quantity += 1 cartproduct.save() cart_obj.save() else: cartproduct = CartProduct.objects.create(cart = cart_obj, product = product_obj, quantity = 1) cart_obj.save() else: cart_obj = Cart.objects.create(total=0) self.request.session['cart_id'] = cart_obj.id cartproduct … -
Django - Sitemap - Manually set absolute urls
I'm generating a sitemap but the website that this sitemap is for has a different URL routing and a different domain. I thought that overriding location method will work but the problem is that Django automatically adds Site url before each url. http://example.comhttps://thewebsite.com... <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>http://example.comhttps://thewebsite.com/article/123/slug</loc><lastmod>2021-05-10</lastmod> <changefreq>hourly</changefreq><priority>0.5</priority> </url> </urlset> class WebsiteSitemap(Sitemap): changefreq = "hourly" priority = 0.5 def items(self) -> typing.List: items = [] items.extend(Article.objects.home()) return items def location(self, obj: typing.Union[Article]): return obj.website_full_url def lastmod(self, obj: typing.Union[Article]) -> datetime: return obj.modified Is there a way to tell Django not to build the URL automatically? -
I am not able to use RemBg Python Software. Help me
I was using RemBg Software provided in this Repository. Whenever I used it. It gives me the following error- Failed to import ahead-of-time-compiled modules. This is expected on first import. Compiling modules and trying again. This might take a minute. Traceback (most recent call last): File "c:\python39\lib\site-packages\pymatting_aot\cc.py", line 36, in <module> import pymatting_aot.aot ModuleNotFoundError: No module named 'pymatting_aot.aot' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python39\Scripts\rembg-server.exe\__main__.py", line 4, in <module> File "c:\python39\lib\site-packages\rembg\cmd\server.py", line 11, in <module> from ..bg import remove File "c:\python39\lib\site-packages\rembg\bg.py", line 6, in <module> from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf File "c:\python39\lib\site-packages\pymatting\__init__.py", line 2, in <module> import pymatting_aot.cc File "c:\python39\lib\site-packages\pymatting_aot\cc.py", line 54, in <module> compile_modules() File "c:\python39\lib\site-packages\pymatting_aot\cc.py", line 8, in compile_modules cc = CC("aot") File "c:\python39\lib\site-packages\numba\pycc\cc.py", line 65, in __init__ self._toolchain = Toolchain() File "c:\python39\lib\site-packages\numba\pycc\platform.py", line 78, in __init__ self._raise_external_compiler_error() File "c:\python39\lib\site-packages\numba\pycc\platform.py", line 121, in _raise_external_compiler_error raise RuntimeError(msg) RuntimeError: Attempted to compile AOT function without the compiler used by `numpy.distutils` present. Cannot find suitable msvc. I also tried to start their server by using the rembg-server command but it still not works. Can anybody … -
How can i filter date exec sql
Hi my problem is i try to filter date but url load but form not. I try to filter but not filter i dont know what is the problem.. When i try to swap date the url its ok but in form not load results ok always same date in form Img url / Inputs HTML views.py def BootstrapFilterView(request): fecha = datetime.now() format_min = fecha.strftime('%d-%m-%Y') date_max = fecha + timedelta(days=1) format_max = date_max.strftime('%d-%m-%Y') cursor.execute("[Pr].[dbo].[NX_Pr]" + "'" + str(format_min) + "'," + "'" + str(format_max) + "'") qs = cursor.fetchall() operacion = request.GET.get('orden') if format_min and format_max: url_listapdf = reverse('materials_all') + '?date_min=' + format_min + '&date_max=' + format_max elif format_min and not format_max: url_listapdf = reverse('materials_all') + '?date_min=' + format_min elif not format_min and format_max: url_listapdf = reverse('materials_all') + '?date_max=' + format_max else: url_listapdf = reverse('materials_all') context = { 'queryset': qs, 'format_min': format_min, 'format_max': format_max, 'url_listapdf': url_listapdf } return render(request, "app/necesidades.html", context) HTML: <form method="GET" action="."> <div class="card-body"> <u><legend class="blue">FECHA</legend></u> <div class="input-group date"> <b class="b-form">DESDE:</b><input type="text" class="form-control" id="publishDateMin" name="date_min" value="{{format_min}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <div class="input-group date"> <b class="b-form">HASTA: </b> <input type="text" class="form-control" id="publishDateMax" name="date_max" value="{{format_max}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <br /> -
How to connect s3 amazon to your django project?
guys sorry for disturbing you. Hope you all are doing great actually I have uploaded the images as well as static files in the s3 bucket but now the error is when we go to the path images does not appear! and when we inspect it, it shows the correct path where the image should be placed and when we access this from s3 we get to see every image here so I was wondering that do we need to change the URLs? and if yes how to do it?? -
wrapping password reset confirm url in a href doesn't work
I have a password reset template with the following redirect to a password confirm view: <a href="{{ protocol }}://{{ domain }}{% url 'consumer_portal:password-reset-confirm' uidb64=uid token=token %}">Change password</a> When I click "Change password" on the browser it doesn't work. However I can copy the url on the change password text and paste it in my browser and it will redirect me to change my password. Anyone know why clicking it doesn't work but pasting it in the browser does? For context, my reset confirm template has the standard link check {% if validlink %} <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="post"> {% form %} </form> {% else %} <p>password reset invalid</p> -
Can anyone help me identify that heroku application error
After opening app I deployed, there is an error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Can you please help me solving or identifying that error? There are logs » Warning: heroku update available from 7.47.6 to 7.53.1. 2021-05-17T08:07:01.958623+00:00 app[api]: Release v1 created by user filip.antoniak99@gmail.com 2021-05-17T08:07:01.958623+00:00 app[api]: Initial release by user filip.antoniak99@gmail.com 2021-05-17T08:07:02.185037+00:00 app[api]: Enable Logplex by user filip.antoniak99@gmail.com 2021-05-17T08:07:02.185037+00:00 app[api]: Release v2 created by user filip.antoniak99@gmail.com 2021-05-17T08:09:13.560585+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=ergonomizer.herokuapp.com request_id=5b27d2eb-9b93-4169-b5a1-c5041f0c46d4 fwd="37.249.138.76" dyno= connect= service= status=502 bytes= protocol=https 2021-05-17T08:09:13.788320+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=ergonomizer.herokuapp.com request_id=0f06c72b-8d59-4409-9946-a343a7ac7b57 fwd="37.249.138.76" dyno= connect= service= status=502 bytes= protocol=https 2021-05-17T08:10:38.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:10:57.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/be2f281b-2961-4df6-8abd-bd691199f6d4 2021-05-17T08:14:21.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:14:40.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/aba64d28-3b09-4ca9-a0db-a5277ff0eac5 2021-05-17T08:18:00.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:18:20.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/9afe7277-a8cc-4782-b52d-bb5698d2273c/activity/builds/9273f61b-0a02-414f-b7cc-0674b19f8b80 2021-05-17T08:27:17.000000+00:00 app[api]: Build started by user filip.antoniak99@gmail.com 2021-05-17T08:27:35.000000+00:00 app[api]: Build failed -- check your build output: … -
Django FastApi 2 servers
Please help me. I have a project on Django, in which some of the processes go through celery. But now I want to transfer all the complex data processing to another server. I plan to use FastApi. But the question arose - how to properly organize the work with the client files that will be processed . Do I need to receive files from the client and save them on the second server, or do I need to save them on the first server and send them over tcp? Perhaps there are other options ? How do I do this ? -
django templates without db, model
I am creating a bulletin board that communicates by DB <> API <> WEB(db-less) method. How should I use {% if user.is_authenticated %} and {% if user.username == A or B %} and so on. when there is no DB or Model? -
Django prefetch_related and N+1 - How is it solved?
I am sitting with a query looking like this: # Get the amount of kilo attached to products product_data = {} for productSpy in ProductSpy.objects.all(): product_data[productSpy.product.product_id] = productSpy.kilo # RERUN I do not see how I on my last line would be able to use prefetch_related. In the examples in the docs it's very simplified and somehow makes sense, but I do not understand the whole concept enough to see myself out of this. Could I please get explained what's being done and how? I find this very important to understand, and where met by my first N+1 here. Thank you up front for your time. -
Class based view is not redirecting to Home after Upload
I am building a BlogApp and I build a Feature of multiple photo upload at a Time. When i add pictures the , I want to redirect to home BUT it stills on that same page. I have also tried HttpResponse but it is still not redirecting. views.py class UploadMultiple(View): def get(self, request): photo = Gall.objects.all() return render(self.request, 'new_gal.html', {'photos': photo}) def post(self, request): form = GallForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return redirect('home') I have also tried :- return HttpResponseRedirect(reverse('home')) When i select then photos are saving BUT it is not redirecting to home page. I have no idea, what am i doing wrong. I am new in using Class Based Views. Any help would be Appreciated. Thank You in Advance. -
How to make a permission for checking the Model only can be update by the belonged users?
The below is my code about model Domain's Update: serializer.py: class DomainUpdateSerializer(serializers.ModelSerializer): class Meta: model = Domain fields = "__all__" models.py: class Domain(models.Model): domain_name = models.CharField(max_length=512, help_text='domain. eg.example.com') cname = models.ForeignKey( unique=True, to=CNAMEModel, on_delete=models.DO_NOTHING, related_name="domains", help_text="CNAME") ssl_cert = models.TextField(max_length=40960, help_text="SSL cert + ca-bundle") ssl_key = models.TextField(max_length=40960, help_text="SSL key") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.domain_name def __unicode__(self): return self.domain_name class Meta: verbose_name = "domain" verbose_name_plural = "domain" ordering = ['ctime'] class CNAMEModel(models.Model): name = models.CharField(max_length=64, unique=True, help_text=". eg:gat.demo.com") desc = models.CharField(max_length=5120, null=True, blank=True, help_text="desc") desc_en = models.CharField(max_length=5120, null=True, blank=True") user = models.OneToOneField(unique=True, to=AuthUser, on_delete=models.DO_NOTHING, help_text="belong user") is_active = models.BooleanField(default=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = "CNAME" verbose_name_plural = "CNAME" ordering = ['ctime'] views.py: class DomainUpdateAPIView(UpdateAPIView): serializer_class = DomainUpdateSerializer permission_classes = [IsAuthenticated, IsAdminUser] queryset = Domain.objects.all() You see Domain belong to CNAME, CNAME belong to a user. I have a question, how can I make a permission for checking the Domain only can be update by the belonged users or AdminUser(IsAdminUser have solved)? -
Django ORM more than one row returned by a subquery used as an expression
My Subquery behaves differently on different machines. Subquery looks like: Sale.objects.filter(object_id=OuterRef("id"), is_canceled=False) .values("object") .annotate(total_amount=Coalesce(Sum("amount"), 0)) .values("total_amount") On my local machine I have 3 Sale instances and the result of the query is: <QuerySet [{'object': 1, 'total_amount': 210}]> On my dev machine I have 2 Sale instances and the result of a call looks like this: <QuerySet [{'object': 100, 'total_amount': 20}, {'object': 100, 'total_amount': 10}]> I checked the query Django ORM generates in both cases and it looks the same SELECT "object_sale"."object_id", COALESCE(SUM("object_sale"."amount"), 0) AS "total_amount" FROM "object_sale" WHERE ("object_sale"."object_id" = 1) GROUP BY "object_sale"."object_id", "object_sale"."price" ORDER BY "object_sale"."price" ASC -
How to fix "Infinite loop caused by ordering" error in Django
When trying to create an instance of a model from the Django admin site on some models that are inherited according to a similar principle, the following error pops up: enter image description here Please tell me how can I fix this? class Task(BaseEntity): """ Задача - проведение каких либо работ BaseProperties: title, created_at, closed_at, author, description, comment, photo BaseEntity: Временные: date_start_work_p, date_start_work_f, date_end_work_p, date_end_work_f Сотрудники: curator, working_team, observers, Связи админ. сущностей: lead_source Коммерческие: client_LE, expenses_p, expenses_f, expenses_is_calculated, contract_price_p, contract_price_f __str__.title BaseHavingSlug: slug BaseHavingManager: manager, assistants BaseHavingParent: project_parent, deal_parent, stage_parent, task_parent """ type_task = models.ForeignKey('TypeTask', on_delete=models.PROTECT, related_name='type_task', null=True, verbose_name='Тип Задачи') working_status_task = models.ManyToManyField('WorkingStatusTask', related_name='working_status_task', verbose_name='Рабочие статусы') closure_status_task = models.ForeignKey('ClosureStatusTask', on_delete=models.PROTECT, related_name='closure_status_task', verbose_name='Статус закрытия', null=True, blank=True) status_task = models.ForeignKey('StatusTask', on_delete=models.PROTECT, related_name='status_task', null=True, verbose_name='Статус Задачи') # если не null – связь по срокам previous_task = models.ForeignKey('Task', on_delete=models.PROTECT, related_name='previous_task_related', verbose_name='Предыдущая задача', null=True, blank=True) # Как считать стоимость – в деньгах или в часах in_money = models.BooleanField(default=True, verbose_name='В деньгах') # Затраченные рабочие часы # Изменить после заполнения можно только через согласование working_hours_p = models.PositiveSmallIntegerField(verbose_name='Рабочие часы (план)', unique=True) working_hours_f = models.PositiveSmallIntegerField(verbose_name='Рабочие часы (факт)', unique=True) # Как считать ФОТ – от плана или от факта salary_is_from_fact = models.BooleanField(default=True, verbose_name='В деньгах') salary = MoneyField(max_digits=19, decimal_places=4, default_currency='RUB', verbose_name='ФОТ', … -
Error When submit comment for the second post in Django
I creating a blog in this blog feed there are posts and for each post there are comments, So my problem when I submit a comment for the first post is submitting successfully but when I try to submit a comment for the second post or third it doesn't submit My comments Form class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True', }) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, self).save(*args, **kwargs) My comments view @login_required def add_comment_post(request): if request.method == 'POST': if request.POST.get('action') == 'delete': id = request.POST.get('nodeid') c = PostCommentIDF.objects.get(id=id) c.delete() return JsonResponse({'remove': id}) else: comment_form = PostCommentForm(request.POST ) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) return JsonResponse({'result': "No action took"}) My comment form in home page template <form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;"> {% load mptt_tags %} {% csrf_token %} <select class="d-none" name="post" id="id_post"> <option value="{{ video.id }}" selected="{{ video.id }}"></option> </select> <div class="d-flex"> <label class="small font-weight-bold">{{ comments.parent.label }}</label> {{ comments.parent }} {{comments.content}} <button value="Postcommentform" id="Postnewcomment" type="submit" style="color: white; border-radius: 0;" class="d-flex … -
DRF spectacular swagger ui problem when extending a new TokenAuthentication for DRF
when extending a new Token Authentication class from rest_framework_simplejwt.authentication.JWTAuthentication drf-spectacular swagger-ui authorize button disappears and there is no way to add token bearer, I guess when you subclass it goes wrong. steps to reproduce: first, create a Django project with rest framework and drf-spectacular and simple jwt installed and configured with documentation guidance. got to /swagger-ui/ and it works fine. then create a subclass of JWTAuthentication like below: from rest_framework_simplejwt.authentication import JWTAuthentication as JWTA class JWTAuthentication(JWTA): pass and in your settings: REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'path_to_your_module.JWTAuthentication', ), } and now if you go to /swagger-ui/ there is no authorize button!!! how can I fix this? and I even tried to create an AuthenticationExtension like: from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme class SimpleJWTTokenUserScheme(SimpleJWTScheme): target_class = 'spec.test.JWTAuthentication' but there is no way to register it anywhere nor on the internet nor in the documentation!! how can I fix authorize button when overriding an Authentication class?? -
Image is not passing to view (cropperjs, django, ajax)
I have an user profile where he can crop his image, and so after cropping, and printing data in view nothing is passed to view Form <form method="post" action="change_photo/" id="avatar_changing_form"> {% csrf_token %} <label for="upload_image"> {% if item.image%} <img src="{{item.image.url}}" alt="" style="max-height:300px"> {%else%} <img src="{%static 'avatar_sample.png' %}" id="uploaded_image" class="img-responsive img-circle" /> {%endif%} <div class="overlay"> <div class="text">Click to Change Profile Image</div> </div> <!-- <input type="file" name="image" class="image" id="upload_image" style="display:none" /> --> {{imageForm.image}} </label> </form> JS & Ajax $(document).ready(function(){ const imageForm = document.getElementById('avatar_changing_form') const confirmBtn = document.getElementById('crop') const input = document.getElementById('upload_image') const csrf = document.getElementsByName('csrfmiddlewaretoken') var $modal = $('#modal'); var image = document.getElementById('sample_image'); var cropper; $('#upload_image').change(function (event) { var files = event.target.files; var done = function (url) { image.src = url; $modal.modal('show'); }; if (files && files.length > 0) { reader = new FileReader(); reader.onload = function (event) { done(reader.result); }; reader.readAsDataURL(files[0]); } }); $modal.on('shown.bs.modal', function () { cropper = new Cropper(image, { aspectRatio: 1, viewMode: 3, preview: '.preview' }); }).on('hidden.bs.modal', function () { cropper.destroy(); cropper = null; }); $('#crop').click(function () { cropper.getCroppedCanvas().toBlob((blob) => { console.log('confirmed') const fd = new FormData(); fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('file', blob, 'my-image.png'); $.ajax({ type: 'POST', url: imageForm.action, enctype: 'multipart/form-data', data: fd, success: function (response) { console.log('success', response) $modal.modal('hide'); …