Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django get_or_create creates object but its not saved in database
So i have a transfer function witch deletes one footballer from database and replaces him with another.I'm also trying to create new instance of transfer object that contains basic data about the transfers. The problem is that the get_or_create fuction returns True for created and even prints out an transfer object with increased pk (i.e. Transfer object(48), but its not appearing in the database. models.py class Transfer(models.Model): player_out = models.ForeignKey(MyFootballer, on_delete=models.CASCADE, null=True, blank=True) player_in = models.ForeignKey(Footballer, on_delete=models.CASCADE, null=True, blank=True) matchday = models.ForeignKey(Matchday, on_delete=models.CASCADE, null=True, blank=True) owner = models.IntegerField (null=True) views.py @login_required def makeTransfer(request): player_in_ID = request.POST.get('playerinID') player_out_ID = request.POST.get('playeroutID') player_out = MyFootballer.objects.get(id = player_out_ID) matchday = player_out.matchday.id player_in = Footballer.objects.get(id = player_in_ID) squad = MyFootballer.objects.filter(owner = request.user, matchday = matchday) budget = 150000000 - calculate_squad_value(squad) new_budget = budget + player_out.footballer.price - player_in.price transfers = Transfer.objects.filter(owner = request.user.id, matchday_id = matchday) transfers_left = 3 - transfers.count() if transfers_left >= 1: if new_budget <= 150000000: if player_out.footballer.position == player_in.position: new_transfer, created = Transfer.objects.get_or_create(player_out_id =player_out_ID, player_in_id = player_in_ID, matchday_id = matchday, owner = request.user.id) print ("here",new_transfer) MyFootballer.objects.filter(id = player_out.id).delete() MyFootballer.objects.create(footballer_id = player_in.id, matchday_id = matchday, owner = request.user, squad_role = player_out.squad_role) return JsonResponse({'status':created}) else: return JsonResponse({'status':'err_pos'}) return JsonResponse({'status':'err_bud'}) return JsonResponse({"status":'err_trans'}) What's weird is … -
How to make sequential signup pages with Django allauth?
I currently have a single page signup form implemented with allauth from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(_('Professional email address'), unique=True) username = models.CharField(_("User Name"), blank=False, max_length=255, unique=True) first_name = models.CharField(_("First Name"), null=True, max_length=255, default='') last_name = models.CharField(_("Last Name"), null=True, max_length=255, default='') country = CountryField(_("Country of Practice"), blank_label='(Country of Practice)', blank = False, default='GB') terms = models.BooleanField(verbose_name=_('I have read and agree to the terms and conditions'), default=False) def get_absolute_url(self): return reverse( "users:detail", kwargs={"username": self.username} ) objects = UserManager() And this is the forms.py class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) username = CharField(label='User Name', widget=TextInput(attrs={'placeholder': 'User Name'})) class Meta(forms.UserCreationForm.Meta): model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms'] field_order = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms'] def clean_terms(self): is_filled = self.cleaned_data['terms'] if not is_filled: raise forms.ValidationError('This field is required') return is_filled def clean_username(self): username = self.cleaned_data["username"] if self.instance.username == username: return username try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) I would like however for the first sign up page to have a ‘next’ button at the bottom and then there would be a second page where the user input separate details (the data input here … -
How can i calculate bmi , protien , carb , calorie , body fat in django
enter image description here I want to calculate all of them return results below submit button -
KeyError: REQUEST_METHOD with Django + uWSGI + nginx + docker
I've built a django REST-API and I want to deploy it on my server. Everything works fine in local dev environment. But on my server I have an error with nginx doesn't pass uwsgi_params correctly (I think). The error It seems to me that my configs work fine, since when I access my domain name, the logs appear on the server. However, the error seems to me that nginx doesn't pass the reqeust_method to wsgi in django. I did found another post here which had the same error, however, I double checked the uwsgi_params file and it's not empty. So I have no clue. simuzones_server_web | Traceback (most recent call last): simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ simuzones_server_web | request = self.request_class(environ) simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 78, in __init__ simuzones_server_web | self.method = environ["REQUEST_METHOD"].upper() simuzones_server_web | KeyError: 'REQUEST_METHOD' simuzones_server_web | [pid: 11|app: 0|req: 1/1] () {48 vars in 977 bytes} [Sun Jan 22 13:28:53 2023] => generated 0 bytes in 5 msecs ( 500) 0 headers in 0 bytes (0 switches on core 0) simuzones_server_web | Traceback (most recent call last): simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ simuzones_server_web | request = self.request_class(environ) simuzones_server_web | File … -
How to fix csrf token problem after deployment on railway of django project
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https//:webiste does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. I added csrf_token_origin but it didn't worked for me and currently i am using python 3.11.0 -
How do I reference a path (URL) in Django? But this path is not in the base app, but in another app
In the base app, which I call it "mywebsite" (the one that contains the settings of the django project), has the urls.py file. But I do not want to reference this file, I want to reference a urls.py in another app, which I call it "account". For the base file, I would reference as {% url'login' %}, for example. How do I reference to the other one? Maybe {% account.url 'login' %}? I tried {% account.url 'login' %} and {% account/url 'login' %} -
How to write permissions in a viewset with conditional statements in DRF?
I have a viewset written in DRF: class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = models.MyClass.objects.all() def get_serializer_class(self): permission = self.request.user.permission if permission=='owner' or permission=='admin': return self.serializer_class else: return OtherSerializer def perform_create(self, serializer): permission = self.request.user.permission if permission=='owner' or permission=='admin': serializer.save() else: employee = models.Employee.objects.get(user=self.request.user) serializer.save(employee=employee) Here, I am using the following statements in both get_serializer_class and perform_create which looks like a repetitive code: permission = self.request.user.permission if permission=='owner' or permission=='admin': Is there any way to write it once and then use it as a permission_class somehow? -
How to add products to cart using sessions as a guest in django
settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" models.py class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(default='-') description = models.TextField() unit_price = models.FloatField() inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Cart(models.Model): created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() I want to add the products in the cart using session through cache. how can I make a key named as 'cart' in request.session and add those product's id in it. I initially tried to set 'cart' key using request.session.setdefault('cart', list()) but then I read the django documentation and it says that the items should be in the form of dictionaries(according to conventions). So what can I do to store the products in the cart for guest users? -
Raise conditional permission error in get_queryset DRF
I want to get all users of an organization by uuid. I am following REST standards so I want my url to look like 'organizations/uuid/users/'. If super admin hits this API, it should be allowed but If an admin user tries using this API, then it should only allow if the admin belongs to the same organization for which users are requested. I used ListAPIView generic view class and I was able to get list of all users in an organization from admin of different organization but it still returns info when it should return 403 error. urls.py path('organizations/<uuid:pk>/users/', OrganizationUsersView.as_view()), views.py class OrganizationUsersView(ListAPIView): serializer_class = UserSerializer permission_classes = (IsAuthenticated, IsSuperAdmin|IsAdmin,) def get_queryset(self): uuid = self.kwargs['pk'] if self.request.user.role == 'admin': if self.request.user.org.id != uuid: return IsOrganizationAdmin() org = Organization.objects.get(id=uuid) return User.objects.filter(org=org) models.py class Organization(models.Model): name = models.CharField(max_length=255, null=False) class User(AbstractBaseUser): .... other fields .... org = models.ForeignKey(Organization, on_delete=models.CASCADE, null=False, related_name='users') -
How to create a nested list of parent/child objects using a function?
everyone! I'm new to Python and Django and I've encountered a problem I can't solve on my own for quite a long time. I have a database that consists of a number objects and each object has one parent (except the first, the 'root' object) and no / one / several children. I need to create a fuction that takes some object and returns this object and recursively its descendants like this: arr = ['States', ['Kansas', ['Lawrence', 'Topeka', ['Some Topeka Street', ['Some House on Some Topeka Street']]], 'Illinois', ['Chicago', 'Springfield']]] I want to get this kind of data structure and use it on Django's unordered list filter. As far as I know about algorithms I should make up a function that somehow should work like this: def make_nested_list(item): if not item.children: # basic case # do something else: for child in item.children: # recursive case # do something make_nested_list(child) # function calls itself # maybe do something here # and finally return self-nested list return result Everything I try turns out to be a mess. How can I do that? -
Django celery-beat dont restart beat
There is a site parsing service that sends several requests to a url with parameters, and this process lasts 30 minutes, if at that time when the request to restart the beat is sent, then the task disappears (stops) and you have to send it again and manually start the process, how can this be avoided so that the request is sent and I create new tasks and safely restart the beat.