Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot recognize package specified in application's __init__.py if i reorganize my applications to an apps folder
I have a Django3 project, let's say "blog". Typical folder structure for applications is: /blog/ /article/ /users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py I want to let the structure to be clean so I put all applications into a apps folder. So now the structure looks like the following: /blog/ apps/ __init__.py article/ users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py I want to use signal function in article apps/application, so the files in article are /blog/ apps/ __init__.py article/ migrations/ __init__.py admin.py apps.py models.py signals.py tests.py views.py users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py in apps/article/signal.py file: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify from core.utils import generate_random_string from apps.article.models import Article @receiver(pre_save, sender=Article) def add_slug_to_question(sender, instance, *args, **kwargs): if instance and not instance.slug: slug = slugify(instance.content) random_string = generate_random_string() instance.slug = slug + "-" + random_string in apps/article/apps.py file: from django.apps import AppConfig class ArticleConfig(AppConfig): name = 'article' def ready(self): import apps.article.signals in apps/article/init.py file: default_app_config = "apps.article.apps.ArticleConfig" if I restart my server, it shows the error: django.core.exceptions.ImproperlyConfigured: Cannot import 'article'. Check that 'apps.article.apps.ArticleConfig.name' is correct. I also tried several settings in apps/article/init.py file like: default_app_config = "article.apps.ArticleConfig" … -
Class diagram of deep learning model deployed in django
i m working on project that is stock market price prediction using deep learning.The Model is then deployed into django framework where the actual and predicted price is shown in graphical form. Anyone can help me in making the uml class diagram of whole project.Thanks -
How to set order_by only on ManytoManyfield in detailview (Django)?
I have 2 models Class and Student. One field within the Class mdel has a ManytoManyField relationship with Student. I want to order the manytomanyfield with first_name in the template. How can I do it? models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=100) class Class(models.Model): student = models.ManyToManyField(Student) subject = models.CharField(max_length=150, unique=True) # many other fields views.py class Class_detailView(LoginRequiredMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html template <div class="row ml-auto mr-auto"> <h6>{{ object.subject }}</h6> {% for student in object.student.all %} <h6 id="class-detail-text" class="mt-2"> {{student.first_name}} <-- want to order here </h6> {% endfor %} </div> right now the names render like this: Freaky Albon Bucky I want it to order like this: Albon Bucky Freaky -
Django ORM join on foreign keys that don't point at each other
tl;dr I'm trying to skip a superfluous join while using Django's ORM Let's say I have models like: # Recipe model not shown, not necessary. class RecipeIngredient(IngredientMixin, models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, related_name='recipeingredients') ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, related_name='recipeingredients') class Ingredient(models.Model): # ...other fields... # M2M field that stores a hierarchy of ingredients. Ingredients can # have multiple parents. parents = models.ManyToManyField( 'self', blank=True, through='IngredientParent', symmetrical=False, ) class IngredientParent(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name='+') parent = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name='+') And I'm trying to figure out which Recipes contain a certain ingredient, but also include Recipes if the parent of an ingredient is our chosen ingredient. For example, "cheese" might be a parent of "cheddar" and if someone selects "cheese", I want to show them all recipes with cheese, but also with cheddar, etc. ANYWAY, I do this: i = Ingredient.objects.get(name='cheese') recipes = Recipe.objects.filter( Q(recipeingredients__ingredient=i) | Q(recipeingredients__ingredient__parents=i) ) print(recipes.query) which gives me the SQL: SELECT -- all Recipe fields FROM "core_recipe" INNER JOIN "core_recipeingredient" ON ("core_recipe"."id" = "core_recipeingredient"."recipe_id") INNER JOIN "core_ingredient" ON ("core_recipeingredient"."ingredient_id" = "core_ingredient"."id") LEFT OUTER JOIN "core_ingredientparent" ON ("core_ingredient"."id" = "core_ingredientparent"."ingredient_id") WHERE ("core_recipeingredient"."ingredient_id" = <ingredient_id> OR "core_ingredientparent"."parent_id" = <ingredient_id>) Looks good. But actually, that INNER JOIN to core_ingredient … -
Django 3.1 TemplateNotFound Exception when Template is Present
I am trying to work towards deploying my application and have done most of my work on Windows. However now that I have moved it over to AWS it does not work anymore. Before anyone links other articles here is a list of all the things I have tried: Adding os.path.join(BASE_DIR,'templates') to TEMPLATE_DIR Changing the permissions of my template My app is in my INSTALLED_APPS variable I have checked that all my render methods are formatted correctly Re-downloaded my project completely Like I said earlier, it works on my Windows machine, just not on AWS or my Mac. Even more strange is that the error says Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/admin/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/auth/templates/uploads/base.html (Source does not exist) And /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html is the correct absolute path to the template I am looking for. If I try to cat that file, using that absolute path, it prints to stdout. All this being said I will include some of my code for critical review. views.py def get(self, request, *args, **kwargs): paste = None return render(request, 'uploads/index.html', … -
How to set checkbox state in a table cell based on another cell's value Django templates
I am trying to set a checkbox inside a cell in each row of a table depending on another cell's value in the row. I am accessing the cell with the value, comparing with a pre-determined value (say "L") and if found, marking the checkbox true. So far I have tried the following: HTML <table id="listTable"> <thead> <tr> <th>Doc Num</th> <th>Short Text</th> <th>Locked</th> <th>Lock Type</th> <th>Frequency</a></th> </tr> </thead> <tbody id="filterTableBody"> {% for data in prod_sch %} <tr> <td><a href="{% url 'prod_schdle' data.pk %}">{{ data.doc_num }}</a></td> <td>{{ data.desc }}</td> <td><input type='checkbox' class='chk_locked' id='id_chkbox_locked' disabled='true'></td> <td>{{ data.lock_type }}</td> <td>{{ data.freq }}</td> </tr> {% endfor %} </tbody> </table> jQuery $(function() { $('#listTable tr').each(function() { var val_status_lock = $(this).find('td').eq(3).html(); if ( val_status_lock === 'L' ) { $('.chk_locked').prop('checked', true); } }); }); Currently, checkboxes of all the rows are getting checked true, even for the rows with a different cell value. How to mark checkboxes of only those rows where the cell value is L? -
Does Sentry work for 2 server instances running the same application pointing to 1 project?
I'm new to Sentry and I'm just curious if it's possible to create 1 project in Sentry and make 2 server instances (2 EC2 instances with load balancer) running the same application and both applications (Django) pointing to the same DSN or 1 project in Sentry? -
How to subtract 2 timezone aware dates in python
I have the following function to find the difference in minutes between 2 dates: def time_diff(self): now = pytz.timezone(self.facility.time_zone).localize(datetime.now()) print(later_time) print(earlier_time) second_diff = (now - self.created_at).total_seconds() return second_diff This prints: > 2020-09-12 20:58:26.006197-07:00 > 2020-09-13 01:57:51+00:00 The created_at is an auto generated field created like: created_at = models.DateTimeField(auto_now_add = True) Time zone is stored with: self.facility.time_zone = 'America/Los_Angeles' Why are the times 2 hours off? -
How To Connect Django With Mqtt
i know how to use mqtt with python but i can't connect django app to mqtt background research <http://www.steves-internet-guide.com/mqtt-basics-course/> <https://pypi.org/project/paho-mqtt/#installation> -
Angular + Django Rest Framework rearranging array on SPA, separate severs works okay
I have a random issue happening. When I run Angular and Django one separate instances (ng serve --poll 2000 & python manage.py runserver) my data is transferred as expected and works okay. When I build my angular project and run via apache2 using django as the entry point for the application I have an array which becomes reordered every time. node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --aot --output-path ../backend/static/ang --output-hashing none The array is loaded with the same contents on different pages and can be in any order. There are 4 primary categories and its these which are reordered. The ITEM1, ITEM2, ITEM3 and ITEM4 below. I have no idea why. The code which makes the nodes is below: def get(self, request): response = {} subjects = ['ITEM1', 'ITEM2', 'ITEM3', 'ITEM4'] for subject in subjects: try: alltitles = TitlePageTitles.objects.filter(title__contains=str(subject)) response.update({subject : []}) titleslist = [] returnedJson = {} returnedList = [] returnedJsonString = "" for title in alltitles: titleslist = list(TitlePageItems.objects.filter(ks_key=title.title).order_by('id').values()) newJsonItem = { "id": 0, "ks_key": title.title, "item_text_display": title.title.replace("_"," "), "item_text_link": title.title.replace("_"," "), "order": -1, "page_id": 0, "children": ArrayToNested(titleslist) } returnedList.append(newJsonItem) response.update({subject : returnedList}) except Exception as inst: print(inst) returnedList2 = [] for key, value in response.items(): #logger.error(key) newJsonItem = … -
How can I create a ForeignKey leaving chances for different models for the TO field?
I have multiple product models like below class ProductBase(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True def __str__(self): return self.name class ProductOne(ProductBase): color = models.CharField(max_length=50) class ProductTwo(ProductBase): type = models.CharField(max_length=50) class ProductThree(ProductBase): breed = models.CharField(max_length=50) Each of these products is expected to have an image_set, so I created the model below for product's images class Image(models.Model): product = models.ForeignKey(to=[HERE IS THE PROBLEM], on_delete=models.CASCADE) image = models.ImageField(upload_to='upload-path') How can I get the product field in my Image class to point to any of the products defined above as desired. -
(Django) Signal isn't working but it works in the shell
I have a signal that runs post_save when a new Student is created that goes through their currently enrolled courses and assigns them an instance of the courses' assignments (for scoring). In users/signals.py: @receiver(post_save, sender=Student) def save_student_assignments(sender, instance, created, **kwargs): if created: all_courses = instance.enrolled_courses.all() assignments = Assignment.objects.filter(session_link__in=all_courses) for assignment in assignments: StudentAssignment.objects.create(student=instance, assignment=assignment) I have already been in users/apps.py to import the signal. If I run this exact code in the shell, it will create the StudentAssignment objects and they'll show up for the user. What am I missing here that's not making the signal fire like it should? -
ImproperlyConfigured at /accounts/verification/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Well I am actually trying to add some very simple logic here. All I want to do is that if the vcode or verification code is equal to 5577 than redirect me to the login page. Otherwise if the user enter wrong number than just show an alert message with text that the code is incorrect or invalid and ask him code to enter again. Right now its showing me an error( given in the Title of this question) when I hit the verify button. If more detail or code is required for help than tell me. I will update my question with that information. I shall me very thankful to you. If you guys spend some of your precious time to answering me with a wonderful and helpful information! class CodeCreateView(CreateView,SuccessMessageMixin): form_class = CodeForm def form_valid(self,form): vcode = form.cleaned_data.get('code') if vcode == 5577: user = form.save(commit=False) user.is_active = True success_message = "Verified successfully" success_url = reverse_lazy('login') else : success_message = "Verifification unsuccessful" return super().form_valid(form) # success_url = reverse_lazy('accounts:code_verification') template_name = "accounts/code_verification.html" -
I get AttributeError: 'SubscriptionForm' object has no attribute 'model' when I try runserver and makemigrations
When I do python manage.py runserver or makegrations I get this traceback issue. Where have I gone wrong? Please help. I"m trying to add this to the admin site as well. Thank you This actually worked once, so I'm not sure what I did wrong or what I changed to make this error come up. traceback error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\checks.py", line 56, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\Charlie\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\sites.py", line 81, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'SubscriptionForm' object has no attribute 'model' models.py class Subscription(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) username = models.CharField(max_length=100) sub_type = models.BooleanField() email = models.EmailField(max_length=100) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) country = models.CharField(max_length=100) state = models.CharField(max_length=100) zip = models.CharField(max_length=10) same_address = models.BooleanField() save_info = models.BooleanField() credit = models.BooleanField() debit = models.BooleanField() paypal = models.BooleanField() cc_name = models.CharField(max_length=100) cc_number = models.IntegerField() … -
Django DateTime Subtraction Hours
I subtract two datetime objects and get integers instead of time in hours and minutes. This is my MODEL.PY class TimeLog(models.Model) start_date = models.DateTimeField(null=True, blank=True, default=datetime.now) end_date = models.DateTimeField(null=True, blank=True, default=datetime.now) time_diff = models.DateTimeField(null=True, blank=True) TimeLog.objects.filter(time_diff=None).update(time_diff=F('end_date') - F('start_date')) I get 2020-09-12 22:51:58.383288 - 2020-09-12 23:03:57.088453 = 718705165 How do I make 718705165 to be in hours and minutes? -
Asynchronous show a POST
I am working on a twitter-like social network site. In one single html page, I have a form to send the "tweet" and also down the form I have displayed all the "tweets" made by all users. {% if posts %} {% for post in posts %} "html that creates the tweet, content, creation date, number of likes, etc." {% endfor %} {% endif %} To handle the form submission, I want the "tweets" to be shown asynchronously, so I`m doing a fetch POST request with JavaScript: document.querySelector('form').onsubmit = (event) => { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { document.querySelector('#new_message').value = "" let div = document.createElement('div') div.innerHTML = ("<p>" + result.creation_date + "</p>" + "<a href='#'>" + result.username + "</a>" + ' said:' + '<br><br>' +"<div class='container'>" + "<p>" + result.body + "</p>" + "</div>"); div.style.cssText = "box-shadow: 0px 0px 2px; ; background-color:#F5F5F5; border-radius:10px; padding: 10px; margin: 5px;"; document.querySelector('#plis').append(div); }); This works fine, the tweets are saved and also showed in the page without having to reload the entire page. But the problem is that I am handling the HTML in both … -
Custom User Model table has no column named is_staff
So I am creating a user registration api, here is my code: models.py class CustomUserManager(BaseUserManager): #Making the username to be the user's email def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): #create and save user with a given email and password if(not email): raise ValueError("User must have a valid Email!") now = timezone.now() email = self.normalize_email(email) user = self.model( email = email, is_staff = is_staff, is_active = True, is_superuser = is_superuser, last_login = now, date_joined = now, **extra_fields ) user.set_password(password) user.save(using= self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): """ Create and save a super user with given email and password """ user = self._create_user(email, password, True, True, **extra_fields) user.save(using= self._db) return user class MyUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length= 50) last_name = models.CharField(max_length= 50) email = models.EmailField(unique= True) age = models.DateField(null= False) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) last_login= models.DateTimeField(null= True, blank= True) date_joined= models.DateTimeField(auto_now_add= True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' #instantiating a CustomUserManager() object objects= CustomUserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) I am getting the following error, when I try to register a user: Error message Image It is complaining about is_staff. Error Message: Operational … -
Tabs and image timed changing
I've a tab where I display tab content on the left side, but on refresh, the tab current page doesn't stay, instead it goes back to the home Link. Secondly, on The tabcontent, I've images on my Django database, were I display them on my template using the forloop, but I want to change the images after a given time. Below is my code for better understanding.. Js // Sidebar functionality function openLinks(links){ var i; var x = document.getElementsByClassName("tabcontent"); for (i = 0; i < x.length; i++){ x[i].style.display = "none"; } document.getElementById(links).style.display = "block"; } // Changing Images var divs = $('#men .column'); (function cycle(){ setTimeout(function(){ var index = Math.floor(Math.random() * divs.length); divs.removeClass('active') .eq(index).addClass('active'); cycle(); },500); })(); My HTML <div class="sidebar"> <ul> <li><a href="#/home" class="tablinks" onclick="openLinks('home')"> <span class="icon"><i class="fas fa-home" aria-hidden=True></i></span> <span class="title">Home</span> </a></li> <li><a href="#/men" class="tablinks" history="true" onclick="openLinks('men')"> <span class="icon"><span class="icon"><i class="fas fa-male" aria-hidden=True></i></span> <span class="title">Men</span> </a></li> </div> <div id="home" class="tabcontent"> {% for men in men %} <div class="column"> <a href="{{men.get_men_absolute_url}}"><img src="{{home.pictures.url}}" style="width: 150px; height: 100px;"></a> </div> <div id="men" class="tabcontent" style="display: none;"> {% for men in men %} <div class="column"> <a href="{{men.get_men_absolute_url}}"><img src="{{men.men_pictures.url}}" style="width: 150px; height: 100px;"></a> </div> </div> -
Django count manytomany relation shows wrong number
I currently have a queryset which aims to extract a list of used colors associated with products, and return response with a list of colors and the amount of of products they're attached to. The colors originate in its own model called ProductColor and is referenced through a ManyToMany relationship in the Product model. In the example bellow there are 3 products which has these colors registered: Product 1: White Product 2: White, Red Product 3: White Wished output should be something like: [ { "colors__name": "White", "count": 3 }, { "colors__name": "Red", "count": 1 }, ] However, the closest i get is: [ { "colors__name": "White", "count": 1 }, { "colors__name": "White", "count": 1 }, { "colors__name": "Red", "count": 1 }, { "colors__name": "White", "count": 1 } ] The queryset is structured like this: products = Product.objects.filter( category__parent__name__iexact=category, status='available' ).values('colors__name', count=Count('colors', distinct=True)) I've tried to add .distinct() at the end of the queryset, but then it returns: [ { "colors__name": "White", "count": 1 }, { "colors__name": "Red", "count": 1 } ] I've also tried using an annotation through .annotate(count=Count('colors')), but then it returns: [ { "colors__name": "White", "count": 7 }, { "colors__name": "Red", "count": 3 } ] How can … -
How does the cost of getting a specific row of a table compare to the cost of getting all rows?
I have to render a tree data structure on a user's browser, each node knows its' children. How does getting the whole table and doing the rest of the heavylifting on the client side compare to getting the nodes via multiple queries, knowing that the user might not require all nodes, but in average 80%? That is, to my SQL server is it better to just send the whole table and be done with it or to send nodes as needed, knowing that all nodes might be needed and in average 80% of nodes are needed? The user always requests a node by ID/Primary Key. This question pertains to Django and loading objects recursively. -
Django get response status?
I'm creating a forum. You know, the typical. Profiles can create posts and answer with comments, also they can vote comments and posts. Profile has a score system called reputation (just a Django's PositiveIntegerField in Profile model), which is the sum of created posts, created comments, and received votes for a profile. I have to update it each time one of these events happen, therefore I made a simple function for it, which I call it after every .save() of those objects with the profile to update. But I thought I maybe could use a Middleware for a cleaner code and so I don't have to remember to call that function everytime. Since the Django documentation says after get_response() we put the # Code to be executed for each request/response after the view is called.. But I don't need to run this middleware on each request/response, instead I thought there is maybe a way to check if the status of a response is the creation of an object, and then check if a post, comment, or vote were created in order to run the score update. I'm opened to other ideas if you think that idea can be better or … -
Fatal Python error: Py_Initialize: Unable to get the locale encoding
When I try to deploy my django app on heroku I get this error while I want to show the app. heroku logs --tail 2020-09-12T20:36:32.949657+00:00 app[web.1]: [uWSGI] getting INI configuration from uwsgi.ini 2020-09-12T20:36:32.949732+00:00 app[web.1]: *** Starting uWSGI 2.0.19.1 (64bit) on [Sat Sep 12 20:36:32 2020] *** 2020-09-12T20:36:32.949732+00:00 app[web.1]: compiled with version: 7.5.0 on 11 September 2020 18:09:44 2020-09-12T20:36:32.949732+00:00 app[web.1]: os: Linux-4.4.0-1076-aws #80-Ubuntu SMP Thu Aug 6 06:48:10 UTC 2020 2020-09-12T20:36:32.949735+00:00 app[web.1]: nodename: 3ae70b13-94fd-4637-9782-d3aa9e80ed45 2020-09-12T20:36:32.949735+00:00 app[web.1]: machine: x86_64 2020-09-12T20:36:32.949737+00:00 app[web.1]: clock source: unix 2020-09-12T20:36:32.949738+00:00 app[web.1]: pcre jit disabled 2020-09-12T20:36:32.949739+00:00 app[web.1]: detected number of CPU cores: 8 2020-09-12T20:36:32.949754+00:00 app[web.1]: current working directory: /app 2020-09-12T20:36:32.949754+00:00 app[web.1]: detected binary path: /app/.heroku/python/bin/uwsgi 2020-09-12T20:36:32.949756+00:00 app[web.1]: *** WARNING: you are running uWSGI without its master process manager *** 2020-09-12T20:36:32.949770+00:00 app[web.1]: your processes number limit is 256 2020-09-12T20:36:32.949771+00:00 app[web.1]: your memory page size is 4096 bytes 2020-09-12T20:36:32.949772+00:00 app[web.1]: detected max file descriptor number: 10000 2020-09-12T20:36:32.949774+00:00 app[web.1]: lock engine: pthread robust mutexes 2020-09-12T20:36:32.949822+00:00 app[web.1]: thunder lock: disabled (you can enable it with --thunder-lock) 2020-09-12T20:36:32.950161+00:00 app[web.1]: uwsgi socket 0 bound to TCP address :24256 fd 3 2020-09-12T20:36:32.950203+00:00 app[web.1]: Python version: 3.6.12 (default, Aug 18 2020, 11:10:29) [GCC 7.5.0] 2020-09-12T20:36:32.950227+00:00 app[web.1]: Set PythonHome to /app 2020-09-12T20:36:32.954759+00:00 app[web.1]: Fatal Python error: Py_Initialize: … -
How can I write view decorator for class and non-class methods?
I've built the following decorator to extract a token from HTTP headers, and call the decorated function. Or, if no token exists, or is invalid, returns a 403 status. def extract_operator(func): @wraps(func) def func_wrapper(self, request, *args, **kwargs): try: operator = Operator.objects.get(token=request.META.get('HTTP_OPERATOR_TOKEN')) return func(self, request, operator, *args, **kwargs) except Exception as ex: return Response({}, status=status.HTTP_403_FORBIDDEN) return func_wrapper The problem I'm running into is that this only works for class methods, not for methods outside class that don't use 'self'. The only examples I could find to address this issue used something like this: def extract_operator(func): @wraps(func) def func_wrapper(*args, **kwargs): try: operator = Operator.objects.get(token=args['request'].META.get('HTTP_OPERATOR_TOKEN')) return func(*args, **kwargs) except Exception as ex: return Response({}, status=status.HTTP_403_FORBIDDEN) return func_wrapper This sorta worked but I am not able to pass the 'operator' variable correctly. Here is a non-class method using the decorator: @api_view(['POST']) @extract_operator def send_support_email(request, operator): pass here is an example of a method in a View: @extract_operator def create(self, request, operator, *args, **kwargs): pass How can I modify my decorator to work correctly with both methods? -
validate date in python
I need to validate a date that comes from the front and say that I am over 13 years and I have the code the only thing missing is what goes into the if thanks for your help import datetime class LegalAgeValidator: LEGAL_BASE_AGE = 13 def __init__(self): self.base_age = LEGAL_BASE_AGE def __call__(self, value): if message = 'age not allowed to register.' % self.base_age raise serializers.ValidationError(message) -
Django queryset getting the related field name to filter an aggregate sum
In my models.py I have the following example: **Orders** id product total_gross **Payments** id status order_ID I am creating the following queryset to get a total sum if the payment status is confirmed. So I use the following: week_order_total = Order.objects.prefetch_related('payments').filter(created__range=(week_start_date, week_end_date)).filter(payments.status='confirmed').aggregate(Sum('total_gross'))['total_gross__sum'] I receive the following error: keyword can't be an expression