Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project guidance required
This is a small project given to me. I need help. If possible, give me the code files in Django: Create a REST api to be consumed by a mobile app which tell you if a number is spam, or allow you to find a person’s name by searching for their phone number. Each registered user of the app can have zero or more personal “contacts”. The “global database” is basically the combination of all the registered users and their personal contacts (who may or may not be registered users). The UI will be built by someone else - you are simply making the REST API endpoints to be consumed by the front end. Data to be stored for each user: Name, Phone Number, Email Address. Registration and Profile: A user has to register with at least name and phone number, along with a password, before using. He can optionally add an email address. Only one user can register on the app with a particular phone number. A user needs to be logged in to do anything; there is no public access to anything. You can assume that the user’s phone contacts will be automatically imported into the app’s database … -
Cutting stock problem methods and techniques
I have taken an interest in creating a web app using React based on cutting stock problem. I have some questions about the topic: Should i pair React with Django or is there better alternative? I'm gonna implement two algorithms each for 1 Dimensional and 2 Dimensional (So 4 in total). What algorithms should i implement? Is there any recommended resources online that will aid me in my work? -
No module named 'debug_toolbar.urls' : version 3.1.1 installed
settings.py INSTALLED_APPS = ( 'debug_toolbar', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) urls.py if DEBUG: import debug_toolbar urlpatterns += url('__debug__/', include('debug_toolbar.urls')) requirements.txt Django django-debug-toolbar==3.1.1 its showing No module named 'debug_toolbar.urls' when testing on the server. -
django pass id in HttpResponseRedirect
I have page that shows a usecase details with edit button that redirects to editing the usecase. my views.py: def edit_usecase(request, ucid): try: usecase_details = Usecase.objects.filter(usecase_id=ucid) if request.method == "POST": usecase_name = request.POST['usecase_name'] usecase_description = request.POST['usecase_description'] usecase_details = Usecase.objects.get(usecase_id=ucid) usecase_details.user_name = usecase_name usecase_details.user_email = usecase_description usecase_details.save() if usecase_details: messages.success(request, "Usecase Data was updated successfully!") return HttpResponseRedirect('/usecase-details/usecase_details.usecase_id') else: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect('/usecase-details/uecase_details.usecase_id') return render(request, 'UpdateUsecase.html', {'usecase_details':usecase_details[0]}) except: messages.error(request, "Some Error was occurred!") return HttpResponseRedirect('/usecase-details/usecase_details.usecase_id') my url: path('update-usecase/<str:ucid>', av.edit_usecase), my template: <div class="row d-flex"> <div class="col-12 mb-4"> <div class="card border-light shadow-sm components-section d-flex "> <div class="card-body d-flex "> <div class="row mb-4"> <div class="card-body"> <div class="row col-12"> <div class="mb-4"> <h3 class="h3">Edit usecase details:</h3> </div> <!-- <li role="separator" class="dropdown-divider border-black mb-3 ml-3"></li> --> <form action="/update-usecase/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">Usecase name:</label> <input value="{{usecase_details.usecase_name}}" type="text" name="usecase_name" class="form-control" placeholder="Name of Employee" required> </div> <div class="col-lg-8 mr-f"> <label class="h6" for="exampleFormControlTextarea1">User Name:</label> <input value="{{usecase_details.usecase_description}}" type="text" name="usecase_description" class="form-control" placeholder="Name of Employee" required> </div> </div> <input type="submit" class="btn btn-primary" value="Submit Changes"> </form> </div> </div> </div> </div> </div> </div> </div> How can I pass the usecase id in HttpResponseRedirect to redirect me to the same page after updating the data> -
How can I allow user to log in with email and to be created with additional fields
I want users to be able to log in using their email address and password. For the registration form, I need to include the following fields: Username, Email, Phone Number, Password, Repeat Password, and Address. All users should be created using these fields. How can I do this please? -
Increase number of Postgres pool connections for each Uvicorn Worker of a Django Application
I am running an asynchronous Django server with django-postgrespool2 as its Database Engine on my local machine. No matter how I configure the pooling parameters, it creates only a certain amount of pool connections. This number seems to be directly proportional to the number of Uvicorn Workers I run for my application. The following parameters are configured in the settings.py DATABASE_POOL_CLASS = 'sqlalchemy.pool.QueuePool' DATABASE_POOL_ARGS = {"max_overflow": 500, "pool_size": 1000, "recycle": 300} I am using the QueuePool class of SQLAlchemy for queueing as mentioned in the official documentation of Django-Postgrespool2. Also, I have significantly incremented the pool size to 1000 and max_overflow to 500. After concurrently hitting requests with a load testing tool, what I have observed is, that the number of database connections in the pool only increase with the number of Uvicorn workers I have running. Even if I increment the pool size to 1000, the number of pool connections created are limited. My inferences, based on the number of Uvicorn workers I ran and the number of pool connections created are stated as follows: Number of Uvicorn Workers Pool Connections Created 5 80 6 96 7 112 8 128 9 144 10 160 50 773 The pool_size and … -
How to remove an annotate attribute from a Django query set?
I have a situation where I am annotating some values and I do not want those to be the output. qs = A.objects.annotate(data=...) I want to remove data before the serialization in my Django projects -
ImportError: Couldn't import Django?
when run with command python manage.py runserver crashes with the error The virtual environment is active, for some reason it does not see the packages that they are all installed.Virtual environment active packages all installed when run with command python manage.py runserver crashes with the error The virtual environment is active, for some reason it does not see the packages that they are all installed.Virtual environment active packages all installed -
There is an error when trying to order in python-django
Whenever I try to order something, I keep getting this error. Here is my views.py: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session del session[settings.CART_SESSION_ID] return redirect('product_list') Please can anyone help me to fix it? -
Remove "%...% in urls
My urls in django have %.... How can I change that? At first this was ok but suddenly changed at some point in my day. My views, models and urls are as follow: class Rant(UUIDModel, TitleSlugDescriptionModel, TimeStampedModel, models.Model): categories = models.ManyToManyField(Category) def slugify_function(self, content): return content.replace("_", "-").lower() def get_absolute_url(self): return reverse("rants:rant-detail", kwargs={"title": self.title}) def __str__(self): return self.title class RantDetailView(DetailView): model = Rant slug_field = "slug" slug_url_kwarg = "slug" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context path("<str:slug>/", RantDetailView.as_view(), name="rant-detail"), path("category/<slug:category>/", rant_category, name="rant-categories"),``` I have no Idea why the link on my localhost is `localhost:8000/first%20rant%20on%20rantr/` Does anyone know where I made a mistake? I'm expecting the urls to have `hyphens` in it like `http://localhost:8000/first-rant-on-rantr/` where did I make a mistake? -
Connecting to LND Node through a server-running Django Rest API
@swagger_auto_schema(tags=['Payment']) def get(self, request): url = ( "<instance address>" ) macaroon = connect.encoded_hex TLS_PATH ='tls.cert' headers = {"Grpc-Metadata-macaroon": macaroon} r = requests.get(url, headers=headers, verify=TLS_PATH) # disable SSL verification return Response(json.loads(r.text)) So I can connect and get the Info when sending a request from my local machine but it fails when sending request from my EC2 running on Elastic Beanstalk env with load balancer. I'm running a t3a.large instance type and Using Django as a framework. Can anyone help as by now I've tried many different solutions. This is the error I get : HTTPSConnectionPool(host='<host>', port=8080): Max retries exceeded with url: /v1/getinfo (Caused by SSLError(SSLError(1, '[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1131)'))) THANK YOU -
Django rest_framework quantity is not incrementing in ecommerce project
models.py class Cartlist(models. user = models.ForeignKey(User, on_delete=models. created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return self.user.username class Items(models.Model): cart = models.ForeignKey(Cartlist, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) order = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return '{}'.format(self.product) Views.py class AddCartView(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = Items.objects.all() serializer_class = AddCartSerializer Serializer.py class AddCartSerializer(serializers.ModelSerializer): class Meta: model = Items fields = ['product'] def create(self, validated_data): user = self.context['request'].user product = self.validated_data['product'] if Cartlist.objects.filter(user=user): item = Items.objects.filter(cart__user=user,product=product) if item: item.quantity += 1 item.save() return item else: item = Items.objects.create(cart=Cartlist.objects.get(user=user),**validated_data) item.save() return item else: cart = Cartlist.objects.create(user=user) cart.save() item = Items.objects.create(cart=cart,**validated_data) item.save() return item Exception Value:'QuerySet' object has no attribute 'quantity' if the product is already exists, then increment the quantity field by 1. Default value is 1 if the user add same product into their cart list the product quantity must be increment by 1 -
Reverse for 'edituser' with arguments '('',)' not found
I have this function in Django function editFunc(id) { $.ajax({ type: "POST", url: "{% url 'edituser' id %}", data: { id: id }, dataType: 'json', success: function(res) { $('#ProductModal').html("Modifica dati"); $('#product-modal').modal('show'); $('#id').val(res.id); $('#username').val(res.username); $('#first_name').val(res.first_name); $('#last_name').val(res.last_name); $('#email').val(res.email); $('#is_staff').val(res.is_staff); $('#password').val(""); $("#password").attr("required", false); $("#passl").html('Password (lasciare il campo in bianco per non modificare la password).'); } }); } I checked the value of id and is ok But i have the error: Reverse for 'edituser' with arguments '('',)' not found To better explain: id="1"; url: "{% url 'edituser' id %}", doesn't work url: "{% url 'edituser' "1" %}", works What is wrong and howto solve ? -
Django - Display 2 Datefields for a Course. When it starts and when it ends
class Kurs(models.Model): # Kursleiter = # Thema name = models.CharField(max_length=200) beschreibung = models.TextField(null=True, blank=True) # teilnehmer = # auto_now macht immer, wenn wir was ändern einen Timestamp updated = models.DateTimeField(auto_now=True) # auto_now_add macht nur einen Timestamp created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is my Models.py Class. I want to create 2, in the Admin Panel visible Fields where I can enter the Start Date and End Date for my Courses. When I tried it this way: start_date = models.DateField(default=timezone.now) end_date = models.DateField(default=timezone.now) start_time = models.TimeField() end_time = models.TimeField() My Commandline Displays this Error: It is impossible to add a non-nullable field 'end_date' to kurs without specifying a default. This is because the database needs something to populate existing rows. I hoped to get 2 Date Fields in my Admin Panel in the View, showed in the ImageAdmin Panel, where I wish to display -
How to add different ranges for a model fields in django admin page
I need sample data like below , i mean if a entry created 1,10 a new row should automatically populated with new values 11 to 100, if i edit the next row i.e making 100 to 40 new row should be created with 41 to 100, i should not able to edit start value. Can anyone suggest if their is any package or any in build approcah? start_value end_value 1 10 11 40 41 100 Models.py class A(Model): start_value = IntegerRangeField(min_value=-100, max_value=100, default=0) end_value = IntegerRangeField(min_value=-100, max_value=100, default=100) class B(Model): ranges=ManytoManyField(A) forms.py class Aform(ModelForm): class Meta: model = A admin.py class AAdmin(TabularInline): model = A form = Aform class RangeAdmin(ModelAdmin): inlines=(AAdmin) site.register(B,RangeAdmin) -
Ordering is not working for string numerical values
I have a text field(Django) for the amount in the DB like amount = models.TextField(null=True, blank=True) SQL query select id, amount from payment order by amount asc; id | amount | -------+---------+ 12359 | 1111111 | ----> entered as "1111111" i.e a string value 12360 | 122222 | 12342 | 20 | 12361 | 222222 | 12364 | 2222222 | 12362 | 2222222 | 12290 | 260.00 | 12291 | 260.00 | 12292 | 260.00 | 12336 | 32 | 12363 | 3333333 | 12337 | 355 | 12331 | 45 | 12341 | 740 | 12343 | 741 | Problem - Ordering is not working as expected. Is it the expected behavior? -
jquey DataTable Ajax add extra column empty value
I have this javascript function: $(document).ready(function() { var table = $('#ourtable2').DataTable({ language: { url: '//cdn.datatables.net/plug-ins/1.13.3/i18n/it-IT.json', }, "ajax": { "processing": true, "url": "{% url 'ausers' %}", "dataSrc": "", }, "columns": [ { "data": "id"}, { "data": "username"}, { "data": "first_name"}, { "data": "last_name"}, { "data": "email"}, { "data": "is_staff"}, { "data": null, "render": function ( data, type, row, meta ) { return '<a href="" onClick="editFunc('+data['id']+')">Modifica</a>'; } }, ], }); }); The issue is that data['id'] is empty What is wrong ? How can i retrieve the value of id ? -
How to use Django to search database and display info in web application?
I'm currently working on a data visualization board. Cyber Security Data Visualization I know a few things about creating classes in models.py, objects in views.py, and putting the value of objects in an HTML file. But the best fuzzy search I know is like this: isc_2022 = Isc.objects.filter(issue_date__startswith='2022').count() This only gets a count number, but now I want to put information in HTML file through Django. The information is specially selected and ordered like this: Search MySQL It is not hard for Python to get a list from a database, here is how I do it: import pymysql connection = pymysql.connect( host="localhost", user='root', password='xxxxxx', database='project', ) cursor = connection.cursor() cursor.execute("""SELECT company, COUNT(*) AS count FROM cc_statistic GROUP BY company ORDER BY count DESC LIMIT 5;""") myresult = cursor.fetchall() mylist = [] for x in myresult: mylist.append(x) print(mylist) But how can Django do this and dynamically connect the values with my web application? And more importantly, is there any better way than asking on Stack Overflow to obtain knowledge like this? I find the official document for Django, like other documentation for other libraries, not easy to use. And they don't always have the thing I want. Thank you for spending … -
How to add an exmaple to swagger_auto_schema in django rest framework?
I am working with @swagger_auto_schema for documenting APIs in django-rest-framework. I want to add examples for both input and output. here is my code for one of the APIs. from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema @swagger_auto_schema( methods=['post'], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['name', 'lastname', 'username', 'password', 'confirm_password'], properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, max_length=50), 'lastname': openapi.Schema(type=openapi.TYPE_STRING, max_length=50), 'username': openapi.Schema(type=openapi.TYPE_STRING, description="it must be unique for every person. it must not contain space or invalid characters."), 'password': openapi.Schema(type=openapi.TYPE_STRING), 'confirm_password': openapi.Schema(type=openapi.TYPE_STRING, description="password and confirm password must be same"), 'national_code': openapi.Schema(type=openapi.TYPE_STRING), 'license_code': openapi.Schema(type=openapi.TYPE_STRING), 'birthdate': openapi.Schema(type=openapi.TYPE_STRING, default="yyyy-mm-dd", description="it is actually a date"), 'gender': openapi.Schema(type=openapi.TYPE_INTEGER, enum=[(1, _("Male")),(2, _("Female"))]), 'address': openapi.Schema(type=openapi.TYPE_STRING), 'email': openapi.Schema(type=openapi.TYPE_STRING), 'phone_number': openapi.Schema(type=openapi.TYPE_STRING), 'image_code': openapi.Schema(type=openapi.TYPE_STRING, description="it is the base64 code of the image"), }, # One example for a correct body ), responses={ 200: 'Staff Created Successfully!', # One example for 200 status code 400: 'Error!', }, operation_description="Add a new staff API. The role field(=staff), customer field(=parent.customer) and parent would be set automatically", ) And this is the rendered schema in swagger. But I want to add two read only JSONs jsut for rendering the correct input and the desired output. I will be grateful for any helpful link or examples. -
Has anyone figured out how to create a Django Persistent Connection or SSE?
I'm trying to create a web application for ordering food where a kitchen logs into a webpage and then receives real time updates on the orders. Ideally they would just leave the webpage open for 12-24 hours at a time. Can websockets do that? I've been trying to get django_eventstream to work, but there are so little examples and explanations on how to get it to work, has anyone been successful at this? -
Django-admin/Python manage.py makemessages gives error and deletes already translated msgstr
Basically i have been facing this issue for about 3 days, I have been trying to run the command line: python manage.py makemessages -l ar Which usually should work, however, its lately been deleting lines from Django.po in which if I compilemessages it causes the system to crash with multiple errors. When running python manage.py makemessages -l ar , I get some warning that I have never seen before on older translations, the warnings that i get is: warning: The following msgid contains non-ASCII characters. This will cause problems to translators who use a character encoding different from yours. Consider using a pure ASCII msgid instead. This is truly annoying and its causing me to bash my head around for hours, would appreciate the help. EDIT: After redoing the translation again from the start, I had to again do makemessages for new lines, and guess what?, the same error appeared and deleted all the changes I made. I would appreciate some help. That it would just refractor and add the new lines to be translated rather than delete 3 years of work. -
I want create conditional questions Django and Graphql
I did not now how create this logic. Form example we have different stages and in this stages we have some conditional questions it look like for example If the user selects I have no education in the 4th question, the stage about education should not be shown to him, if he chooses I have education, the stage about education should be shown. In front I use React in backend i use django graphql. can someone give mee some advise -
Image from database to send in whatsapp
Now I want to take orders on WhatsApp number for that I have used pywhatkit when i visit particular product detail, i want image of product to send from database, iam facing problem in that I have used pywhatkit module to send product detail, now I want image also to appear while sending WhatsApp msg but Iam getting only text related to product and image URL and path I am getting instead of image -
can we create arrayfield without creating model container?
I am facing problem in creating array field in mongo using django... I am using djongo connector... can't we create ArrayField in without specifying the model container ... I don't want to specify model_container in ArrayField because I don't want to make my model a child class and don't want to give value each and every field for parent class assigned in model_container... I tried - from djongo import models models.ArrayField() I am expecting - I just want to create array field in mongo db with json format/dictionary inside like [{"key1":"value1"}, {"key2":"value2"}] -
How do I make my content published automatically after a Webflow POST request
So I am adding items in my collection that I have in Webflow. The POST request I make is something like this. url = "https://api.webflow.com/collections/<collection_id>/items" payload = {"fields": {}} headers = { "accept": "application/json", "content-type": "application/json", "authorization": <bearer_token> } requests.post(url, json=payload, headers=headers) I added '?live=True' in my URL which apparently means that my content should be published without me needing to do it manually from Webflow. However, it doesn't work. Every time I create an item using a POST, I have to go to Webflow and publish my content. Is there a way around it?