Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django payal with multiple products returns
I'm using django-paypal and PayPalEncryptedPaymentsForm as def payment_process(request): host = request.get_host() paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, # "item_name": "python_book787", # "amount": "13", # "invoice": "some invice kkili9", "currency_code": "USD", "notify_url": f"http://{host}{reverse('paypal-ipn')}", "return_url": f"http://{host}{reverse('payment:success')}", "cancel_return": f"http://{host}{reverse('payment:cancel')}", } i = 1 for x in Order.objects.filter(user=request.user): paypal_dict.update({f"item_name_{i}": str(x.product.name)}) paypal_dict.update({f"amount_{i}": x.product.price}) i += 1 form = PayPalEncryptedPaymentsForm(initial=paypal_dict) return render(request, "payment/payment_process.html", {"form": form}) and in my templates that's {{ form.render }} but when i click to Buy it button, it loads a page like this Then what ever price i enter and continue.. paypal wants me to pay that much price. (Why it just do like this) :\ -
Passing and Using Dictionaries in Django Template Tags
I have a function that uses the psutil library to fetch CPU usage data. import psutil from django.utils.safestring import mark_safe def get_cpu(): """Gets the system-wide CPU utilisation percentage""" utilisation = list(psutil.cpu_percent(interval=1, percpu=True)) cpu_data_utilisation = [] load_avg_list = [] cpu_data = {} for count in range(len(utilisation)): count = count + 1 cpu_data_utilisation.append({ "label" : str("CPU " + str(count)), "util" : round(utilisation[count-1]) }) load_avg_tuple = tuple(psutil.getloadavg()) load_avg_1 = load_avg_tuple[0] load_avg_5 = load_avg_tuple[1] load_avg_15 = load_avg_tuple[2] load_avg_list.append({ "1" : round(load_avg_1), "5" : round(load_avg_5), "15" : round(load_avg_15) }) cpu_data = { "core_util" : cpu_data_utilisation, "load_avg" : load_avg_list, } return cpu_data I also have a template tag which calls and returns the get_cpu function. @register.simple_tag def get_cpu_data(): return mark_safe(get_cpu()) In the HTML file, adding these two lines: {% get_cpu_data as cpu_data %} {{ cpu_data }} Renders this: {'core_util': [{'label': 'CPU 1', 'util': 66}, {'label': 'CPU 2', 'util': 21}, {'label': 'CPU 3', 'util': 62}, {'label': 'CPU 4', 'util': 22}, {'label': 'CPU 5', 'util': 56}, {'label': 'CPU 6', 'util': 22}, {'label': 'CPU 7', 'util': 54}, {'label': 'CPU 8', 'util': 23}], 'load_avg': [{'1': 5, '5': 5, '15': 4}]} The dictionary has two keys, core_util and load_avg. I want to take the lists out of the values paired to … -
Passing Dictionary from Views and Accessing in JavaScript
I am passing dictionary from Views in Django, and want to access in JavaScript(written in HTML) -
How to fix error upgrading Wagtail 2.10.2 to 2.11.8?
I've been upgrading from Wagtail v1.13 / Django v1.11 / Python 3.5.2 to bring a project up to date. Everything has gone smoothly I'm now at Wagtail 2.10.2 / Django 3.0.14 / Python 3.8.9 The project uses puput, so can't go beyond Django 3.0.14 until puput supports a newer version of Django. That's not a problem, I'm happy with that for now. However after installing Wagtail 2.11.8, when I run makemigrations I get the following error: AttributeError: module 'wagtail.core.models' has no attribute 'MultiTableCopyMixin' The Wagtail 2.10.2/Django 3.0.14 combination created 0038_auto_20210624_0634.py that contains the following line: bases=(wagtail.core.models.MultiTableCopyMixin, models.Model), Sure enough in Wagtail 2.10.2 wagtail.core.models.MultiTableCopyMixin exists, but in Wagtail 2.11.* MultiTableCopyMixin has been removed. Any ideas? -
Calling a view function within a "classic" function in Django
Is it possible to call a view function (and return a rendered HTML back to the browser) from a function? Many thanks in advance for your help. -
pandas to_json , django and d3.js for visualisation
I have a pandas dataframe that I converted to json in order to create graphs and visualize with d3.js so I would like to know how to send this json format obtained in django (in the view or template) in order to visualize with d3.js def parasol_view(request): parasol = function_parasol() parasol_json = parasol.to_json(orient='records') parasol = parasol.to_html(index = False, table_id="table_parasol") context = { 'parasol': parasol 'parasol_json':parasol_json } return render(request,'parasol.html',context) template : {%block content%} {{parasol| safe}} {{parasol_json| safe}} {%endblock content%} -
Empty UpdateView form for extended AbstractUser in Django
I’m trying to build my first Django custom user model extending AbstractUser as MyUser which then has a OneToOne relationship with my Employee class (and, later, with other classes such as Contractor). I’m using GCBV, and creating and displaying a new employee work as expected however the update form contains the correct fields but they are empty and I don’t understand why. The database contains the expected data from the create. I have other GCBVs working with full CRUD for classes without the user connection so I hoped that I understood enough to get the user part working - clearly not! Do I need to do something extra for Update that isn’t needed for Create or for non-user-related models? Any help would be much appreciated - this is my first post here so I hope that I have provided enough detail: models.py class MyUser( AbstractUser ): # Uses username, first_name, last_name and email from AbstractUser is_employee = models.BooleanField( default = False, verbose_name=_('Staff')) is_contractor = models.BooleanField( default = False, verbose_name=_('Contractor')) class Employee( models.Model ): user = models.OneToOneField( settings.AUTH_USER_MODEL, # MyUser on_delete=models.CASCADE, related_name='employee', ) is_staff_admin = models.BooleanField( default=False, null=True, verbose_name=_('Administrator') ) views.py class EmployeeUpdateView( UpdateView ): model = Employee pk_url_kwarg = 'employee_pk' … -
98% of memory is in use in aws beanstalk enviroment
I'm doing an app with django and I'm hosting it in a beanstalk enviroment in aws, I was deploying new a new version to the env but this suddenly went from "OK" to "Degraded" the logs were auto deleted and the hint I have is that when I look in "Causes" its says im using 99% of the memory. I'm not sure what can I do to solve it, any ideas? -
django celery-progress: default messages of element 'progress-bar-message' replace custom message
I start using Django celery-progress and have an issue with messages displayed while waiting for task to start in my template, I have customized progress-bar-message element with an icon and changing text Waiting for progress to start... for Waiting for import to start...: <div id="progress-bar-message"><i class="fa fa-clock-o" aria-hidden="true"></i><span> Waiting for import to start...<span></div> but even if my changes are displayed at start, it is change to Waiting for task to start... without icon... I do not understand how to manage this -
Suspicious activity on Django
I was running a django server on my aws instance for testing and these requests popped, showing bad requests from an unknown ip with a link of russia. I am unsure what is it and is this a major security threat. Can anyone explain what does this means ? -
Django application level wsgi setting
My django project has three apps as shown. /project/ -/project/ - settings.py - wsgi.py - urls.py -/auth/ -/app1/ -/app2/ Here app1 and app2 are independent of each other (use different models and views) but share same auth. Is it possible to have separate app level WSGI file rather than project level so that the apps can be well isolated ? -
How to write a condition, that the function is not executed, if there is data in the database? Django
Every time a run my Django app, the same data is inserted into database. I only want to include data the first time, when there are no values in base(table). I am getting my data from API and Json. view.py from django.shortcuts import render, HttpResponse from .models import Brands import requests def get_brends(request): all_brands = {} url ='http://makeup-api.herokuapp.com/api/v1/products.json?brand' response = requests.get(url) data = response.json() for result in data: brand_data = Brands( name=result['name'], price=result['price'], image_link=result['image_link'], brand=result['brand'], category=result['category'], product_type=result['product_type'], description=result['description'], ) brand_data.save() all_brands=Brands.object.all().order_by('-id') return render(request, 'brands_makeup/brands.html', { "all_brands":all_brands}) model.py class Brands(models.Model): name = models.CharField(max_length=100, default="None") price = models.DecimalField(decimal_places=3,max_digits=4,null=True,blank=True) image_link = models.CharField( max_length=50, blank = True, null = True) brand = models.CharField( max_length=150, blank = True, null = True) category = models.CharField( max_length=150, blank = True, null = True) product_type = models.CharField( max_length=150, blank = True, null = True) description = models.CharField( max_length=1500, blank = True, null = True) def __str__(self): return self.name , self.price , self.category , self.brand I am only trying to include JSON once in my database when a database is empty. -
Call a separate http request from django view and return response as view response
I need to call Microsoft graph API from front end. I have designed the flow like this: Ajax Call --> Django View --> Microsoft Graph API --> Return response of graph api from django view I am sending an ajax call from front end to a django view. In view i am using concurrent module to initiate a new thread for http request(calling Microsoft graph API). I have followed this answer. Issue is the http request that i have initiated for Microsoft Graph API is getting timed out. If i initiate the request stand alone from python manage.py shell then it is working fine probably because it is an independent process. class MicrosoftSubscriptionList(LoginRequiredMixin, ListView): model = ApiSubscription template_name = "ReportingWebapp/microsoft_api_subscriptions.html" def post(self, request): action = request.POST.get("action", None) if action == 'create_presence_subscription': try: with concurrent.futures.ThreadPoolExecutor() as executor: # create_presence_subscription function will call graph api future = executor.submit(create_presence_subscription) api_response = future.result() return HttpResponse(api_response.text) except Exception as e: log.exception(e) return HttpResponse("Internal Error") Microsoft graph api error that i am getting "message":"Subscription validation request timed out." -
changing django admin panel interface
here is the Django default admin panel I want to keep the functionality (like accessing users table and buttons) but change the interface. I don't want to write Django and It is also hard and needs much time to style this panel again. I want exactly the default admin panel but with an attractive style and appearance. I saw Django admin dashboard templates but it did not have the functionality, for example a button that when you click you can see users table and you can add or edit user. Is there any quick way (like templates or a stylesheet) to achieve this goal? -
issues in django REST framework custom user registration,login and login with separate profile for each role
I am beginner to Django and try to implement custom user model and providing functionality for registration, login with separate profile for each role. for application I am trying to develop there us 3 users roles 1) student 2) Teacher 3) Institute so I am trying to address following broad level requirement a) need separate registration REST API URL for student, Teacher and Institute b) registration REST API URL for student, Teacher and Institute should require only unique email address and password. username may derived internally based on users email Address c) After registration of student/teacher/institute it should create blank profile and separate REST API be provided for updating Profile of student, teacher and institute. field of profile of student , teacher and institute are different as shown in content of model.py my current code as shown below does not work as expected and gives many errors a) python manage.py createsuperuser command gives error File "D:\djangoprojects\hellodjangousers\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' b) after commenting some code and creating super user errors occurs for creating profile of user c) url http://127.0.0.1:8000/api/v1/rest-auth/registration/ when posted shows error TypeError at /api/v1/rest-auth/registration/ save() takes 1 positional argument … -
How to store API data in variable/Memory in Python or django and reuse it when required without calling API again?
How to store API data in variable/Memory in Python or django and reuse it when required without calling API again? without storing data in any file. -
Unique single comment like and dislike for each user
My comments model: class Comment(models.Model): product = models.ForeignKey(Product ,on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User ,on_delete=models.CASCADE, max_length=80, related_name='comments_user') body = models.TextField() subject = models.CharField(max_length=255, default="") created_on = jmodels.jDateField(auto_now_add=True) created_on_time = models.TimeField(auto_now_add=True,null=True) active = models.BooleanField(default=False) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) And my like and dislike views: def like(request,product_id,comment_id): product = get_object_or_404(Product, id=product_id) comment = get_object_or_404(Comment, product=product, id=comment_id) comment.like = comment.like + 1 comment.save() return redirect("/products/category/"+str(product.product_category.category_url)+"/"+str(product.product_subcategory.subcategory_url)+"/"+str(product.product_url)+"/") def dislike(request,product_id,comment_id): product = get_object_or_404(Product, id=product_id) comment = get_object_or_404(Comment, product=product, id=comment_id) comment.dislike = comment.dislike + 1 comment.save() return redirect("/products/category/"+str(product.product_category.category_url)+"/"+str(product.product_subcategory.subcategory_url)+"/"+str(product.product_url)+"/") I want each user only like or dislike the specific comment. and then if that user changed the opinion and wanted to dislike it, the like would be remove and add 1 more to dislike. and also one comment just can get one like or dislike from one user. -
render_to_string doesn't render image
I have this Market Application where cashier can print receipts via website. I render an html document and order printer to print. But it seems that it doesn't render/find images. Here is my code: context = { 'order': order, 'item': item } html = render_to_string('receipt.html', context) And my html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use PyQt5 to print thermal receipts</title> </head> <body> <img src=' {% static "images/favicon.png" %} ' style="align-items: center;" width="130" height="130"/> <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: {{ order.code }} </span> <br> <br> <span>Order time: {{ order.created }}</span> <br> <br> <span>Cashier: {{ order.waiter }}</span> <br> <!--- and so on ---> It's my first project using render_to_string function so any help would appreciated. -
Django: Reverse for ‘topic_posts’ with arguments ‘(3, ”)’ not found
The reverse of '‘topic_posts’ works fine in other places. But it doesn’t work here. HTML file <td class="align-middle"> {% with post=board.get_last_post %} <small> <a href="{% url 'topic_posts' board.id post.topic.id %}"> By {{ post.created_by.username }} at {{ post.created_at }} id - {{ board.id }} {{ post.topic.id }} </a> </small> {% endwith %} </td> url setting path('boards/<int:board_id>/topics/<int:topic_id>/', views.topic_posts, name='topic_posts'), topic = get_object_or_404(Topic, board_id=board_id, id=topic_id) return render(request, 'topic_posts.html', {'topic': topic}) When I changed the board.id and post.topic.id to integer value , for exmaple 1 and 24, the web would render. I commented <a href="{% url 'topic_posts' board.id post.topic.id %}"> and added {{ board.id }} {{ post.topic.id }} to see if there is an error with the query, turned out there is no problem, it would render 1, 24 on the webpage. Then I tried <a href="{% url 'topic_posts' board.id 24 %}"> It worked fine, but <a href="{% url 'topic_posts' board.id post.topic.id %}"> still won’t work. Thanks for reading! -
ENVIAR MENSAJE A UN USER ESPECIFICO QUE SE LE PASA POR URL DJANGO POSTMAN
A partir de la pagina de detalle de un anuncio, envio por la url el usuario que ha subido el anuncio, para enviarle un mensaje. Necesito que el campo de destinatario en el formulario del mensaje se muestre este usuario y no tenga yo que buscarlo manualmente. El sistema de mensajes es con Postman y Django. [Formulario mensaje][1] [1]: https://i.stack.imgur.com/No9c7.png <form action="{% if next_url %}?next={{ next_url|urlencode }}{% endif %}" method="post">{% csrf_token %} <table> {% block pm_write_recipient %}{% endblock %} {% comment %} {{ form.as_table }} {% endcomment %} <p> <label>Destinatario: </label> <input type="text" name="recipients" id="recipients" > </p> <p> <label>Asunto: </label> <input type="text" name="subject" id="subject" > </p> <p> <label>Contenido: </label> <textarea name="body" rows="3" id="body" ></textarea> </p> </table> Arriba se ve que le paso el usuario marta, este usuario debe aparecerme en el campo destinario. urls.py (postman): views.py (postman): class WriteView(ComposeMixin, FormView): """ Display a form to compose a message. Optional URLconf name-based argument: ``recipients``: a colon-separated list of usernames Optional attributes: ``form_classes``: a 2-tuple of form classes ``autocomplete_channels``: a channel name or a 2-tuple of names ``template_name``: the name of the template to use + those of ComposeMixin """ form_classes = (WriteForm, AnonymousWriteForm) autocomplete_channels = None template_name = 'postman/write.html' @sensitive_post_parameters_m @never_cache_m … -
DJANGO : how to run API-request in the background so my users experience no delay?
I've a script that get's data from an API. The API needs some time to calculate and return the values. This means that my my user experiences a lot of delay (9sec) to go to the next page, until the API has returned the values. Is there a way to run the script with the API in the background? So the user can continue their experience without any hinder ? (I wonder if async functions can help?) the code I use to run the API: import requests body = {...} headers = { 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', 'Authorization': '...', 'Content-Type': 'application/json; charset=utf-8' } call = requests.post('https://api....', json=body, headers=headers) print(call.status_code, call.reason) print(call.text) -
How to use multiple lookup fields in Django Rest framework in a class based view?
I literally searched similar questions but didn't a answer that solves my question Here i want a functionality like a question can have multiplt answers my models.py class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) status = models.BooleanField(default=False) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.question def clean(self): if self.doubt_class_id and self.conceptual_class_id : raise ValidationError("only one field can be set") class AnswersModel(models.Model): answer = models.TextField() question_id = models.ForeignKey(QuestionModel, on_delete=models.CASCADE) my urls.py path('questions/', views.QuestionModelView.as_view()), path('questions/<int:id>/', views.QuestionModelViewID.as_view()), path('questions/<int:id>/answer/', views.AnswerModel.as_view()), my views.py # Create your views here. class QuestionModelView(mixins.ListModelMixin, mixins.CreateModelMixin,GenericAPIView): queryset = models.QuestionModel.objects.all() serializer_class = serializers.QuestionModel_serializer permission_classes = [IsAuthenticated] def get(self, request): return self.list(request) def post(self, request): return self.create(request) class QuestionModelViewID(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,GenericAPIView): queryset = models.QuestionModel.objects.all() serializer_class = serializers.QuestionModel_serializer permission_classes = [IsAuthenticated] lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) def put(self, request, id=None): if int(request.POST.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if id: return self.update(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) def delete(self, request, id=None): if int(request.POST.get('author')) != self.request.user.id: return Response("you cannot destroy othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if id: return self.delete(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) class AnswerModel(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): … -
Django Rest Framework: consuming external API's
I'm practicing my Django by building app that consume API's from several sport sites, what I want to achieve is a single API endpoint that works as a search engine and return all possible results with pagination of 10 results per request. What is the best approach for building app like this? How to avoid being blocked by making too many requests per minute, is it a good idea to store all the requested data in local cache/db ? -
'super' object has no attribute 'set_context'
I upgrade Django version from 1.11 to 3.2 and upgrade the installed python. I am facing an error at this line super().set_context(serializer_field) Below is the Full class code. '''' class UniqueForProjectValidator(UniqueValidator): """ Validates uniqueness of field within project Context of parent serializer must contain 'project' key Model must have project field """ def set_context(self, serializer_field): super().set_context(serializer_field) self.project = serializer_field.parent.context['project'] def filter_queryset(self, value, queryset): queryset = queryset.filter(project=self.project) return super().filter_queryset(value, queryset) '''' -
How can I delete all child objects of a parent object without deleting parent object with Django
I have two models that use the same class as foreign key. I don't want to delete the parent model (which is being used as foreign key) but delete the child models that are associated with the parent model. class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, default=None) class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, default=None) Now I am deleting them separately as below : b_list = B.objects.filter(a = A) for b_list_item in b_list: b_list_item.delete() c_list = C.objects.filter(a = A) for c_list_item in c_list: c_list_item.delete() How can I delete them all together with a single command ?