Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why when i use 0 as parameter is not found, but is completely fine when the parameter is 1, 2, 3, ... in Django-Redirect
articles = { 'sports': 'Sports news', 'music': 'Music news', 'travel': 'Travel news', 'tech': 'Tech news', } def num_page_view(request, num_page): topic_list = list(articles.keys()) print(topic_list) topic = topic_list[num_page] return HttpResponseRedirect(topic) I'm currently learning dynamic url. Here's when i use /0 it is shown not found Error input 0 But, when i use /1 it's completely fine, it redirected into "music" page. Please Help! I tried print the topic_list, and it is shown like this: ['sports', 'music', 'travel', 'tech'] when i print topic_list[0] it is shown as "sport" but i dont know, i cant do redirect. -
Django can't connect to Postgresql
I'm working on my first ever Django project. I've Create a Postgresql Database on a host(which my project is already on that host) which is accessible on public network too .I can connect to the database on my local computer so the database is created. But in production I'm trying to migrate to the database but I got the FATAL: database "postgre" does no t exist I tried to connect it on my local with public network host and port but still got the same error. here is my db code : DATABASES = { 'default': { 'ENGINE': config('ENGINGE', default='django.db.backends.postgresql'), 'NAME': config('NAME', default='postgre'), 'USER': config('USER', default='postgre'), 'PASSWORD': config('PASSWORD', default='postgre'), 'HOST': config('HOST', default='postgre'), 'PORT': config('PORT', default='5432'), } } I'm passing the variables with .env. Also I tried to connect with dj-database-url like this : DATABASES = DATABASES['default'] = dj_database_url.config('DATABASE_URL') And in both cases I've got the same error. Does anyone got any idea what's wrong here? -
How to resolve error: collectstatic - Could not find backend 'storages.custom_azure.AzureStaticStorage'
I have a django app and I have installed the module: django-storages[azure] with the command: pipenv install django-storages[azure] And now I try to run the collectstatic command. But if I enter the command: python manage.py collectstatic I get this error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' So my pipfile looks: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" django-storages = {extras = ["azure"], version = "*"} [dev-packages] [requires] python_version = "3.10" settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "uploader", "storages" ] STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'uploader.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'storages.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "name" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' and I have a file custom.azure.py in the app uploader: from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = ''name' # Must be replaced by your <storage_account_key> account_key= 'key' azure_container = 'media' expiration_secs = None class AzureStaticStorage(AzureStorage): account_name = 'name' account_key = 'key' azure_container = 'static' expiration_secs = None Question: how to resolve the error: Could not find backend 'storages.custom_azure.AzureStaticStorage': No module named 'storages.custom_azure' -
How to add django-filter Rangefilter class?
I am try to add bootstrap class in to price range filter but i can't, import django_filters from panel.models import Product, Category,Size,TopNote, BaseNote, MidNote from django import forms class ProductFilter(django_filters.FilterSet): price = django_filters.RangeFilter( # widget = forms.TextInput(attrs={'class':'form-control'}) ) class Meta: model = Product fields =['name', 'category_id', 'price', 'top_notes', 'base_notes', 'category_id', 'size'] when I am add class using widget = forms.TextInput(attrs={'class':'form-control'}) range filter convert into 1 textbox i dont't know why ???/ -
How to properly aggregate Decimal values in a django app: 'decimal.Decimal' object has no attribute 'aggregate'
I'm in a django-tables2 Table, trying to compute the sum of a column (based on a MoneyField (django-money) in the model, see hereunder): import django_tables2 as table class PriceAmountCol(table.Column): # print(f"Total price is: {record.price.amount}") # print(f"Type of total price is: {type(record.price.amount)}") def render(self, value, bound_column, record): total_price = record.price.amount.aggregate( total=Sum("price") ) Class MyTable(table.Table): # Fields price = PriceAmountCol( verbose_name=_("Price [EUR]"), ) #... But this error is raised: File "/code/djapp/apps/myapp/tables.py", line 192, in render total_price = record.price.amount.aggregate( AttributeError: 'decimal.Decimal' object has no attribute 'aggregate' If not commented out, the two print instructions give: Total price is: 112.80 Type of total price is: <class 'decimal.Decimal'> How could I properly aggregate price values (Decimal) in my current table column? The field in the model is as follow: price = MoneyField( default=0.0, decimal_places=2, max_digits=12, default_currency="EUR", verbose_name=_("Price [EUR]"), ) Version info django 4.2.8 djmoney 3.4.1 django-tables2 2.7.0 python 3.10.6 Related information https://django-tables2.readthedocs.io/en/latest/pages/column-headers-and-footers.html#adding-column-footers Django-tables2 column total Django-tables2 footer sum of computed column values -
taking picture from the django admin panel to a website with zip
There will be a field in the Django admin panel, I will select zip from this field. there will be about 60 to 70 images in the zip file. I want to be able to display these images as slides on my website, but I haven't found a solution. I've tried multiple solutions, but none of them have been successful, so I can't share the codes. -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/login/login/
I stored the user registration details in the database, but when I attempt to log in with the entered data, it is not working; instead, it displays the following message. enter image description here here is urls.py urlpatterns=[ path('',views.index,name='index'), #path('counter',views.counter,name='counter'), path('register/',views.register,name='register'), path('login/',views.login,name='login.html'), path('logout/',views.logout,name='logout.html'), path('post/<str:pk>',views.post,name='post.html') #path('',views.display_records,name='table.html'), ] here is views.py def login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('/') else: messages.info(request,'Invalid User Login') return redirect('login') else: return render(request,'login.html') here is login.html <h1>Login Now</h1> <style> h3{ color: red; } </style> {% for message in messages %} <h3>{{message}}</h3> {% endfor %} <form action="login/" method='POST'> {% csrf_token %} <p>Username</p> <input type="text" name="username" placeholder="username"/> <p>Password</p> <input type="password" name="password" placeholder="password"/> <br> <br> <input type="submit"/> </form> After completion of registration.it is not redirecting to login page instead showing this. type here enter image description here -
Sending Django celery task to AWS GPU
I have a question related to designing the backend and frontend of an application that I'm currently working on. Although this might be more suited to AWS, I am asking here first because the community is great and very helpful. I have developed an application that works well locally, but now I want to move it to the cloud. I'm facing some issues while doing so. The application is standalone and requires GPU for the celery task. The task is initiated when the user uploads an image, and once it's done, everything is saved and the GPU machine is turned off. However, the application needs to run continuously without requiring the GPU. The user should be able to login and see the dashboard and upload job process data anytime. How can I achieve this? Should I separate my application into two parts? I have researched and found that many people suggest using AWS API, but before doing so, I need to know how to make a setup for it. Has anyone done this combination of Django and AWS before? If not, what are you using for your ML inferences in production? My appliction is working well in laptop. how to … -
Django OSError: [Errno 22] Invalid argument in \\.venv\\Lib\\site-packages\\admin_tools
I have cloned a Django project from Gitlab repository and I get this error when I try to run the server. OSError: [Errno 22] Invalid argument: 'C:\\Users\\irina\\project\\.venv\\Lib\\site-packages\\admin_tools\\theming\\templates\\admin:admin\\base.html' Dependencies are installed via poetry. I think the error is due to the encoding. How can this be fixed? I'm working on Windows 11. -
Django Celery not able to fetch data from particular DB schema
We are facing the issue fetching the data from particular schema's table which is available and the data fetching issue occurs intermediately after few hours of restart of supervisorctl where celery worker is defined. Below is the code mentioned: with schema_context("public"): try: client = Client.objects.get(subdomain=hostname) except ObjectDoesNotExist: client = Client.objects.using("paid").get(subdomain=hostname) Also i have set the connection to particular schema using schema_context function. We have rabbitmq as middleware and we have 3 different queues set and this problem occurs in all queues. we are using libraries celery==4.4.7 django-celery==3.3.0 -
Why can't we view Google Drive public file for longer without getting 403 Forbidden Error?
I am working on a Django project where I allow user to upload their images on google drive with public access and then I display all the uploaded images user-wise. Everything done, I can create folder, and then uploading file in it and getting the file-id. But on viewing that image, I have stucked badly. I have used so many ways not to get a 403 Forbidden Error but still no success! https://drive.google.com/file/d/{file-id}/preview https://drive.google.com/uc?id={file-id}&export=download https://drive.google.com/uc?export=view&id={file-id} File (which is just an image) I can view only few times but then I starts getting this annoying 403 forbidden error. I am really frustrated with this error, please help. -
how to solve 'Error Dict' object is not callable error [closed]
views.py from django.contrib import messages from django.shortcuts import render, redirect from clgapp.forms import StudentForm def student_form(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() messages.success(request, "order confirmed") return render(request,'student_form.html',{'form': form}) else: form.errors() else: form = StudentForm() return render(request, 'student_form.html', {'form': form})` -
django.server logs are not shown in CloudWatch - Using Zappa
My django application is running on AWS Lambda with zappa. I recently added the following to configure logs. LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, "filter_user_id": {"()": "<path_to>.UserIdFilter"}, }, "formatters": { "django.server": { "format": "[%(asctime)s] %(message)s user_id:%(user_id)s ", } }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", }, "django.server": { "handlers": ["django.server"], "filters": ["filter_user_id"], "level": "INFO", "propagate": False, }, }, } This is working well when I run this on docker / local server. But when I deployed this to AWS Lambda it is not showing the corresponding logs in the Cloudwatch. Could anyone help? Thanks in advance. -
Creating and Sending PDF file directly to printer without print preview in react and django?
here is any chance to Creat Pdf file and Send PDF file directly to printer without open print preview?? currently! i am able to create pdf and save it in my local.And im also able to print once pdf file is created by opening pdf. Here what im looking for: Generate pdf first and save it to my local and it should be print to my printer once pdf file is created without opening print preview window. what i tried: currently i am able to generate pdf and print them as well by open pdf file form my local. here is my sample code for pdf functionality: model.py: class OrderTransactionPDF(models.Model): pdf_file = models.FileField(blank=True, null=True, validators=[FileExtensionValidator( allowed_extensions=['pdf'])]) transaction_time = models.DateTimeField(default=datetime.datetime.utcnow()) view.py: @csrf_exempt def search_pdf(request): if request.method == "GET": from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') pdf_url_list = [] from_date = datetime.strptime(from_date, '%Y-%m-%d') to_date = datetime.strptime(to_date, '%Y-%m-%d') from_date = datetime.combine(from_date.date(), time(0, 0, 0, tzinfo=pytz.timezone('UTC'))) to_date = datetime.combine(to_date.date(), time(23, 59, 59, tzinfo=pytz.timezone('UTC'))) order_transaction_pdfs = OrderTransactionPDF.objects.filter( transaction_time__range=[from_date, to_date] ).order_by('-transaction_time') for pdf in order_transaction_pdfs: pdf_url_list.append({ 'pdf_url': pdf.pdf_file.url, 'transaction_time': pdf.transaction_time }) return JsonResponse({'pdf_url_list': pdf_url_list}, safe=False) urls.py: path('generate_pdf', generate_pdf), js code: const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', … -
Is there a way to add formset in django-admin without using inline?
I have a model called Employee which is defined as follows: class Employee(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField("Name", max_length=255) address = models.CharField("Address", max_length=255) department = models.ForeignKey(Department, on_delete=models.SET_NULL) team = models.ForeignKey(Team, on_delete=models.SET_NULL) position = models.ForeignKey(Position, on_delete=models.SET_NULL) Is there a way to add multiple name and address of employee for the same department, team and position in django-admin form? I want something like formset including fields name and address for the model Employee where you can enter the department, team and postion and just add the formsets multiple times like how you would do for inlines. I have not tried anything as of yet. -
Duplicate entries in admin view due to M2M field
class User(AbstractBaseUser): organizations = models.ManyToManyField(Organization) facilities = models.ManyToManyField(Facility) class Organization(models.Model): ..fields here class Facility(models.Model): ..fields here Whenever I enter multiple entries for organization the user value is duplicated that many times in the admin view list, but not for facility. -
Django forms not rendering CharFields
In my Django form, only CharFields are exclusively not showing up. Other fields work just fine (e.g. the EmailField and a TurnstileField using django-turnstile). I cannot figure out why. I followed the Django docs and tried to build a form. Code is as follows: auth.html {% block body %} <form action="https://artimaths.com/auth/{{ action }}/" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py from django.core.exceptions import ValidationError from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import send_mail from django.template import loader from .models import Member from .forms import SignupForm, LoginForm from modules import context import hashlib import re def signage(request, action): t = loader.get_template("auth.html") if action != "register" and action != "login" and action != "logout": return HttpResponse(STATUS_DICT[str(400)] + str(400)) if action == "register": req_context["form"] = SignupForm req_context["form_class"] = SignupForm elif action == "login": req_context["form"] = LoginForm req_context["form_class"] = LoginForm if req_context["status"] is not 200: return HttpResponse(STATUS_DICT[str(req_context["status"]) + req_context["status"]]) return HttpResponse(t.render(req_context, request)) forms.py from django import forms from turnstile.fields import TurnstileField from .models import Member class SignupForm(forms.Form): username = forms.CharField(label="Username"), password = forms.CharField(label="Password"), email = forms.EmailField(label="Email") terms = forms.BooleanField(label="I agree with the Terms of Service and Privacy Policy of Artimaths") captcha = TurnstileField(theme="dark", size="compact") class Meta: … -
How to make multiple post requests with one button handler in React?
I am trying to generated PDF for my application.Pdf functionality is working well.I have two PDF functionality for post request which is seperate right now.Those two PDF post functionality is setting up two indivisual button handler. Ex1: const handleViewOrder = async () => { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); } Ex2: const handleProductSellsPdf = async () => { const response = await fetch('/**generate_item_pdf**', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); what im trying now that,combine those Ex1 and Ex2 in one button handler and generate pdf once i click button. backend code is working fine. problem is that i dont know how to do it in in react/java script. any suggestion please this is my code of pdf generate functionality for diffrent button handler in react : const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); const responseData = await response.json(); const pdfURL = responseData.pdf_url; localStorage.setItem("pdf_url",pdfURL) window.open(pdfURL, '_blank'); if (!response.ok) { throw new Error('Network response was not ok'); } } catch (error) { console.error('Error fetching data:', error); } }; const handleProductSellsPdf = async () => … -
How to set a (Django) celery beat cron schedule from string value
I am using Django with celery beat. I would like to configure the cron schedule via env var (string value of the cron). We are currently setting the cron schedule like this, using celery.schedules.crontab: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": crontab(minute=0, hour='1,3,5,13,15,17,19,21,23'), }, } I would like to configure the schedule by passing a crontab in string format, like this: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": '0 15 10 ? * *', }, } However, I cannot find any documentation for how I can do this. The naive attempt above does not work. I could parse the cron string into minute/hour/day etc values, and then pass them into crontab with the relevant kwargs, but that feels quite messy. It seems there should be an elegant way to do this. -
Django Form inital values don't work on render
I have a model `Transaction' and ModelForm to create one : class Transaction(models.Model): """ Invoice model. Represents a basic income/outcome transaction. """ title = models.CharField(max_length=32, verbose_name="Title") category = models.ForeignKey(Category, related_name="transactions", on_delete=models.CASCADE, null=True, blank=True) operation = models.CharField(max_length=8, choices=OPERATION_TYPE, verbose_name="operation") value = models.DecimalField(max_digits=14, decimal_places=2, verbose_name="value") currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, verbose_name="currency") comment = models.CharField(max_length=255, null=True, blank=True) date_created = models.DateField(auto_now_add=True, blank=True, null=True) class Meta: verbose_name_plural = "Transactions" ordering = ["-date_created"] class NewInvoiceForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.objects.all()) class Meta: model = Transaction fields = ("title", "category", "operation", "value", "currency") help_texts = { "operation": _("Money spent/received. For expenses use a negative value.") } I have a Preference model linked with each user to store settings : class Config(models.Model): """ Represents user's preferences. """ user = models.OneToOneField(CustomUser, related_name="config", on_delete=models.CASCADE) currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, default=DEFAULT_SETTINGS["currency"]) language = models.CharField(max_length=56, choices=LANGUAGE_CHOICE, default=DEFAULT_SETTINGS["language"]) class Meta: verbose_name = "config" verbose_name_plural = "configs" I'm trying to get user's currency from Config model as initial value for Transaction creation form. But initial value never renders. My view : def create_transaction_view(request): if request.method == "POST": form = NewInvoiceForm( request.POST, instance=request.user ) if form.is_valid(): new_invoice = Transaction(**form.cleaned_data) # retrieving user's currency preference for further converting if income is different from base currency user_currency = request.user.config.currency # performing … -
Discretization of Multiple Time Series [closed]
I'm working on discretizing multiple time series for a project. Here's what I've done so far: I concatenated the train signals like this: [1,2,3,5] and [7,3,6,7] into [1,2,3,5,7,3,6,7]. Then, I trained a K-means ML model with the single, combined signal. Finally, I clustered all the signals with the trained model. I'm not sure if this is the right approach. I chose to concatenate the signals because the k-mean (from scikit-learn) allows inserting only a single array, so I didn't know how to feed it with multiple time series. Has anyone done something similar, or does anyone have suggestions for a better discretization method? -
Computing AUC and ROC curve with micro and macro - average on multi-class data in Scikit-Learn
I am computing and plotting AUC and ROC curves for multi-class data for the output of 3 different classifier. I want to see the difference in using micro and macro average on plotting ROC curves in a multi-class setting. I am following the code provided on scikit-lean in OvR (one versus rest) scenario. However, the macro-average ROC curves do not look right, sice some are not starting from (0,0) position. Below, graph shows the performance of Random Forest trained on 3 different augmented datasets macro-average ROC (NOT right) Whereas, the same classifier with ROC plotted using micro-average do not show the same problem. micro-average ROC curve (starts from Zero) I Have also other examples from other datasets using different classifiers (NB and DT) as the following one: macro-average ROC curve (NOT right) For plotting the curves with micro and macro average I used the following code, where: model_proba = contains aggregated predicted probabilities from a 10-CV classes = sorted(list(np.unique(y_test))) print('Sorted:',classes) n_classes = len(np.unique(y_test)) y_test_binarize = label_binarize(y_test, classes=classes) print('Binarized:',y_test_binarize) #y_test_binarize = label_binarize(y_test, classes=np.arange(classes)) scores = {} for model_name, model_proba in d_probabilities.items(): #iterating over 3 probabilities of 3 models y_pred = model_proba scores[model_name] = model_proba fpr ,tpr ,roc_auc ,thresholds = dict(), dict(), … -
Django - Moving some logic from viewsets to a model or model method in viewsets
I have a small educational project of a social network. There's a Recipes and ShoppingCart models. Besides other functionalities, RecipeViewSet allows users to download a file with the ingredients of recipes previously added to the shoppingcart. This part of the RecipeViewSet looks like this: @action( detail=False, methods=['GET'], permission_classes=[IsAuthenticated] ) def download_shopping_cart(self, request): user = self.request.user if not user.shoppingcarts.exists(): raise ValidationError('The shopping cart is empty.') return FileResponse( get_shopping_list( user_cart=user.shoppingcarts.all() ), as_attachment=True, filename='shopping list ' + dt.now().strftime('%d-%m-%Y') + '.txt', ) The function that forms the list of ingredients for downloading looks like this: def get_shopping_list(user_cart): ingredient_name = 'recipe__recipe_ingredients__ingredient__name' ingredient_unit = ( 'recipe__recipe_ingredients__ingredient__measurement_unit' ) ingredient_amount = 'recipe__recipe_ingredients__amount' amount_sum = 'recipe__recipe_ingredients__amount__sum' ingredients = user_cart.select_related('recipe').values( ingredient_name, ingredient_unit ).annotate(Sum(ingredient_amount)).order_by(ingredient_name) recipes = [f'"{recipe.recipe.name}"' for recipe in user_cart] ingredients_list = [ (f'{number}. {ingredient[ingredient_name].capitalize()} ' f'({ingredient[ingredient_unit]}) - ' f'{ingredient[amount_sum]}') for number, ingredient in enumerate(ingredients, 1) ] return '\n'.join(['Recipes:', *recipes, 'To buy:', *ingredients_list]) I want to move some of the logic (the first half of the function) that is not directly related to forming the text out of the get_shopping_list function and transfer it to a model. Therefore, my questions are, which model is better to move it to, ShoppingCart or Recipe and why? And how can this be implemented? -
Adding restriction on who can access form submission information on Wagtail CMS
I have a form page in my web application that is using Django and Wagtail. Is there a way to have a way to restrict or manage which Wagtail users can access the form submission data? Thank you So far I can't find anything that will help me answer my question rather than adding permission in the code base -
Django UserCreationForm Meta fields
I created customized usercreationform class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", ) The simple question is if it works without "password1", "password2" in fields? class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", "password1", "password2", ) if both work, what is the difference between two?