Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create collapsible cards in bootstrap in django template?
I have a table of these collapsible cards with dynamic content in them. The code I have taken from bootstrap looks like this: <p> <a class="btn btn-primary" data-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button> </p> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1"> <div class="card card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2"> <div class="card card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. </div> </div> </div> </div> Problem But as you can see, each collapse is controlled by this attribute multiCollapseExample1. In my django template, when I use this, on clicking any of the close button, only the first card collases because it has a static value of 1. How can I give it a dynamic value so every card opens and closes correctly? Reason I am asking is because … -
Please help for this error on Pycharm.Useing django
I'm trying to make a website using django,and my next step is run manage.py,to create superuser,but when I input Username,Email address,password,then press Enter,the IDE(Pycharm) feedback an Commanderror: manage.py@education > createsuperuser "D:\PyCharm 2019.1\bin\runnerw64.exe" E:\pythonproject\education\Scripts\python.exe "D:\PyCharm 2019.1\helpers\pycharm\django_manage.py" createsuperuser E:/pythonproject/education Tracking file by folder pattern: migrations Username: admin Email address: 976413993@qq.com Warning: Password input may be echoed. Password: 12345678 Warning: Password input may be echoed. Password (again): 12345678 This password is too common. This password is entirely numeric. Bypass password validation and create user anyway? [y/N]: y CommandError: '' value has an invalid date format. It must be in YYYY-MM-DD format. I need your help! I try to Google this problem,but I didn't find any useful information。Forgive my broken English, because I come from China, English level is not too high。 -
How do I store data in a csv format to a database then manipulate that data in a python's django web framework
I am scraping tweets from twitter and saving them in a csv format after cleaning them. I want to store the data in a SQL database, any help? -
Setting up Django with docker
I am tried setting up django using docker but I am getting this error. I have set up my Dockerfile and the docker-compose.yml. docker-compose.yml version: "3" services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY . /code/ This is the error I am getting. Watching for file changes with StatReloader web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/threading.py", line 917, in _bootstrap_inner -
Django CMS Show_Menu Example wont work for multi-level menu
base.html: <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> {% show_menu 0 1 100 100 "menu.html" %} </ul> </div> menu.html: {% load i18n menu_tags cache %} {% for child in children %} <li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}{% if child.children %} dropdown{% endif %}"> <a {% if child.children %}class="dropdown-toggle" data-toggle="dropdown"{% endif %} href="{{ child.attr.redirect_url|default:child.get_absolute_url }}"> <span>{{ child.get_menu_title }}</span>{% if child.children|length %}<span class="caret"></span>{% endif %} </a> {% if child.children %} <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu"> {% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %} </ul> {% endif %} </li> {% if class and forloop.last and not forloop.parentloop %}{% endif %} {% endfor %} dropdownmenu.html: {% load i18n menu_tags cache %} {% for child in children %} <li {% if child.children %}class="dropdown-submenu"{% else %} {% endif %}> <a tabindex="-1" href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }}</a> {% if child.children %} <ul class="dropdown-menu"> {% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %} </ul> {% endif %} </li> {% endfor %} Submenu doesn't show up -
ModuleNotFoundError: No module named 'mysite.setting' error when start debugging
When i try to start debugging my django project, pycharm raises the error /home/vinc/miniconda3/bin/python /home/vinc/Downloads/pycharm-2018.3.4/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 37987 --file /mnt/7E8A3C928A3C4943/MEGASync/UNI/LM/UNIMORE/3/AWM/mysite/browse/views.py pydev debugger: process 8451 is connecting Connected to pydev debugger (build 183.5429.31) Traceback (most recent call last): File "/home/vinc/Downloads/pycharm-2018.3.4/helpers/pydev/pydevd.py", line 1741, in <module> main() File "/home/vinc/Downloads/pycharm-2018.3.4/helpers/pydev/pydevd.py", line 1735, in main globals = debugger.run(setup['file'], None, None, is_module) File "/home/vinc/Downloads/pycharm-2018.3.4/helpers/pydev/pydevd.py", line 1135, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/home/vinc/Downloads/pycharm-2018.3.4/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/mnt/7E8A3C928A3C4943/MEGASync/UNI/LM/UNIMORE/3/AWM/mysite/browse/views.py", line 4, in <module> from browse.forms import * File "/mnt/7E8A3C928A3C4943/MEGASync/UNI/LM/UNIMORE/3/AWM/mysite/browse/forms.py", line 3, in <module> from .models import Comment, Attraction, Image, AttractionTag File "/mnt/7E8A3C928A3C4943/MEGASync/UNI/LM/UNIMORE/3/AWM/mysite/browse/models.py", line 3, in <module> from portal.models import Profile File "/mnt/7E8A3C928A3C4943/MEGASync/UNI/LM/UNIMORE/3/AWM/mysite/portal/models.py", line 1, in <module> from django.contrib.auth.models import User File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/vinc/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/vinc/miniconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return … -
How to insert variable results into calls in Django Template Language
In Django I'm trying to make a generic "confirm action" call which I can easily pass the final address to, but I'm having difficulty inserting a variable in the link: <a href="{% url 'view_do_confirm_action' 'url view_delete_object {{ object.object_name }}' %}"> Delete this object </a><br> (In case it's not clear, the argument to view_do_confirm_action is the url to be followed if the user confirms.) "{{ object.object_name }}" is not being resolved at the right time here - any advice? Thank you scan -
Is it possible to add multiple records to a single model via add?
I have a model in Django class UserData(models.Model): name = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='images/', null=True, blank=True) info = models.CharField(max_length=100, null=True, blank=True) encodedata = models.TextField(default={}) processedflag = models.BooleanField(default=False) I want to implement addition of multiple rows into this table from Django Admin. i.e the user can add multiple rows for UserData from a sinle page. I want to know if this is possible ? I have to inherit the InlineModel class, however in this scenrio i dont have another parent Model that the userData belongs to. -
Scraper - word frequency and names
django rest api should return: 10 most common words with their number available at the address / stats / and The 10 most common words with their numbers per author available under the address / stats / / This script finds the addresses of subpages with articles and collect the data from them. how to add a functions to the scraper that will return these words? import requests from bs4 import BeautifulSoup as bs from selenium import webdriver url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent' : 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome() for article in all_links: d.get(article) soup = bs(d.page_source, 'lxml') [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])] visible_text = soup.getText() # here I think you need to consider IP rotation/User-Agent changing try: print(soup.select_one('.post-title').text) except: print(article) print(soup.select_one('h1').text) break # do something with … -
Returninig first_name and last_name in a dropdown
I have a dropdown of usernames, but I would like instead first_name + Last_name from the user model. I have been trying to return these in the model in various ways, any idea where I've gone wrong? def __str__(self): # return self.assigned_to.first_name # return str(self.firstname)+ '-' +str(self.lastname) # return u'%s %s' % (assigned_to.first_name, self.last_name) # return str(self.user.first_name) # return str(self.location_name)+ '.' +str(self.location_sub_name) In my model: assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='assigned_to', on_delete = models.PROTECT, related_name='assigned') In my htmlform: <div class="col col-md-4" style="color:white;">{{ form.assigned_to|add_class:"col-md-12"|append_attr:"placeholder:To"}}</div> -
Update model (database) from template
I have few models: models.py class Posudba(models.Model): nazivKnjige = models.ForeignKey(Knjiga, on_delete=models.CASCADE, null=False) nazivProdavaca = models.ForeignKey(User, on_delete=models.CASCADE, null=False) nazivKupca= models.ForeignKey(Kupac, on_delete=models.CASCADE, null=False) datum = models.DateField(null=False, blank=False) kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.nazivKnjige) + ', ' + str(self.nazivProdavaca) + ', ' + str(self.nazivKupca) + ', ' + str(self.Datum) class Knjiga(models.Model): naziv = models.CharField(null=False, blank=True, max_length=120) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) datumObjave = models.DateField(null=True, blank=False) izdanje = models.CharField(null=True, blank=True, max_length=120) slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.naziv) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) + ', ' + str(self.slika) UnosPosudbe.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="{% url 'UnosPosudbe' %}" method="post" enctype=multipart/form-data> {% csrf_token %} <table border="1"> {{forma.as_table}} </table> <input type="submit" name=""> </form> </body> </html> forms.py class PosudbaForma(forms.ModelForm): class Meta: model = Posudba fields = '__all__' Views.py @login_required def UnosPosudbe(request): if request.method == 'GET': forma = PosudbaForma() elif request.method == 'POST': forma = PosudbaForma(request.POST,request.FILES) if forma.is_valid(): forma.save() return redirect('pregledPosudbe') return render(request, 'unosPosudbe.html', {'forma':forma}) urls.py path('UnosPosudbe/',views.UnosPosudbe, name='UnosPosudbe'), Is it possible that on button submit in "UnosPosudbe.html" I do those things: Check if field "kolicina" from model "Knjiga" is higher or equal to field "kolicina" from model "Posudba" (He can rent a … -
writable double nested serializer
i am trying to create a nested serializer using DJANGO REST FRAMEWORK. but i don't know how to use create update methods in serializer.py. iam allready created models and some working serializers. models.py class JournalEntry(models.Model): CHOICES = ( ('SALES', 'Sales'), ('PURCHASE', 'Purchase'), ('DEBITNOTE', 'DebitNote'), ('CREDITNOTE', 'CreditNote'), ('COSTOMER_RECIEPT', 'CustomerReceipt'), ('SUPPLIER_PAYMENT', 'SupplierPayment'), ('EXPENSE', 'Expense'), ('JOURNAL', 'Journal'), ) date = models.DateField() transaction_type = models.CharField(max_length=15, choices=CHOICES, default='SALES',null=True, blank=True) description = models.CharField(max_length=15,null=True, blank=True) @property def child(self): return self.journalitem_set.all() class JournalItem(models.Model): journal_entry = models.ForeignKey('core.JournalEntry', on_delete=models.CASCADE) account = models.CharField(max_length=15, choices=CHOICES, default='SALES',null=True, blank=True) partner = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) debit_amount = models.DecimalField(max_digits=15,decimal_places=2,null=True, blank=True) credit_amount = models.DecimalField(max_digits=15,decimal_places=2,null=True, blank=True) class CustomerReceipt(models.Model): reciept_no = models.IntegerField() journal_entry = models.ForeignKey(JournalEntry, on_delete=models.CASCADE, null=True, blank=True) serializer.py, some required serializers are already did. class JournalItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = JournalItem fields = [ 'id','journal_entry', 'account','partner', 'debit_amount','credit_amount' ] read_only_fields = ('journal_entry',) class JournalEntrySerializer(serializers.ModelSerializer): child = JournalItemSerializer(many=True) class Meta: model = JournalEntry fields = ('id','date','transaction_type','description','child') def create(self, validated_data): albums_data = validated_data.pop('child') musician = JournalEntry.objects.create(**validated_data) for album_data in albums_data: JournalItem.objects.create(journal_entry=musician, **album_data) return musician def update(self, instance, validated_data): child = validated_data.pop('child') # albums = (instance.child).all() # albums = list(albums) instance.date = validated_data.get('date', instance.date) instance.transaction_type = validated_data.get('transaction_type', instance.transaction_type) instance.description = validated_data.get('description', instance.description) instance.save() keep_choices = [] for choice … -
how to change the value of some field in django by based on the value of other field of another model?
Here i have two models.With these models i want to make the value of current_balance in Ledger model dynamic.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field then the value of current_balance should be (opening_balance - amount_to_pay).If not the expense form the the current_balance will be the same as opening_balance.how can i do that ? models.py class Ledger(models.Model): name = models.CharField(max_length=200) account_number = models.CharField(max_length=250,unique=True) opening_balance = models.FloatField(default=0.0) amount_to_pay = models.OneToOneField('Expense',on_delete=models.CASCADE) account_type = models.CharField(max_length=200) current_balance = models.FloatField(default=0.0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='name') class Expense(models.Model): pay_from = models.CharField(max_length=200) payment_option = models.ForeignKey(Ledger, on_delete=models.CASCADE) amount_to_pay = models.FloatField(default=0.0) expense_date = models.DateField(default=datetime.date.today) expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = AutoSlugField(unique_with='id', populate_from='expense_type') -
How secure is django's cleaned_data (XSS, CSRF, SQL Injections, HTML/JS Injections, etc)?
Are all these risk handled by django's cleaned_data fields or do I need to implement additional security measures like strip tags? -
How to display friend requests using Django-friendship
I'm trying to implement friendship model in my django project using django-friendship. How do I display the friend requests in the template and what should I pass through the view. I tried with a custom Friend model but failed to implement hence changed to prebuilt django-friendship model. I have created a view with the required arguments to be passed using the guide given on the github page. The friend list display works but the friend request display doesn't. My view: @login_required def friend_list(request,username,pk): user = get_object_or_404(User,username=username,pk=pk) friend_requests = Friend.objects.requests(request.user) friends = Friend.objects.friends(user) sent_requests = Friend.objects.sent_requests(request.user) args = {'user':user, 'friend_requests':friend_requests, 'friends':friends, 'sent_requests':sent_requests} return render(request,'friend_list.html',args) My template: {% if friend_requests %} {%friend_request in friend_requests %} <h3>{{ friend_request.user.username }} </h3> <a href="{% url 'add_friend_request' friend_request.user.pk True %}" style="display: flex"> <button type="button" class="btn btn-outline-dark">Confirm</button> </a> <a href="{% url 'add_friend_request' friend_request.user.pk False %}"> <button type="button" class="btn btn-outline-dark">Reject</button> </a> {% endfor %} {% else %} <h5>No Friend Request</h5> {% endif %} I expected that this would display all the friend request but it is not displaying anything. The webpage is blank -
Using Django built in forms and functionality to allow CRUD for anon and registered users
I need to expose Django admin forms to anon or registered users. It seems quite overhead to reproduce the same forms that are found from Django Admin site. For example creating instances for models with foreign keys to other models and to post both at the same time. You need to built all the UI functionality such as Add another, Remove javascript and also table view etc. Can't figure out why since Django seems to have a solution? Is it possible to reuse built in forms? -
Get google map marker ID in Jquery
I am not able to get value for markers[this.id].accId inside $.slidePanel.show. The value is available when I try to log it before $.slidePanel.show. I am new to jQuery and Javascript, any help is highly appreciated. google.maps.event.addListener(markers[i], 'click', function() { accId = markers[this.id].accId; console.log(markers[this.id].accId); map.setZoom(12); map.setCenter(markers[this.id].getPosition()); $.slidePanel.show({ url: "{% url 'route-add-account' view.kwargs.pk markers[this.id].accId %}", settings: { method: 'GET' } }); }); -
How to pass values from html to python
I have a 4 buttons on first page which put me through to another page(All those 'buttons' are connected to database in mysql) and on this second page I have some data from mysql tables which I wanna display depending on what I have chosen in the first page. Right now I just display everything I have and I don't really know how to change that. I was looking for solutions but none worked. views.py def kategorie_list(request): obj = Kategorie.objects.all() context ={'obj': obj} return render(request, "kategorie/lista.html", context) def uslugodawcy_list(request): obj = Uslugodawcy.objects.all() context ={'obj': obj} return render(request, "uslugodawcy/uslugodawcy_lista.html", context) first html page {% for Kategorie in obj %} {{Kategorie.idkategorie}} . {{Kategorie.nazwakategorii}} {% endfor %} second {% for Uslugodawcy in obj %} {{Uslugodawcy.iduslugodawcy}} . {{Uslugodawcy.nazwa_uslugodawcy}} {% endfor %} -
ImportError: cannot import name
Why can’t I import the Provider model from the providers app into the payments app? Traceback (most recent call last): File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/work_projects/startapp/midgard/payments/models.py", line 71, in <module> class Invoice(models.Model): File "/home/m0nte-cr1st0/work_projects/startapp/midgard/payments/models.py", line 73, in Invoice from providers.models import Provider File "/home/m0nte-cr1st0/work_projects/startapp/midgard/providers/models.py", line 9, in <module> from products.models import Category File "/home/m0nte-cr1st0/work_projects/startapp/midgard/products/models.py", line 180, in <module> class Product(models.Model): File "/home/m0nte-cr1st0/work_projects/startapp/midgard/products/models.py", line 217, in Product from providers.models import Provider ImportError: cannot import name Provider -
How to find that the user that has login is not a new user?
I have given users to login in the system using google login but every time the user logins using google login, it always redirects to the same location, but I want if the user is not new then it should be redirected to the another page. Until now every time the user logins using google login it redirects the user to the page fileupload. LOGIN_REDIRECT_URL = 'fileupload' But I am not able to redirect the old user to another location. Login Redirect Url LOGIN_REDIRECT_URL = 'fileupload' html form {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="modal fade" id="Modal" aria-labelledby="ModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="Label">User Profile</h5> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="{% url 'uploadprofile' %}" method="POST"> {%csrf_token%} <div class="form-group"> <input type="hidden" name="username" class="form-control" id="username" value="{{user.username}}" style="font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif" required> </div> <div class="form-group"> <label for="contact_no">Contact Number:</label> <input type="tel" name="contact_no" class="form-control" id="contact_no" placeholder="Contact no." style="font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif" required> </div> <div class="form-group"> <label for="dept_no">Department Number:</label> <select id="dept_no" name="dept_no" class="form-control" style="font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida … -
Working with JSON in Django. Add data and parse iy in template
I have a code for adding data to json: for pair in pairs: for timeframe in timeframes: klines = Kline.objects.filter(timeframe=timeframe, pair=pair, closed = True).order_by('-open_time')[:10] list_pair_data = [] for kline in klines: kline_data = [] kline_data.append(kline.price_open) kline_data.append(kline.price_close) list_pair_data.append(kline_data) pair_data = json.dumps( {'pair':pair.title, 'timeframe':timeframe.title, 'data': list_pair_data}) all_data.append(pair_data) return render(request, 'indicators/indicators_list.html',{'all_data':all_data}) And i show it in template: {% for item in all_data %} <p>{{ item }}</p> {% endfor %} And what I see in page: {"pair": "BTCUSDT", "timeframe": "1h", "data": [[7654.09, 7660.98], [7619.18, 7654.96], [7636.3, 7620.76], [7627.8, 7636.28], [7714.04, 7628.43], [7666.53, 7715.02], [7815.42, 7666.53], [7901.2, 7815.42], [7906.9, 7901.69], [7880.55, 7907.71]]} {"pair": "BTCUSDT", "timeframe": "4h", "data": [[7627.8, 7660.98], [7901.2, 7628.43], [7939.96, 7901.69], [7802.95, 7939.6], [7881.19, 7802.31], [7895.35, 7882.22], [7904.48, 7895.17], [7966.44, 7904.87], [7890.62, 7966.45], [7847.92, 7890.49]]} {"pair": "BTCUSDT", "timeframe": "1d", "data": [[7904.48, 7628.43], [7937.16, 7904.87], [8147.94, 7938.15], [7257.32, 8148.48], [7355.28, 7257.45], [7868.67, 7355.26], [8169.08, 7866.59], [7945.26, 8169.87], [7795.62, 7947.56], [6968.24, 7790.71]]} {"pair": "BTCUSDT", "timeframe": "15m", "data": [[7637.82, 7649.93], [7655.54, 7638.74], [7661.45, 7657.92], [7627.58, 7660.98], [7633.5, 7627.65], [7638.67, 7632.93], [7654.09, 7640.39], [7668.52, 7654.96], [7648.13, 7672.28], [7595.65, 7648.11]]} {"pair": "ETHBTC", "timeframe": "1h", "data": [[0.031903, 0.031785], [0.03195, 0.031903], [0.031843, 0.031958], [0.031952, 0.031843], [0.03189, 0.031953], [0.031696, 0.031879], [0.031659, 0.03169], [0.03198, 0.031659], [0.031966, 0.03198], [0.031881, 0.031964]]} {"pair": "ETHBTC", "timeframe": … -
Virtual environment packages installation error
I am working on AWS Console Ubuntu server.First of all pip default packages are not installing with pip and whenever we try to install packages in virtual environment,those packages are installing in global.Those packages are not showing while we list pip using pip list command. I tried several times by uninstalling and installing virtual environment as well as pip,but somehow all packages are installing in global not in virtual environment. Expected output is that Pip will list all the installed packages in virtual environment. -
Django: put offline a post after an event
I'm trying to put offline the posts after an event, a definite date. I've developed a simple model for test my aim and inside the model I've put a function(named is_expired) that, ideally, must define if a post is or not is online. Below there is the model: from django.db import models from django.utils import timezone import datetime class BlogPost(models.Model): CHOICHES = ( ("Unselected", "Unselected"), ("One Month", "One Month"), ("One Year", "One Year"), ) title = models.CharField( max_length=70, unique=True, ) membership = models.CharField( max_length=50, choices=CHOICHES, default="Unselected", ) publishing_date = models.DateTimeField( default=timezone.now, ) def __str__(self): return self.title @property def is_future(self): if self.publishing_date > datetime.datetime.now(): return True return False @property def is_expired(self): if self.membership == "One Month": def monthly(self): if publishing_date + datetime.timedelta(days=30) >= datetime.datetime.now(): return True if self.membership == "One Year": def yearly(self): if publishing_date + datetime.timedelta(days=365) >= datetime.datetime.now(): return True return False class Meta: ordering = ['-publishing_date'] For show a list of all expired posts I use this simple template: {% for p in posts_list %} {% if p.is_future or p.is_expired %} <div class="container my-4 bg-primary"> <h3><a class="text-white" href="{{ p.get_absolute_url }}">{{ p.title }}</a></h3> <h5>Data di pubblicazione: {{ p.publishing_date|date:"d - M - Y | G:i:s" }}</h5> {% if p.is_expired %} <p>Expired? … -
Correctively Django query datetime for data/object one hour from now
i am filtering Django query to getting updatetime last one hour from now, The model has a DateTimeField. this is for getting all updatetime that update one hour ago, i've tried using datetime.now() - timedelta(hours = 1), and using range(min,max) onehours = datetime.now() - timedelta(hours=1) queryset = TbDevice.objects.filter(updatetime__gte=onehours).order_by('-updatetime') this codes should return updatetime from last hour ago, but actually the queryset return all data with "date" is today -
Error overriding get method in Django Rest
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset method and the get method. I could make the get_queryset() method work, but the get() method isn't working (I'm assuming some kind of syntax error). The working code : class VehicleList(ListAPIView): permission_classes = (AllowAny,) serializer_class = FleetVehicleSerializer def get_queryset(self): domain = self.request.META.get('HTTP_DOMAIN', None) if domain is None: raise Exception("Domain is missing in request header") qs = FleetVehicle.objects.using(domain).all() return qs Not working code: class VehicleList(ListAPIView): permission_classes = (AllowAny,) serializer_class = FleetVehicleSerializer def get(self, request): domain = self.request.META.get('HTTP_DOMAIN', None) if domain is None: raise Exception("Domain is missing in request header") vehicles = FleetVehicle.objects.using(domain).all() return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' ) The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?