Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Add 1 month above today's date with django python
I want to add 1 month to today's date and keep this date in database enter image description here i tried this but it gave error -
Media folder not working properly & Images not being saved - Django
I am trying to add images to a post. (Using Django v3.2.5) root_directory/settings.py: BASE_DIR = Path(__file__).resolve().parent.parent ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') root_directory/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), path('app2/', include('app2.urls')), path('app3/', include('app3.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app3/models.py: from django.db import models from ckeditor.fields import RichTextField class Post_Picture(models.Model): title = models.CharField('Title', max_length=120) image = models.ImageField(blank=True, null=True, upload_to="images/") caption = RichTextField(blank=True, null=True) def __str__(self): return self.title app3/forms.py: from django import forms from django.forms import ModelForm from .models import Post_Picture class PostPicForm(ModelForm): class Meta: model = Post_Picture fields = ('title', 'image', 'caption') labels = { 'Title': '', 'Caption': '', } widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Title your post'}), 'caption': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Anything extra you want to add?'}), } app3/views.py: from django.shortcuts import render, redirect from .models import Post_Picture from .forms import PostPicForm from django.http import HttpResponseRedirect from django.contrib import messages def your_home(request): friend_posts = Post_Picture.objects.all() return render(request, "app3/your_home.html", { 'friend_posts': friend_posts, }) def post_pic(request): submitted = False if request.method == "POST": form = PostPicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('post_pic?submitted=True') else: form = PostPicForm() if 'submitted' in request.GET: submitted = True return … -
Django does not add attribute to the custom ModelForm widget
I'm trying to add another attribute in HTML (placeholder) using Django Widgets, when I do it, they don't appear in the HTML. models.py class InvitadosIngreso(forms.ModelForm): class Meta: model = InvitadosIngreso fields = ['oficina_pro' ,'documento' widgets = { 'oficina_pro' : forms.Select(attrs={'class':'form-control'},choices=ch_pro) ,'documento ': forms.TextInput(attrs={'class':'form-control', 'placeholder':'prueba',}) } forms.py class InvitadosIngreso(models.Model): oficina_pro = models.CharField(max_length=100, default='') documento = models.CharField(max_length=100, default='') nombre = models.CharField(max_length=100, default='') class Meta: db_table = 'InvitadosIngreso' -
Django -> post/get work but loading a fixture gets a "no such column error'
I've created a new model, and can post and get, and I receive all the fields. this indicates the underlying table is correct. I also manually checked my migrations and all the fields are there. And manually check the serializer (which is observably working via post/get). However, when I try the dumpdata or loaddata command, I get the error: "no such column: creator". Why would these two command think the field doesn't exist when the other aspects of the app can use it?