Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Call a view function into another view function
my todo list has two different functions add_task & view_task I don't want to create one single function I want that view task will call add task # Add Task Page def add_task(request): submitted = False if request.method == "POST": form = TodoForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/add_task?submitted=True') else: form = TodoForm if 'submitted' in request.GET: submitted = True return render(request, "core/add_task.html", {'form':form, 'submitted': submitted}) # Task List Page def view_task(request): task_list = Todo.objects.all() #This is the part of view_task function where I have been trying to call add_task function # If you see a few lines below, I am calling already form, return render(request, "core/view_task.html", { 'task_list': task_list, #'form':form, }) -
Define multiple templates for a block
I am moving a site over to wagtail and decided to use the codered extensions. The library comes with a image-gallery content-block. I want to use this but define a few templates that you can choose from in the admin ui. Normally you define a template in the meta section but I noticed there is a dropdown in the admin ui for template. How do I add a template to that dropdown? Link to the content block I want to change I am interested in adding a html template and not inheriting from the content-block to change behaviour. (Unless inheriting is the only way to add a template to the dropdown) -
django NoReverseMatch not a valid view function or pattern name
I am having problems with an old project that was running on a deprecated django version. I updated django to 4.1.5 and made a few edits to the urls.py files that they were using python from django.conf.urls. I changed this to use re_path but now am running into an issue I have not been able to resolve. The server starts up okay however when I try to access any of the pages, I get the following Error: Error: NoReverseMatch at /control/ Reverse for 'control.views.set_notes' not found. 'control.views.set_notes' is not a valid view function or pattern name. Looking at the Trace here is where it looks like the error is happening from url line below: $.ajax({ url: "{% url 'control.views.set_notes' %}", type: "POST", data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'notes' : notes }, error: function (error) { alert("error setting notes to " + notes); }, success: function (response) { } I have my root urls.py setup as follows: from django.urls import include, re_path urlpatterns = ( re_path(r'^control/', include('control.urls')), re_path(r'^profiles/', include('profiles.urls')), re_path(r'^roasts/', include('roasts.urls')), ) My other control.urls.py setup is as follows: from django.urls import re_path import control.views urlpatterns = ( re_path(r'^$', control.views.index), re_path(r'^get_state/$', control.views.get_state), re_path(r'^cancel_profile/$',control.views.cancel_profile), re_path(r'^get_profile/$', control.views.get_profile), re_path(r'^set_temp/$', control.views.set_temp), re_path(r'^set_notes/$', control.views.set_notes), re_path(r'^add_marker/$', … -
The Payment could not be created because the data didn't validate
I get the following error: The Payment could not be created because the data didn't validate. #view def home(request): customer = Customer.objects.all().filter(user=request.user) payments = Payment.objects.all().filter(user=request.user) if request.method == "POST": form = PaymentForm(request.POST) if form.is_valid: fs = form.save(commit=False) fs.user = request.user fs.save() messages.add_message(request, messages.INFO, 'ثبت با موفقیت انجام شد') else: messages.add_message(request, messages.WARNING, 'خطا در ثبت') else: form = PaymentForm() context = { 'payments': payments, 'customer': customer, 'form': form, } return render(request, 'payment/index.html', context) #model class Payment(models.Model): number = models.IntegerField(verbose_name='شماره چک', unique=True) price = models.IntegerField(verbose_name='مبلغ چک') date = jDateField() pardakht = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='دریافت از') bank = models.IntegerField(choices=bank, verbose_name='بانک') description = models.TextField(verbose_name='توضیحات', null=True) status = models.BooleanField(default='0') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f'{self.number}' #forms from jalali_date.fields import JalaliDateField, SplitJalaliDateTimeField from jalali_date.widgets import AdminJalaliDateWidget, AdminSplitJalaliDateTime from .models import Payment class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ['number', 'price', 'date', 'pardakht', 'bank', 'description'] number = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='شماره چک') price = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='مبلغ چک') pardakht = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), label='مشتری') bank = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), choices=bank, label='بانک') description = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), label='توضیحات') def __init__(self, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.fields['date'] = JalaliDateField(label=('تاریخ چک'), widget=AdminJalaliDateWidget) index.html <h4 class="text-center alert alert-info"> ثبت چک جدید </h4> <form method="post" action="#"> {% … -
Python Openpyxl library cannot deal with automatic row height
I'm currently using Openpyxl in a Django project to create an excel report. I'm starting from a blank excel model in which column C has text wrap enabled. Infact when I open the model and populate manually a cell I correctly get this But when I run this trial code wb = openpyxl.load_workbook(fileExcel) sh = wb["Rapportini"] sh["C3"]="very very very very very very very very very very long row" wb.save(fileExcel) this is the result I know openpyxl (strangely) cannot set row autoheight. I also tried to set wrap_text = True in the cell, but no way... any ideas ? -
Django error: Cannot assign "''": "" must be a "" instance
I am getting this error when adding a pair. Cannot assign "'1'": "Pair.exchange" must be a "Exchange" instance. models.py: class Exchange(models.Model): name = models.CharField(max_length=25) def __str__(self) -> str: return f'{self.name}' class Pair(models.Model): symbol = models.CharField(max_length=20) ask = models.FloatField() bid = models.FloatField() exchange = models.ForeignKey(Exchange, on_delete=models.PROTECT) created = models.DateTimeField() def __str__(self) -> str: return f'ID: {self.id} Symbol: {self.symbol} Ask: {self.ask} Bid: {self.bid} Exchange: {self.exchange}' views.py: def show_pair(request): pairs = Pair.objects.all() br = [str(pair) + '<br>' for pair in pairs] return HttpResponse(br) def add_pair(request, symbol, ask, bid, exchange): pair = Pair.objects.create(symbol=symbol, ask=ask, bid=bid, exchange=exchange) return HttpResponsePermanentRedirect('/pair/') urls.py: path('pair/add/<symbol>/<ask>/<bid>/<exchange>/', views.add_pair) I'm trying to add pairs via a link, but I get this error, what could be the problem? -
How to limit the number of fetched children in django-treenode
I have a comment Model, where a comment can be a root item or under another comment. I'm using REST API to get the full tree. Is it possible to limit its depth, so for example It will stop after 3 nodes from each root comment. I want to add a "more" feature instead of show the whole tree at once. ` class CommentSerializer(serializers.ModelSerializer): leaf_nodes = serializers.SerializerMethodField() class Meta: model = Comment fields = [ 'id', 'body', "leaf_nodes" ] def get_leaf_nodes(self, obj): return CommentSerializer(obj.get_children(), many=True).data ` I tried looking at the documentation on GitHub but didn't find a solution. -
I have problem using google OAuth2 with django: GSI_LOGGER]: The given origin is not allowed for the given client ID
I have an issue with @react-oauth/google npm package. When I using react app on port 3000 and backend django on port 8000 every thing work's, but after I build react app and using port 8000, I try to log in via google, I get that Erros: Failed to load resource: the server responded with a status of 400 m=credential_button_library:45 [GSI_LOGGER]: The given origin is not allowed for the given client ID. I did double check on 'Authorised JavaScript origins' and 'Authorised redirect URIs' (image attached) but the giving origin are allowed, so whats can be the problem? I read about similar problems here on the site and also tried CHAT GPT but nothing helped. This is my configurations: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://localhost:3000", "http://127.0.0.1:3000", "http://127.0.0.1:8000" ] class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = ['http://localhost:8000', 'http://localhost:3000', 'http://127.0.0.1:8000', 'http://localhost:8000/accounts/google/login/callback/'] # ! client_class = OAuth2Client -
Installed Django using pipenv on Mac (Zsh). Command not found: django..?
Installed django inside a file in Desktop using pipenv., it created pipfile and pipfile.lock without any issues later when trying to start project using 'djang0 -admin startproject' it outputs Zsh: command not found: django. Tried python3 -m django startproject forum and it worked fine., untill later i tried creating superuser using the same method and it outputs the same result. why it didn't work in the first and worked fine with the second command.? Is there any resource you can point where i can understand the shells and paths better..? What's the solution for this..? Sorry, i am new to Coding and these issues taking up a lot of my productive time..Trying to understand the issue better and prevent this from happening in future rather than fixing it temporarily. Thanks in advance I have tried installing the latest version of python3 Uninstalling and installing pipenv, django using pip3 pipenv graph shows django 4.10 was installed I couldn't locate the bin folder or define path as stated on some blogs -
Rollup.js Typescript React Npm Package Error: Cannot find module './tslib.es6-eaa548e7.js'
I have created a npm package using typescript react and rollup.js. I have link it to the project using yalc (similar to npm link) and getting the following error: Server Error Error: Cannot find module './tslib.es6-eaa548e7.js' Require stack: - /Users/paul/Projects/test-project/.next/server/pages/index.js Package structure: - dist/ - ContactForm7.d.ts - ContactForm7.js - index.d.ts - tslib.es6-eaa548e7.js - Wordpress.d.ts - Wordpress.js - src/ - package.json - rollups.config.js - tsconfig.json pages/index.tsx is importing the package with: import { getPage } from 'package-wordpress/dist/Wordpress'; This is the starting contents of dist/Wordpress.js which looks to be initiating the error: 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var tslib_es6 = require('./tslib.es6-eaa548e7.js'); // this is where error occurs var axios = require('axios'); var cacheData = require('memory-cache'); rollup.config.js: import typescript from '@rollup/plugin-typescript'; import replace from 'rollup-plugin-replace'; import commonjs from '@rollup/plugin-commonjs'; export default { input: { Wordpress: 'src/Wordpress.tsx', ContactForm7: 'src/ContactForm7.tsx' }, output: { dir: 'dist', format: 'cjs', exports: 'named', }, plugins: [ typescript({ tsconfig: 'tsconfig.json' }), replace({ 'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE) }), commonjs() ], external: ['react'], }; tsconfig.json: { "compilerOptions": { "target": "es5", "jsx": "react", "module": "esnext", "lib": ["esnext"], "strict": true, "esModuleInterop": true, "declaration": true, "outDir": "dist", "importHelpers": true }, "include": [ "src", "src/index.tsx" ] } -
How to integrate Cardpointe payment gateway in django
How to integrate Cardpointe payment gateway in Django. I got stuck with it. I dont know how to do it and I am not getting any example on google. -
how do python async behaviour behaves with api requests?
I've been into Python/Django and things are going good but I'm very curious about how django handle any asynchronous tasks for example if there is a database query that took 10 seconds to execute and another request arrives on the server during these 10 seconds? def my_api(id): do_somthing() user = User.objects.get(id=id) # took 10 sec to execute do_somthing_with_user() I've used the queryset method that fetch something from database and let's say it took 10 seconds to complete. what happens when another request arrives on the django server, how django respond to it? will the request be pending until the first query responds or will it be handled in a parallel way? what is the deep concept for it? How Python Handles these type things under the hood? -
Cannot import name 'DEFAULT_STORAGE_ALIAS' from django.conf
I've setup a project that uses memcache and got it working properly but suddenly it stopped working and I just can't figure out why. According to the traceback is something that has to do with Django itself but that would be odd. So I'm asking you guys for help to help me figure out what's going on with this error. I haven't seen anything similar. Any clue? Here's the traceback: Traceback (most recent call last): File "/Users/rodrigodelaporte/Documents/code/harlan/manage.py", line 22, in <module> main() File "/Users/rodrigodelaporte/Documents/code/harlan/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 257, in fetch_command klass = load_command_class(app_name, subcommand) File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 10, in <module> from django.core.servers.basehttp import ( File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/servers/basehttp.py", line 17, in <module> from django.core.handlers.wsgi import LimitedStream File "/Users/rodrigodelaporte/Documents/code/harlan/venv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line … -
I get error messages trying to use my python
My python was once working, but recently stoped. Shows error on every syntax. Eg: 'python' is not recognized as an internal or external command, operable program or batch file. Please how do I fix this. -
how to calculate daily average in dango serilizer
my model : class Record(models.Model): type = models.CharField(max_length=9, choices=RECORD_CHOICES) user = models.ForeignKey(User,on_delete=models.CASCADE) record = models.DecimalField(decimal_places=4,max_digits=8) date_time = models.DateTimeField() my serializer: class RecordSerializer_1(serializers.ModelSerializer): class Meta: model = Record fields = ['type','record','date_time'] my view : records = Record.objects.filter(user=user,type="HeartRate") serializer = RecordSerializer_1(records, many=True) I have more than one record at same day , I need to calculate average and return only one record per day -
What is the best pathway for building a django-rest api for a project?
I am about to begin a major project using Django-rest framework. I know that there is no "Correct" coding practice for anything, but I would still like to know what should be the path to follow for an easy and quick development experience. Should I be done with the Custom user models, user registration, and authentication first and then add the database model for other stuff? Or should I prefer another course of action? Thank you in advance. -
Write Django QuerySet that remove all whitespace from specific Keys within a JSONFIELD
I would like to write a Django QuerySet that removes whitespaces from Specific Keys within a JsonField. I have a django model with a JsonField type. MyModel(Model): a: str, properties: JSONField this is an example of database lines : a, properties “first”, {“key_1”: “ key1value”, “key_2”:”key2value”, “key_3”: “ key_3”} “second”, {“key_2”: “ key2 “} and my queryset should update my data removing whitespace of specific key. So for Key_1 and Key_2 it will give me: “first”, {“key_1”: “key1value”, “key_2”:”key2value”, “key_3”: “ key_3”} “second”, {“key_2”: “key2“} I tried using MyModel.objects.update(properties_key_1=F("propertieskey_1”).strip().lower(), propertieskey_2=F("properties_key_2”).strip().lower()) but I get an error: ==> result AttributeError: 'F' object has no attribute 'strip I tried: MyModel.objects.update(properties__key_1=RawSQL("properties->key_1->value", []).strip()) ==> result 'RawSQL' object has no attribute 'strip' I tried: MyModel.objects.update(properties__key_1=RawSQL("TRIM(properties->asset_class->value)”) ==> SyntaxError: positional argument follows keyword argument Any idea please ? thx you -
customized dropdown value based on foreign key in django admin
My Models class ServicesMenu(models.Model): category = models.CharField(max_length=200) class Varient(models.Model): category = models.ForeignKey(ServicesMenu, on_delete=models.CASCADE) varient_Name = models.CharField(max_length=200) class VarientSubField(models.Model): select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE) name = models.CharField(max_length=200) so the problem is in VariantSubField, its display something like this. here some value are similar i cant change them but i need is to display "category" from ServicesMenu with these VariantSubField dropdown fields. -
Composite permissions DRF
I have a view class inherited from RetrieveUpdateDestroyAPIView. I need to have different permission classes for different method so I am over writing get_permissions method but I'm getting error TypeError: unsupported operand type(s) for |: 'IsSuperAdmin' and 'IsOwner. views.py class UserView(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer http_method_names = ['patch', 'get', 'delete'] def get_permissions(self): if self.request.method == 'GET': return [IsAuthenticated(), IsSuperAdmin()|IsOwner()|IsAdmin(), ] elif self.request.method == 'DELETE': return [IsAuthenticated(), IsSuperAdmin()|IsAdmin()] else: return [IsAuthenticated(), IsSuperAdmin()|IsAdmin()|IsOwner(), ] permissions.py class IsSuperAdmin(BasePermission): message = "You must be super admin to perform requested operation" def has_permission(self, request, view): if request.user.role == "super_admin": return True return False class IsAdmin(BasePermission): message = "You must be admin to perform requested operation" def has_permission(self, request, view): if request.user.role == "admin": return True return False class IsOwner(BasePermission): message = "You must be owner of resource to perform requested operaton" def has_object_permission(self, request, view, obj): if obj.id == request.user.id: return True return False -
400 Bad Request Django/React
I have built a server with Django and I am receiving a 400 Bad Request within Postman when I check the POST method. However, it is displaying the JSON data within the Postman as well. Originally, I thought it was a frontend issue, because my console log was stating AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} As I stated before, the error is showing in Postman so I'm assuming it's actually a server issue. Im real "finicky" when it comes to file colors, and if it is any color than the default color, I feel like there is errors within the file. Could these orange/beige files contain the problem? If I click on one of those files Im met with: The file is not displayed in the editor because it is either binary or uses an unsupported text encoding. Because I am new to django, I don't want to do something that's going to create an even bigger problem than what I already have. Below will be my settings.py """ Django settings for django_rest_api project. Generated by 'django-admin startproject' using Django 4.1.4. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ … -
Django model access from custom file
Can I receive access to Model from some custom file. For example I create folder in my project with name Bot. Create some custom_file.py, in current file call model from other app. For example: from trading.models import Values Then I get an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Also try solution like this in my custom_file.py: import os import django os.environ["DJANGO_SETTINGS_MODULE"] = 'trading.settings' django.setup() But still doesn't work. -
How to save a raster in RasterField after save in GeoDjango?
I am building an app using Django with PostGIS backend. Thus, GeoDjango. I have a model with FileField, and RasterField [1]. I want to save a raster object to RasterField after supplying the FileField. I am trying to achieve this using a post_save signal. class Layer(models.Model): name = models.CharField(max_length=50, blank=True) file = models.FileField( upload_to='layers', null=True, max_length=500) raster_file = RasterField( null=True, blank=True, ) After some research [2], you have to use GDALRaster [3] to make the raster as an object. In my signals: from django.contrib.gis.gdal import GDALRaster from data_management.models import Layer @receiver(post_save, sender=Layer) def create_raster(sender, instance, **kwargs): instance.raster_file = GDALRaster(instance.file.path) instance.save() When I am uploading the file in my admin, the raster_file is not filled and not created. How do I save the raster, which is uploaded through the file field, in my raster_file field? -
How do I filter django models based on product fields?
I am trying to run a filter command, using related fields; and am unsure how to go about it: class Listing(models.Model): name = models.CharField(max_length=150) slug = models.SlugField() description = models.TextField() catchphrase = models.TextField(null=True, blank=True) picture_0 = models.ImageField(upload_to = "mainimages") picture_1 = models.ImageField(null=True, blank=True, upload_to = "./product/static/product/imgs") picture_2 = models.ImageField(null=True, blank=True, upload_to = "./product/static/product/imgs") short_term_price = models.IntegerField(default=0) long_term_price = models.IntegerField(default=0) tax = models.IntegerField(default=0) tag = models.ForeignKey('Tag', on_delete=models.PROTECT) def __str__(self): return self.name class Order(models.Model): listing = models.ForeignKey(Listing, on_delete=models.PROTECT) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) lease_date = models.DateField() clear_date = models.DateField() price = models.IntegerField(default=0) #cents def __str__(self): return self.listing.name def get_display_price(self): return "{0:.2f}".format(self.price / 100) The general idea is that the user provides a start date and an end date and Django only returns the listings that aren't already in an order in that timeframe. I am unsure how to go about the view function: def search_products(request, start_date, end_date): listing = Listing.objects.select_related('order').all() -
How to send Django AllAuth email verification as alias
I just setup a Google workspace. One of the accounts has an alias: info@domain.com. I’d like to send all emails from that alias. I know I have to authenticate with the actual account email address through EMAIL_HOST_USER (which I have done), but how do I force Django AllAuth to send emails from the alias email? Is this something that can be achieved by overriding AllAuth views and using send_mail()? Any help would be appreciated. -
How can I remove the navbar in these three parts in my python project?
I am currently trying to build a website with python django. At the moment I am making a dashboard for the website. On the dashboard I want to show three tiles for different menu options. Dashboard Ignore the content this is just a placeholder for now. As you can see in every part of the dashboard the navbar is included. My code for the dashboard looks like following: {% extends 'base.html' %} {% block titel %}Dashboard{% endblock %} {% block content%} <div class="container-fluid"> <h1 class="fw-bold">Dashboard</h1> <div class="row"> <div class="col-sm-4"> <div class="card"> <div class="card-body" > {% include 'todolist/index.html' %} </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> {% include 'todolist/index.html' %} </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> {% include 'todolist/index.html' %} </div> </div> </div> </div> </div> {% endblock %} The base for all the sites are in a extra file called base.html. In this file is also the navbar defined. How can I prevent that the navbar will be in every part of the dashboard while still using the extends part?