Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Server Error (500) Django App on AWS server
Good day, i have currently my django project running on an aws server. I have used Nginx and configured it all. The application is running, but when i try to login via the login page i have created or try to login via the admin panel it gives me a Server Error (500). I have my DEBUG=False and added my server dns to ALLOWED_HOSTS. As for the Database. I have got my SQL Database running on an Azure server and used environment variables (that i have permanently set in my ubuntu terminal) to get my password and username. I have also tried to set DEBUG to False and trying to figure out the issue when running python manage.py runserver so i could experiment with it on my localhost, but no luck. I cant access 127.0.0.1 eventhough i have added it to my Allowed hosts. How could i see what the error is? Thank you in advance -
Setting up hypertables in TimescaleDB with multiple time-series
I am about to integrate TimescaleDB in my django project, but what’s unclear to me is how timescale groups different timestamps together to form a time-series. Imagine I have multiple Drinks (coca-cola, lime-juice etc, fanta, water…). I can have a million drinks in my database. Each drink can have multiple time-series related to it. A time-series of consumption data over the years, a time-series of customer data over the years etc… Then imagine I also have food data with the same assumptions. I want to save all those data in a hypertable. I can start by creating a hypertable and inject all consumption data for Coca-Cola in the year 2018. Now i also want to store customer data for Coca-Cola too, but the time-stamps will collide. I will have 2022-12-03 multiple times. Thus timescale must have a best-practice of how to group timestamps together to from a time-series. Otherwise I could only have a single time-series in a hypertable. I see two solutions: I can save a foreign key or an object-id with the timestamp. E.g. 2022-01-01 and 5, whereas 5 is the id of coca cola object. Or I can create a meta-table which stores the meta-information about the … -
Relationships in Django - how to filter data
I've looked at a lot of entries and I know how to filter simple relationships. Unfortunately, I'm stuck and I don't know how to filter my table data when one of the tables is a branch of a certain string. models.py from django.contrib.auth.models import User class Autor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) description = models.TextField(blank=True, null=True) class Incident(models.Model): group_no = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) description = models.TextField(blank=True, null=True) deleted = models.BooleanField(default=False) class Department-leader(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="leader") department = models.ForeignKey(Group, on_delete=models.CASCADE) class Group(models.Model): group_no = models.CharField(max_length=40, unique=True) active = models.BooleanField(default=True) views.py def get_author(user): qs = Autor.objects.filter(user=user) if qs.exists(): return qs[0] return None def show_all(request): show_all_records = Incident.objects.filter(deleted=False).order_by('-id')[:300] if request.user.is_authenticated: autors_list = get_author(request.user) user_list = get_user_model() logged_user = get_object_or_404(user_list, username__exact=autors_list) (...) print("Logged user: " + str(logged_user.id)) else: logged_user = "" context = { 'show_all_records': show_all_records, 'logged_user': logged_user, } return render(request, 'incident/all_records.html', context) The show_all_records variable represents all the records of the Incident table and that is ok. The second thing I would like to display are entries for the logged in person i.e. all incidents in particular departments of the leader who is logged in. If the tables were connected linearly, I would have no problem building this filter. But how … -
How to increment counter in django templates
I am trying to get the total count of infringements for each infringer. The counter is not incrementing. ( {{ a|add:"1" }} ) It outputs 1 1 1 instead of total of 3. Please assist. {% for infringer in page_obj %} <tr> <td>{{infringer.id}}</td> <td>{{infringer.created|date:"d M, Y"}}</td> <td>{{infringer.name}}</td> <td>{{infringer.brand_name}}</td> <td>{{infringer.status}}</td> <td> {% with a=0 %} {% for i in inc %} {% if infringer.id == i.infringer.id %} {{ a|add:"1" }} {% endif %} {% endfor %} {% endwith %} views.py @login_required(login_url='login') def infringerlist(request): q = request.GET.get('q') if request.GET.get('q') != None else '' ings= Infringer.objects.filter(Q(created__icontains=q) | Q(id__icontains=q) | Q(status__name__icontains=q) | Q(brand_name__icontains=q) | Q(name__icontains=q), customer=request.user.customer,) paginator = Paginator(ings, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) inc = Infringement.objects.filter(customer=request.user.customer) context= {'page_obj': page_obj, 'inc': inc} return render(request,'base/infringers_list.html', context) -
requests hang unless timeout argument given
My backend runs on openshift and makes get requests to other openshift clusters via kubernetes python client. I am having an issue where requests hang until the default timeout value is reached. I have done some tests in the pod to see if it can reach other openshift clusters and discovered the following: requests.get("some_other_cluster_api_url") will hang and return correctly in 2 mins, but requests.get("some_other_cluster_api_url", timeout=1) returns correctly in 1 second. Why does the request not return immediately in the first case? -
Does django mail output get persisted in different tests?
Does django from django.core import mail mail.output get persisted over different tests? I have different tests that does email sending and now I see that the length of mail.output is more than the number of emails I'm sending in my tests. I have done mail.output=[] in both setUp and tearDown but I can still see extra outputs. Any ideas why this might happen? -
Django as_p() method equivalent for non-form / display only use cases
I have a handful of models with 10+ fields each. During my first draft of development I am less concerned about how things look and am trying to get to the critical components of the code ASAP. I love the myForm.as_p method built into the Forms object. The main benefit is that I can alter the models as needed, make my migrations, and the as_p will show these new fields without me having to change the template. My questions is: is there an equivalent method for display only use cases? I have tried combing through the docs but have not found a thing outside of forms. The ideal would be something like a class based DetailView that in the template can use {{ object.as_p }}. Anyone know of a dynamic display function like that outside of forms? -
Pass Image data of one view obtained from POST method to other view without using any Databases
I am working on a Django project . It fundamentally contains two views. First is HomePageView. It contains a form that take image input from user(anonymous).On submitting the form, user gets redirected to the second view, ResultView. forms.py from django import forms from .models import * class ImageForm(forms.Form): image = forms.ImageField(label = 'Choose an image below.') views.py from django.views.generic import TemplateView from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .models import * from .forms import * import base64 def HomePageView(request): if request.method == 'POST': form = ImageForm(request.POST , request.FILES) if form.is_valid(): image_object = request.FILES['image'] #or should i use : image_object = form.cleaned_data['image'] #or should i use : image_object = request.POST.get('image') request.session['image_object'] = image_object return redirect(to='ResultView') else: form = ImageForm() params = {'form': form} return render(request, 'home.html', params) home.html <form action="{% url 'ResultView' %}" method="post" enctype="multipart/form-data">{% csrf_token%} <!--- Styling ---> <div class="col-md-8 mt-4 pt-5"> <div class="container mt-5 "> <div class="row p-3 "> <div class="col-md-12 align-items-center"> {{ form.as_p }} </div> </div> <div class="row"> <div class="col-md-4 ms-3"><button type="submit" class="btn btn-outline-dark font-monospace" data-mdb-ripple-color="dark">SUMBIT</button></div> <div class="col-md-4"></div> <div class="col-md-4"></div> </div> </div> </div> </div> </div> </form> Now, I want to obtain the image that user has uploaded. Pass it to the result view, do some … -
Django REST: ignoring custom fields which are not part of model
My TimeReport model looks like this: class TimeReport(models.Model): minutes_spent = models.PositiveIntegerField() task = models.ForeignKey(Task, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) reported_for = models.DateField() note = models.TextField(null = True, blank=True) status = models.CharField(max_length=50, choices=State.choices, default=State.new) user = models.ForeignKey(User, on_delete=models.PROTECT) And my model serializer: class TimeReportCreateSerializer(serializers.ModelSerializer): class Meta: model = TimeReport fields = ( 'id', 'minutes_spent', 'reported_for', 'note', 'status', 'task_custom_id', ) task_custom_id = serializers.CharField() def create(self, validated_data): user = User.objects.get(auth_user_id = self.context['user_id']) task = Task.objects.filter(custom_id = validated_data['task_custom_id']).filter(user = user.id).first() report = TimeReport(**validated_data) report.user = user report.task = task report.save() return report So, the problem is, that I want to take a custom value in a serializer, which is not a part of a model and do some custom logic with it - in this case search for the right 'task' in the database. But when I try to parse the model by using report = TimeReport(**validated_data), it gives me an exception: TypeError at /api/report/ TimeReport() got an unexpected keyword argument 'task_custom_id' Im kind of new to Django and python itself, so - what is the best approach? -
How to make a form for selecting categories with parents in Django?
I have a model called Ad: class Ad(models.Model): # ... category = models.ForeignKey( Category, null=True, on_delete=models.CASCADE, related_name="ads" ) # ... It has a foreign key to a Category model which has a foreign key to itself so that it can have a parent: class Category(models.Model): parent = models.ForeignKey( "Category", on_delete=models.CASCADE, related_name="children", null=True, ) title = models.CharField(max_length=255) I created a model form for Ad model to allow users to create new ads: class AdForm(forms.ModelForm): class Meta: model = Ad fields = [ # ... "category", ] I want users to be able to select a parent category in the form and then, they should be able to select from the parent's children. How can I do such thing? -
View takes 1 positional argument but 2 were given
Trying to do a POST request to openAI but getting the error TypeError: View.__init__() takes 1 positional argument but 2 were given When I try post something: {"write hello world"} Here is my view: def get_help(user_input): response = openai.Completion.create( engine="text-davinci-002", prompt="user_input", temperature=0.5, max_tokens=1024, top_p=1, frequency_penalty=0, presence_penalty=0 ) return response["choices"][0]["text"] @api_view(['POST']) class receive_response(View): def post(self, request): user_input = request.POST["user_input"] response = get_help(user_input) return HttpResponse(response) and my urls.py: urlpatterns = [ path("get", get_help, name="get_help"), path("post", receive_response, name="post"), ] -
The future backend language in terms of popularity and revenue in 2023 and above
What is the future back language in terms of popularity and revenue in 2023 and above, please share your experience with me. 1 - Golang 2 - Python 3 - Node.js 4 - PHP I did a lot of research, but I didn't get any results -
Best way to install Facebook Meta Pixel and Conversions Api, and create a Facebook catalogue feed in Python Django?
i have created a simple e-commerce website using Python with Django, and some vanilla JS and Jquery -> https://greengoshop.mk. However now i need to install an existing Facebook Pixel with events and setup the Conversion API(server-side) events. Also I need to auto sync the products on save with an already created Facebook Catalogue. I have read the documentation facebook provides but I can not really comprehend it. Seeing as it is an e-commerce website, that would imply that orders and carts would have multiple products in them and i would like to handle those events in my backend but I do not know how to proceed. Are there any tools/python packages that would help me with my goal and which ones should i use? -
select field from html form in django
I create a form in html to register a user and i have problem in gender field <form action="" method="POST"> {% csrf_token %} <select name="gender"> <option hidden>Gender</option> <option value="0">Male</option> <option value="1">Female</option> <option value="2">Prefer not to say</option> </select> </form> my forms file class RegisterForm(forms.Form): GENDER = [ ("0", "Male"), ("1", "Female"), ("2", "Other") ] gender = forms.ChoiceField(choices=GENDER) then i want to get a valid data in view file def post(self, request): form = self.form_class(request.POST) if form.is_valid(): return HttpResponse("hello") i can't give is_valid() for this part of html my view is class based views I try without <select> with {{ form.gender }} that run right, But when i use <select> in html that didn't run -
Django set model value, using another value of the same model
I am creating a board game, and I want to set value job_exp using an age value, I tried to use redefined save method, but it changes value after each save,so I try to create method, but I got: TypeError: unsupported operand type(s) for -: 'IntegerField' and 'int' Here is models: class Character(models.Model): def set_job_exp(age): return randint(0, age - 18) age = models.IntegerField("Age",default=randint(18, 100)) job_exp = models.IntegerField('Job exp',blank=True,default=set_job_exp(age) How to convert IntegerField to int or do you have any ideas how to solve it? -
Is it possible to send a static file (image) from my Python Django backend to my NextJs front end (django rest framework)
as the title suggests I am using a Django BackEnd and a Next.js frontend, I have had no issues uploading an image from a NextJs form to django for static file storage. where I am running into issues is i cannot seem to send the image file back to the front end to take advantage of the nextjs component. basically everything I have attempted sends the path in the response which I can use as a src standard tag but I would like to understand how to send a full image file -
django include template repeated in all url but get data from main url
i have one html template for my main body and in every url this main body is fixed. but the data from this fixed body is show only in main url or in one url like this i have a inbox and number of message on it inbox message number in every url i have this message but in main url or view i send data to template for example if yo go to main url the number on inbox show but if you go to another url because the data is not in your view yo dont have number how can i fix this !!? or my question is how include template get data from special url in every url in django!? -
Using Django's "truncatechars" to get last n characters of a word
While I was learning Django Templates, I came to know that we can use Django's built in template's truncatechars function to get first n characters of a world like this; Here, data = Stackoverflow.com {{ data|truncatechars:9 }} # It would print "Stackover.." But what should I do If I need last 9 characters of a word like '..rflow.com' Is there built in function in django template which can give me the inverse of truncatechars:9 ? -
getCookie(name) in django for paypal integration
`I am trying to integrate paypal payment in one website. I need paypal payment id and status response. I have a paypal button integrated already using paypal.Buttons function. The problem I face is if I use csrf token, the paypal button disappears from the page. If I am not using the csrf then the function will work, but with errors "Forbidden (CSRF token missing.):". If I remove " 'X-CSRFToken': 'csrftoken' " from function sendData() and "var csrftoken = getCookie('csrftoken');" then the paypal button will appear again. var csrftoken = getCookie('csrftoken'); var url = "{% url 'payments' %}" // payments is a custom name var orderID = "{{ order.order_number }}" var payment_method = " PayPal" function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = docodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sendData() { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': 'csrftoken', }, body: JSON.stringify({ orderID: orderID, transID: details.id, // from paypal response payment_method: payment_method, status: details.status, // from paypal response … -
How do I record data FK'd to two other models?
Using the 'Pizza' example, I have a Toppings Model, I have a PizzaTemplate Model and a 'Pizza', and now I need to record an amount of topping for each pizza. For Example I have a 'Pepperoni Pizza', I need to record 1 scoop of cheese, 1 scoop of pepperoni. Then I might have a 'Pepperoni Pizza - Extra Pepperoni' which would be 1 scoop of cheese and 2 scoop of peperoni, it uses the same selection of toppings, which have already been defined, I just need to record how much of each. My Current models.py looks like this: class Topping(models.Model): name = models.CharField(max_length=100) unit = models.CharField(max_length=100) class PizzaTemplate(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField(Topping) class Pizza(models.Model): name = models.CharField(max_length=100) Im guessing I need another model like so: class Ingredients(models.Model): pizza = models.ForeignKey(Pizza) topping = models.ForeignKey(Topping) amount = models.IntegerField() I'm not sure if this is the correct way to achieve this or there's a smarter way? The idea is to be able to create a new pizza, choose a topping template, and then specify varying amounts of each topping for this particular Pizza Option. My idea was to dynamically create the form for each input on page load, eg, get the … -
Solution to filter by Cumulative sum and error: Window is disallowed in the filter clause
This is follow-up to a question to: Filter Queries which sum of their amount field are greater or lesser than a number which is supposed to be solved. Answer suggests using Window function with filter but this results in a error: django.db.utils.NotSupportedError: Window is disallowed in the filter clause. Comment from @atabak hooshangi suggests removing the Window function, but query doesn't work in intended way after that. Any ideas to solve this problem? -
how to get a column value of foreign key in the form of object?
There is 2 models Registration and RegistrationCompletedByUser, I want Registration queryset from RegistrationCompletedByUser with filters(user=request.user, registration__in=some_value, is_completed=True) over RegistrationCompletedByUser. Hence result should be like <QuerySet [<Registration: No name>, <Registration: p2>, <Registration: p-1>]>. Now what I tried is Registration.objects.prefetch_related('registrationcompletedbyuser_set') but filters() not working. Another way I tried is model Managers but don't pass parameters for custom filtering. models.py class Registration(models.Model): name=models.CharField(max_length=255) number=models.SmallIntegerField(null=True, blank=True) class RegistrationCompletedByUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) registration= models.ForeignKey(Registration, on_delete=models.CASCADE) points = models.SmallIntegerField(default=100) is_completed = models.BooleanField(default=False) -
Django Channels do not send message within except block in Celery task
I am currently facing an issue with the Django Channels and Websockets. I have an application that somehow works with files and Sharepoint. Issued code sample where defect occurs: @shared_task(bind=True) def upload_to_sharepoint_task(self, user_id: str, document_type: str, upload_file: str, filename: str) -> None: """Uploads a file to SharePoint.""" task_id = self.request.id try: upload_to_sharepoint(user_id, document_type, upload_file, filename) print(f"Task {task_id} completed successfully.") async_to_sync(get_channel_layer().group_send)(task_id, { "type": "send_task_status", "message": {'task_id': task_id, 'status': "SUCCESS", } }) except BackendError as e: print(f"Task {task_id} failed with error: {str(e)}") async_to_sync(get_channel_layer().group_send)(task_id, { "type": "send_task_status", "message": {'task_id': task_id, 'status': "FAILURE", 'error': str(e)} }) If everything the method upload_to_sharepoint does not throw an exception, everything works just fine - the message is sent to the group and, via WebSocket, propagated to the Client. However, if I try to simulate a situation when the exception is thrown (for instance, by throwing the BackendException explicitly), the error message gets printed in the console, but WebSocket does not receive any message nor the Client. My TaskConsumer: class TaskConsumer(WebsocketConsumer): def connect(self): self.task_id = self.scope['url_route']['kwargs']['task_id'] # Join the task_id group async_to_sync(self.channel_layer.group_add)(self.task_id, self.channel_name) self.accept() def disconnect(self, close_code): # Leave the task_id group async_to_sync(self.channel_layer.group_discard)( self.task_id, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] print(f"Task {self.task_id} received … -
ModuleNotFoundError: No module named '_sqlite3' Error when try to import sqlite3 and Django
I tried to Create Django Project. I'm able to create project but not able to run the runserver command. I got below error. I also tried to import sqlite3 got same error >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.11/sqlite3/__init__.py", line 57, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.11/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' >>> Python version: Python 3.11.0 -
File from django model not uploading
These are my models class Post(models.Model): title = models.TextField(default="no title") body = models.TextField(default="no body") creation_date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) document = models.FileField(upload_to="uploads/", null=True, blank=True) the one that isn't working is document, i have set up a form and when i "post" the form the other stuff like title ,body, creation date and creator are being saved but the document isn't, cant even find it in any folder this is my view class Post_List(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): posts = Post.objects.order_by("-creation_date") form = PostForm() context = { "post_list" : posts, "form" : form, } return render(request, 'social/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.order_by('-creation_date') form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.creator = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return redirect('/feed') I tried migrating again but nothing changed