Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, formula to get the monthly percentage income performance
I have the following code: import datetime total_income = {'Revenues': [100 for m in range(12)]} current_month = datetime.date.today().month current_revenue = total_income['Revenues'][current_month - 1] cumulative_revenue = sum(total_income['Revenues'][:current_month]) All works perfectly but now I wanna get the percentage increase/decrease monthly value compared to the previous month. Ad example if current_month = 6 I want to calculate the percentage increase/decrease compared to the may month. Ad example: current_montlhy_performance = (revenuse_jun-revenuse_may)/revenuse_may*100 Moreover I wanna manage all error that could arise ad example if the denominator is equal to zero. -
Django boolean filter elements in template
I have a Django template where I do queries like this: {% for post in user.post_auctions_set.all %} The point for me now is that I only want to display post elements that don't have the Boolean prime = True. I came across template tags but never really worked with them. Can smb. give me a hint on how I could setup a filter like? Thanks in advance -
Setting browser/os restrictions on Django
I’m new to django programming, not python, and could do with a hand. I am attempting to make a website exclusive to a certain device. I have created a disallow page accessible by ‘/disallow/’. How do I go about running os/browser checks that then redirect in the event the os/browser is not on the verified list. I know the information I am wanting to check will be in the request and I can use request.META['HTTP_USER_AGENT'] However where do I write any logic required and how could I apply this to any page the user tries to access. Any help would really be appreciated Ed -
Loading JSON contents using django framework
How can I load all the contents of a JSON file into my project?? I am using Python-Django as my backend and MongoDB as my database. I am trying to store the contents of JSON file onto MongoDB (Djongo) -
Overriding save method in a django proxy model
I am using a third party application and i wish to override the save() method of the original model to validate some data. class CustomState(State): class Meta: proxy = True def save(self, *args, **kwargs): print('hellooo in save method of state') super(State, self).save(*args, **kwargs) However the code snippet above does not run. Therefore my question is is there a way to override the save method of a model ? Or if thats not possible , is there a way to add in validation before the third party model instance is created? -
Django : local variable 'order' referenced before assignment
I'm trying to make a json API that list all the product in an order. This is my code : models.by: ... class order(models.Model): user = models.ForeignKey(memberArea, on_delete=models.CASCADE) comment = models.TextField(null=True, blank=True) orderDay = models.DateTimeField(auto_now_add=True) deliveryDay = models.DateField() deliveryPlace = models.CharField(max_length=255) state = models.CharField(max_length=255) price = models.TextField(null=True, blank=True) response = models.TextField(null=True, blank=True) def __str__(self): return self.state ... views.py: ... from .models import category, product, byProduct, memberArea, order, orderDetail ... #Orders @api_view(['GET']) def orders(request): '''Get all the orders for a user''' context = [] if request.GET.get('user'): #If we make a request type ?user=... id_user = request.GET.get('user') user = get_object_or_404(memberArea, pk=id_user) if request.GET.get('order'): #If we make specific request on a specific command id_order = request.GET.get('order') orders = order.objects.filter(id=id_order, user_id=id_user) if not orders.exists(): return HttpResponse(status=404) #Or 404 else: orders = order.objects.filter(user_id=id_user) for order in orders: #For all the orders that the user have made dictionary = { 'userId': id_user, 'id': order.id, 'orderDay': order.orderDay, 'deliveryDay': order.deliveryDay, 'deliveryPlace': order.deliveryPlace, 'products' : [], #List all the products orders } ... When I run this code, I get an error of this type : local variable 'order' referenced before assignment I don't understand why I get this error. Someone can explain to me ? Thanks by advance -
How to set dynamically date in a countdown Jquery?
In my django application I want to create a countdown which is initialized at 5 minutes when the user click submit button of my form. (id is #loadQuestion). To get a dynamic timer I used jquery countdown So I did like this : var finished = new Date() $("#loadQuestion").click( function(event) { console.log(finished); finished.setMinutes(finished.getMinutes() +5); console.log(finished); // return finished; }); $('#defaultCountdown').countdown(finished, function(event) { // console.log(finished); $(this).html(event.strftime('%M:%S')); }); My problem is that variable finished is not saved as finished.getMinutes() + 5 as I want in the submit function. How could I set this variable ? I tried to define it as global (outside the functions) I can see in the log when I click submit that the first function works ( I get current time then current time + 5 minutes), and in the next function in the log I get current time again ... ) I tried to return the variable finished in the first function but how can I get the returned output ? I don't call this function anywhere its just on click I tried an other method with '''5 * 60 * 1000 + (new Date()).getTime();''' instead of '''finished''' in the countdown function but the problem is that … -
Sending emails from an html form embedded in another html
I am trying to embed an HTML with a form into another HTML (my home page) and allow users to interact with the form on my home page to send emails to my account. The HTML form sends emails successfully when a user submits a valid form. However when I try and interact with the HTML form embedded in my home page no emails are being sent and I do not get any error messages to get a better understanding of what the problem might be Here is my form {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} Title {% endblock %}</title> </head> <body> {% block content %} Contact Us {% endblock %} <form method="post" action="" class="validate"> {% csrf_token %} {{ form|crispy }} <div class="form-field"> <label for=""></label> <input type="submit" value="Submit Assignment" /> </div> </form> </body> </html> This is how I embedded the form in my home page: <include src="{% url 'assignmentSubs' %}"></include> ... <script> (() => { const includes = document.getElementsByTagName('include'); [].forEach.call(includes, i => { let filePath = i.getAttribute('src'); fetch(filePath).then(file => { file.text().then(content => { i.insertAdjacentHTML('afterend', content); i.remove(); }); }); }); })(); </script> my forms.py class AssignmentSubs(forms.Form): from_email = … -
Not Null constrained error on field handled in views.py
I am working with django rest framework. I have Product and Review models. Review is related to Product like so; class Product(models.Model): name = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(max_length=2000, null=False, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) is_featured = models.BooleanField(default=False) created= models.DateTimeField(auto_now_add=True) class Review(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) product= models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=80, blank=False, null=False) body = models.TextField(max_length=400, blank=False, null=False) is_approved = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) I wrote a serializer class for the review: class ReviewSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) class Meta: model = Review fields = ['id', 'author', 'title', 'body', 'is_approved', 'created'] def create(self, validated_data): title = validated_data.get('title') body = validated_data.get('body') author = self.context['request'].user review = Review.objects.create(title=title, body=body, author=author) return review and in my views.py, i have this; class ReviewCreateView(CreateAPIView): serializer_class = ReviewSerializer queryset = Review.objects.all() permission_classes = [IsAuthenticated,] authentication_classes = [TokenAuthentication,] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) product_id = kwargs.get('product') product = Product.objects.get(id=product_id) serializer.save(product=product) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) in my urls urlpatterns: path('api/review/new/<product>/', ReviewCreateView.as_view(), name="create-review"), Issue is when i send a review from the frontend to that api, i keep getting a Not Null constraint error like so: IntegrityError at /api/review/new/23/ NOT NULL constraint failed: products_review.product_id … -
required = True not taking effect in Django form field
what i want is to make the DateField and CharField required so that the form cant be submitted with the fields empty, but even after setting required = True in both it doesn't take effect and end up throwing an error on saving the form, i dnont know where am getting it wrong here is the form class: class RepairOrderForm(forms.ModelForm): brand = forms.CharField( required=True, widget=forms.TextInput( attrs={ "placeholder": " e.g DELL", } ) ) model = forms.CharField( required=True, widget=forms.TextInput( attrs={ "placeholder": "Device model", } ) ) serial_no_or_IMEI = forms.CharField( required=True, label="Serial No/IMEI", widget=forms.TextInput( attrs={ "placeholder": "Device serial No/EMEI", } ) ) fault_details = forms.CharField( required=True, widget=forms.Textarea( attrs={ "placeholder": " A detailed description of the fault", } ) ) pick_up_date = forms.DateField( required=True, # initial = datetime.date.today, widget=forms.DateTimeInput( attrs={ # "class": "datepicker", } ) ) coupon_code = forms.CharField( required=False, widget=forms.TextInput( attrs={ "placeholder": "Got a coupon/voucher use it here and get a discount on your repair order", } ) ) survey = forms.CharField( required=False, widget=forms.Textarea( attrs={ "placeholder": "How did you hear about us", } ) ) terms_and_condition = forms.BooleanField( required=True, label=' I have read and agree to the' ) class Meta: model = RepairOrderModel fields = [ 'device_type', 'brand', 'model', 'serial_no_or_IMEI', 'fault_details', 'pick_up_date', … -
Getting empty Queryset with no reason in django
I try to get objects from a manytomany relationship but it return empty. The first method, get_service_users return data but both pprint() attempts at save() method return '[]' empty. why? and how do i get the same response? class workSession(models.Model): sort_service = models.CharField(max_length=50) date = models.DateTimeField() service_worker = models.ManyToManyField(User, related_name="service_worker", limit_choices_to={'groups__name': 'Worker'}) service_user = models.ManyToManyField(Associate, related_name="service_user") price = models.FloatField(verbose_name="Price") fee = models.OneToOneField(Fee, on_delete=models.deletion.CASCADE, null=True, blank=True, editable=False) def get_service_users(self): return ", ".join([(associate.name + ' ' + associate.surname) for associate in self.service_user.all()]) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.pk: fee_pk = Fee() fee_pk.title = self.sort_service fee_pk.description = self.sort_service + " session" fee_pk.date = self.date fee_pk.quantity = self.price fee_pk.save() pprint(self.service_user.all()) actual_worksession = workSession.objects.get(pk=self.pk) pprint(actual_worksession.service_user.all()) fee_pk.save() self.fee = fee_pk -
mod_wsgi not installing in CentOS v8
I tried installing mod_wsgi to deploy my flask application but I get the following error: Error: Unable to find a match: mod_wsgi I am following this article: https://dev.to/sm0ke/flask-deploy-with-apache-on-centos-minimal-setup-2kb7 sudo yum install mod_wsgi No match for argument: mod_wsgi Error: Unable to find a match: mod_wsgi -
Django: When I try to take input within url using path() showing invalid syntax
I tried to take an integer input within the url in urls.py and take it to views.py this is the code I did : urlpatterns = [ .... path('dater/plus/int:offset/' , views.timeahead, name='timeahead' ) .... ] but it is showing syntax error at this path. This is my first question on stack overflow, I'm just a beginner pardon me for any blunders I make. -
About django 3 and websockets in python3
I want to make a chatting application using django3. Is it possible to use sockets in python programming and django together to build a real time chatting a app and If it is How ?? -
Update a model field fetching data from user model in django
I have a User model using AbstractBaseUser. I have a model Employee using Model class. I want that when a user is created though sign up, the user inherits all the fields of Employee model. I have made a OnetoOne relation between User model and Employee. But after creating an user when I query employee model, I can not find any data relation to the created User. User manager: class UserManager(BaseUserManager): """ Creates and saves a User with the given email and password. """ def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email,username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user User: class User(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserManager() def get_full_name(self): # The user is identified by their email address … -
Django 2.2 and Djongo Embedded Models - “Models aren't loaded yet”
Whenever I try to create an EmbeddedFieldin Django with Djongo I get the below error message. I tried everything suggested around the web. But I'm absolutely stuck here and need help to overcome that issue. As soon as I try to migrate or try to runserver it throws this error. This error starts to appear as soon as I use EmbeddedField. I haven't modified the manage.py file. Error Message djongo django.core.expceptions.AppRegistryNotReady: Models aren't loaded yet. models.py from djongo import models class ClientRepresentation(models.Model): client_main_contact = models.CharField(max_length=100) client_stand_in_contact = models.CharField(max_length=100) class Meta: abstract = True class User(models.Model): client_name = models.CharField(max_length=100) client_location = models.CharField(max_length=100) client_representation = models.EmbeddedField( model_container=ClientRepresentation # null=True ) objects = models.DjongoManager() def __str__(self): return self.client_name settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # REST Framework API 'rest_framework', # Own Apps 'usr' ] manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djongotest.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
How to acess inner class in from one class to another class in python
class A: class A1: print("A1") class A2: print("A2") class B(): class B1(A): #We need to access class A1 in this position like output will be A1 only A.A1() x = B.B1() # But we get output A1 and A2 # We need only A1 -
Form date time field Django 3.0.6
How i can display date Time field form like on Django admin I am using Django 3.0.6 I am beginner in django. I try to search on djangodocs and i can founded. -
Is it possible to get data list from django many to many field?
class ProductVariatons(models.Model): # Variatons of a products like, 38-Small-Red, 39-Small-Green name = models.CharField() sub_variations= models.ManyToManyField(SubVariations) class SubVariations(models.Model): # SubVariations like 38, 39, Small, Medium, Large, Red, Green... name = models.CharField() For example user sent me a list of some sub variations like (38-Small) and i would like to response like here is the options depend on your request: 38-Small-Red, 38-Small-Green. Because there are the only choices for selecting 38 and Small.If the user would have choosed 39-Small i would like to send response like: 39-Small-Red, 39-Small-Green, 39-Small-Blue.If I filter like: user_request_list = [38, 'Small'] filtering = ProductVariatons.objects.filter( sub_variations__in=user_request_list ) It gives me a queryset of all the datas contain 38 and 'Small'. When i access third option's of the datas that i received, (and list them) it's ['Red', 'Green', 'Blue'] But that is not the list that i want.What i want is exactly the 38 and 'Small' datas contain in the same ProductVariatons data i mean the list must be ['Red', 'Green']. I hope that i could made myself understood. -
Django. Display of an HTML element in the ckeditor editor
There is a task in ckeditor when adding an HTML div in the editor, how can I display the area (that the tag is "added" in this place)? <div data-content="menu" data-id="test-menu" data-type="extra">div-menu</div> Now I have it displayed like this I want it to look something like this How can this be done in Django? (so that styles are not applied to HTML, but only work in the editor) to insert custom HTML I wrote my plugin. Here is the code snippet that inserts the desired HTML html_menu = '<div data-type=\"extra\" data-content=\"menu\" data-id=\"'+menu+'\">div-menu</div>' editor.insertHtml(html_menu) -
Running Gunicorn alongside Daphne on Nginx
I have been following several different tutorials about how to set up gunicorn and daphne in parallel so that gunicorn can serve http to my django apps and daphne to my django channels app. However, I am now stuck on the welcome to nginx homepage and I cannot figure out what the problem is. supervisor.conf [program:example] directory=/home/user/example/example command=/home/user/envs/example/bin/gunicorn example.wsgi:application user=user autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/user/envs/example/bin/gunicorn-error.log [program:serverinterface] directory=/home/user/example/example command=/home/user/envs/example/bin/daphne -b 0.0.0.0 -p 8001 example.asgi:application autostart=true autorestart=true stopasgroup=true user=user stdout_logfile = /home/user/example/bin/gunicorn-error.log nginx/sites-availible/example.com upstream app_server { server http://unix:/run/gunicorn.sock fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://example.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; listen 443 ssl; server_name example.com www.example.com; # Let's Encrypt parameters ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location = /favicon.ico { access_log off; log_not_found off; } location / { try_files $uri @proxy_to_app; } location /ws/ { try_files $uri @proxy_to_ws; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location @proxy_to_ws { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } -
ho can i fix this ?IS this editor problem or some code error?
File "C:\Python\lib\site-packages\django\core\management_init_.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Python\lib\site-packages\django\core\management_init_.py", line 37, in load_command_class return module.Command() -
React and Nginx messing up urls when using axios, incorrect API calls
I'm running two applications on my device, one is django app hosted on apache localhost:8001 and second one is react app running on nginx localhost:8005. Also I'm using nginx as a proxy router, which is listening on port 80 and redirecting to backend if endpoint starts with /api and frontend if endpoint is /(anything). For example my domain is 'xyz.com'. Backend is running fine, but I'm getting big problem with React and axios. Axios calls api by domain like 'xyz.com/api/users/add/' and half of urls are working. But for few cases he is adding frontend url to axios request. For example 'xyz.com/edit-user/api/users/add/' and I have no idea why. Problem is 100% by the nginx or frontend. I have no clue why only for certain urls Axios is adding frontend url for API calls. Here is nginx config: server { listen 80; listen [::]:80; root /var/wwww/nginx; location /api { proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for; proxy_set_header Host $http_post; proxy_redirect off; #rewrite ^/api(.*) $1 break; proxy_pass http://127.0.0.1:8001/; } location / { #rewrite ^/web(.*) $1 break; proxy_pass http://127.0.0.1:8005/; } } server { listen 8005; server_name localhost; location / { root /home/ubuntu/Frontend/idom/build; index index.html index.htm; } } and here is auth.js: import axios from 'axios'; import { createMessage, … -
How to add addclass jQuery function in tab-pane html boostrap?
I have the following html structure <ul class="nav nav-pills ml-auto"> <li class="nav-item"> <a class="nav-link active" href="#revenue-chart" data-toggle="tab">Storico</a> </li> <li class="nav-item"> <a class="nav-link" href="#sales-chart" data-toggle="tab">Budget</a> </li> </ul> This tab is linked to the following tab-content: <div class="tab-content p-0"> <div class="chart tab-pane active" id="revenue-chart" style="position: relative; height: 300px;"> <canvas class=" w-100 " id="revenue-chart-canvas" height="300" style="height: 300px;"></canvas> </div> <div class="chart tab-pane " id="sales-chart" style="position: relative; height: 300px;"> <canvas class=" w-100 " id="sales-chart-canvas" height="300" style="height: 300px;"></canvas> </div> I want to create a jQuery function that give me the possibility to, when I click on the sales chart button the fuction add the following class attribute: <div class="chart tab-pane active " id="sales-chart" -
Django - rendering a zipped list in template
I have made a list in my django views that consists of two other lists. Now in my html, I want to render this in a table format. My views are as follows: z = [] dict_lyrics = {'question': [], 'answer': []} for word in user_word: x = lyrics_list_clean.index(word) y = user_word.index(word) flash = Flashcard.objects.get(owner=self.request.user, question=word) z.append(flash.answer) dict_lyrics['question'].append(lyrics_list_clean[x]) dict_lyrics['answer'].append(z[y]) context['question'] = dict_lyrics['question'] context['answer'] = dict_lyrics['answer'] context['dict_lyrics'] = dict_lyrics context['length'] = len(dict_lyrics['question']) context['combined'] = list(zip(dict_lyrics['question'], dict_lyrics['answer'])) So the combined list gives me something like this: combined = [[question1, answer1], [question2, answer2], etc.] In other words, the relevant questions and answers are grouped together. But how do I render it correctly in my template? The following is the table I want to have: <table> <thead> <tr> <td>Question</td> <td>Answer</td> </tr> </thead> <tbody> {% for item in lyrics %} <tr class='lyrics-table'> <td>{{item}}</td> <td> {% if item in user_flash %} <!-- here I need to show the corresponding answer for the relevant question--> {% else %} <!-- other code not relevant here --> {% endif %} </td> </tr> {% endfor %} </tbody> </table> </div> But I can't get it right. The only way I have found to render the list in my template is by …