Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the correct way to get websocket message do display in django template using django channels?
I'm trying to display stock market data from a third party api in realtime using channels and celery. I'm using celery to get data from the api and channels to receive and send the data to the client. My issue is that the data isn't rendering in the template and my python and javascript aren't showing any errors so I have no idea what's wrong. Help would be appreciated. ignore commented out code in snippets. tasks.py import requests from celery import shared_task from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() @shared_task def get_stock_info (): # request.session['sym'] = sym payload = {'symbol': 'nvda'} # r = requests.get('https://api.twelvedata.com/time_series?&interval=1min&apikey=177206d91bf247f2a09d14ee8f4a4f16', # params=payload) r = requests.get('https://api.twelvedata.com/price?apikey=177206d91bf247f2a09d14ee8f4a4f16', params=payload) res = r.json() price = res['price'] async_to_sync(channel_layer.group_send)('stocks', {'type': 'send_info', 'text': price}) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer class StockConsumer(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('stocks', self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard('stocks', self.channel_name) async def send_info(self, event): msg = event['text'] await self.send(msg) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="#price">{{ text }}</p> <p id="description">{{ res.Description }}</p> <script> var socket = new WebSocket('ws://localhost:8000/ws/stock_info/'); socket.onmessage = function(event){ var price = event.data; document.querySelector('#price').innerText = price; } </script> … -
django.core.exceptions.ImproperlyConfigured the issue is caused by circular import
I am doing simple API project in the starting I did not got the error but now circular import error what is the actual error in my coding does it need anything to add in the settings.py or in urls.py and what are the major causes of the error -
In python Django I want to execute two statements on if else that if email is taken show message if employee id is taken show message
I have a html registration form where I am displaying if any username or email exists or not so if it exists then display username is taken and if email exists it will display email is taken but the problem is even if I give email in the email field in the html form it says username is taken but not email I tried elif statement it didn't worked the username is taken is working perfectly but not email. If anyone knows please help This is my views.py def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: if User.objects.filter(username = username).first(): messages.success(request, 'Username is taken.') return redirect('/register/') if User.objects.filter(email = email).first(): messages.success(request, 'Email is taken.') return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request , 'register.html') -
How to match the question id in the nested table to the main table
const questionsData = useSelector((state) => state.questionsData) useEffect(() => { dispatch(getQuestionsData()) }, []) const columns = [ { title: 'Question No', dataIndex: 'key', key: 'question_no', }, { title: 'Scenario', dataIndex: 'description', key: 'description', width: '25%', }, { title: 'Total Marks', dataIndex: 'qn_total_mark', key: 'qn_total_mark', }, ] const expandedRowRender = () => { const columns = [ { title: 'Part Description', dataIndex: 'part_desc', key: 'key', }, ] return ( <Table columns={columns} dataSource={questionsData} /> ) } return ( <> <Table columns={columns} dataSource={questionsData} expandable={{ expandedRowRender }} /> </> ) } for question in questions: if question.question_id not in res: res[question.question_id] = { "key": question.question_id, "question": question.question, "description": question.description, "qn_total_mark":question.qn_total_mark, "part_desc": question.part_desc, } what i am trying to do is create a nested table to store the part_desc , however my nested table right now gives back all the part desc regardless of the question number,is there a way to store the part description matching the question number respectively -
how to print in django after filtering data using django-filters user input
i have a module children with 4 fields a. child _id ( pk) b. first_name c. middle_name d. last_name i have used django-filter app now I want the user filter the data and by clicking the button and get print of the filter data i have searching on internet tried installing xhtmltopdf, weasypdf but of no use .I am new to it. is there any way I can print report based on filteration done by user -
How to update django settings in AppConfig ready funciton or other way?
now i have a code: class BlueappsAccountConfig(AppConfig): name = 'myapps' verbose_name = 'myapps' def ready(self): settings.configure(MYAPPS_CONFIG={"APP_CODE": "appcode"}) exist_middleware = settings.MIDDLEWARE add_my_middleware = ("myapps.middleware.MyMiddleware",) + exist_middleware settings.configure(MIDDLEWARE=add_my_middleware ) i have my middleware and some DIY configuration,i need to update django settings so that MyMiddleware to work and update some myapps config to settings,but i have error: Traceback (most recent call last): File "C:\python\py368\lib\threading.py", line 916, in _bootstrap_inner self.run() ... app_config.ready() File "F:\account_django_test\myapps\MyAppConfig.py", line 12, in ready settings.configure(MYAPPS_CONFIG={"APP_CODE": "appcode"}) File "F:\account_django_test\venv\lib\site-packages\django\conf\__init__.py", line 107, in configure raise RuntimeError('Settings already configured.') RuntimeError: Settings already configured. what should i do if i want to edit settings on before app installed or edit it on settings not configured moment? -
Javascript not reflected on Django Project
I am trying to show a carousel box/ banner in my page but I am having an issue with the JavaScript it is not appearing. I have borrowed the HTML/ CSS and JS from https://codepen.io/StephenScaff/pen/egOedp/ and I am trying to apply the same concept to my Django Project. I have added the HTML in a file called projects.html and in the base file I have linked a new CSS file simple.css with css format which in my Django project project working but my issue is when I tried to implement to JS file here is what happened in my trials. Also the next and previous buttons are not showing Trial 1 I have added under the HTML file projects.html but the js code appeared under the banner image like normal text {% block script %} Added the JS code... {% endblock script %} Trial 2 in my base.html file I created a new file called simple.js and added in the static folder and linked it but still it didn't reflect on the server. <script src="{% static 'simple.js' %}"></script> My question What am I doing wrong causing this confusion and how to implement the JS code for this simple banner to … -
module 'django.http.request' has no attribute 'user'
I want to save author automatically in article model,i searched a bit and came across these references: Here and Here Each of them and other references on the Internet said that to save the user field, the save_mode method should be used in the admin.py file. Then I wrote this code for it in admin.py: class ArticleAdmin(admin.ModelAdmin): list_display = ('author','simple_created','slug','title_en','views','status') search_fields = ('desc_en','desc_fa','title_en','title_fa','body_en','body_fa') ordering = ['-created'] def save_model(self, request, obj, form, change): obj.author = request.user obj.save() return super().save_model(request, obj, form, change) But the problem is that I don't have access to the User through request and I get the following error: AttributeError at /admin/blog/article/10/change/module 'django.http.request' has no attribute 'user' I think Django uses django.http.request by mistake but I did not import it at all Django version : 3.2 Python version : 3.8.5 How can I solve this problem and access the user? -
I have installed requests but I still get ModuleNotFoundError: No module named 'requests' (Django)
If I do pip3 install requests I get (Requirement already satisfied), If I do pip install request I get (Requirement already satisfied), python3.9 -mpip install requests (Requirement already satisfied), It seems like I have requests already installed but still I get "ModuleNotFoundError: No module named 'requests'" I'm having a file with this code in my django project import requests def client(): credentials = {"username": "admin", "password": "hampus123"} response = requests.post("http://127.0.0.1:8000/api/rest-auth/login/", data=credentials) print("Status Code:" , response.status_code) response_data = response.json() print(response_data) if __name__ == "__main__": client() -
How does Django change Boolean values dynamically?
Hi how do I approach telling django : --> Upon user submitting a Post, and click is True --> Turn other Post False (there can only be one post that is true) -
How to set value to django-select2 field Programmatically (on button click) using javascipt?
In my django app I have a WorkerModel and a ProvinceModel, each worker has a province_id field. I have define a form for Worker using ModelSelect2Widget (django_select2) for province_id. I want to know how to set a value to province_id field using javascript. The idea is that when a button is clicked we make an ajax request getting the id and name of the province and I want to set the value of province_id to the province id I just got from django_select2.forms import ModelSelect2Widget class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(), search_fields=['des_prov__icontains'], attrs={'style': 'width: 100%;'}), } in the template <script> //on a button click a want to set the value of province_id $(document).ready(function () { $('#id_province_id').djangoSelect2({ placeholder: 'Seleccione una opción', escapeMarkup: function (markup) { return markup; }, language: { noResults: function () { return "No se encuentran resultados."; } } }); }); </script> -
Progress <input type=“file”> to other form when submit is pressed
This all works fine but what i want to do is have the name of the file i was uploading stored in a hidden input type so when i submit my form with text fields,the name of the image can be submitted to the database. I have noticed that when i submit my main form to database, the image has been saved into the database. I am able to save it in a temporary folder named "media". However, whenever I edit the form, the image cannot be retrieve anymore My question is how do i pass data of the uploaded file to my other form? This is my newclaim.html (Form which submit the receipt) <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field"> </div> </form> This is my existingclaims.html (Form which retrieve the receipt) <form method="POST" action="/editclaims/{{claims.id}}" enctype="multipart/form-data"> <div> <input id="receipt" type="file" value="receipt" hidden> <label for="receipt"> {{ claims.receipt }} </label> </div> </form> This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins.save() return render(request, 'Login/newclaim.html/', {'user':user}) # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) … -
Dynamically add HTML items to the right of previous item instead of below
I'm sure this is an amateur question, but I am having difficulty figuring out how to dynamically add html items to the right(same horizontal level) inside of my div. When I add a new Label it adds below the previous label I added. How do I place the new Label to the right of the previous label I added to my webpage? My javascript: <script> $(document).ready(function(){ $("#comp").click(function (e){ event.preventDefault() $('#items').append('<label>My Label</label>); }); }); </script> My html: <div id = "items"> </div> <input type="button", name = "comp" value = "Compare" id="comp"></input> -
Python: unsupported format character ''' (0x27) at index 350
I've got this error using the MySQL db backend for django. The query I'm trying to execute (it worked perfectly with MariaDB connector): cursor.execute("SELECT a.*, COALESCE( NULLIF(a.aa_change_ref_gene, '.'), NULLIF(a.gene_detail_ref_gene,'.') ) AS variant, b.*, c.* FROM `db-dummy`.specimen_genome_data c JOIN `db-dummy`.genome_info a ON a.record_id = c.genome_id JOIN `db-dummy`.specimen_data b ON b.record_id = c.specimen_id WHERE a.gene_name LIKE concat(?, '%') ORDER BY a.gene_name LIMIT 30", (gene,)) What I've tried: Basically replacing the '%' for "%" and '%%' Then I am getting this error for the "%" case: Exception Type: TypeError Exception Value: not all arguments converted during string formatting And this error for the '%%' case: Exception Type: ProgrammingError Exception Value: not all arguments converted during bytes formatting Exception Location: /home/prime/.env/intervar/lib/python3.6/site-packages/MySQLdb/cursors.py in execute, line 203 -
SQLAlchemy optional ForeignKey
In SQLAlchemy.orm I have the following class: class Table(Base): __tablename__ = 'table' id = Column(Integer, primary_key=True) src = Column(Integer, ForeignKey('other.id')) dst = Column(Integer, ForeignKey('other.id')) source = relationship("Other", foreign_keys=[src]) destination = relationship("Other", foreign_keys=[dst]) I want to make the src and source optional which means those records could be empty in the table. In Django's ORM, I used to make a model field optional by using blank=True and null=True like: src = models.ForeignKey(Other, blank=True, null=True) There is a default parameter for each column in SQLAlchemy as well. I tried: src = Column(Integer, ForeignKey('other.id'), default=None) But it doesn't work. -
ValueError: Cannot use None as a query value django ajax
I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error. view: def load_brand(request): if request.is_ajax(): term = request.GET.get('term') brand = Brand.objects.all().filter(brand__icontains=term) return JsonResponse(list(brand.values()), safe=False) ajax: $('#id_brand').select2({ ajax: { url: '/brand/ajax/load-brand/', dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.brand}; }) }; } }, minimumInputLength: 1 }); -
I finished AWS web service and test to enter domain web site and this error message popped up in chrome developer tool
this is the architecture used in AWS how I configured AWS VPC VPC’s private ip range : 172.31.0.0/16 1 public subnet 3 private subnets how I configured AWS route table private subnet route table configuration ->172.31.0.0/16 local ->0.0.0.0/0 NAT gateway -included subnets → frontend private subnet / backend private subnet / RDS private subnet total 3 private subnets included in private route table public subnet route table → 172.31.0.0/16 local → 0.0.0.0/0 internet gateway → public subnet that contains Application Load Balancer / bastion host ec2 / NAT gateway total 1 public subnet included in public route table How I configured Application Load Balancer internet facing connected instance : frontend ec2 instance in private subnet then all the configuration done I entered domain web site to test it then I confronted with this error [Vuetify] [UPGRADE] ‘v-content’ is deprecated, use ‘v-main’ instead. console.ts:34 ***found in *** —> VMain *** VApp*** *** App*** *** Root*** POST ‘http://ec2-xxx-xxx-xxx-xxx.us-west-1.compute.amazonaws.com:8000/Product/item_list’ xhr.js:177 !net::ERR_CONNECTION_REFUSED! !Uncaught (in promise) Error:Network Error createError.js:16 *** at t.exports (createError.js:16)*** *** at XMLHttpRequest.d.onerror (xhr.js:84) !*** POST ‘http://ec2-xxx-xxx-xxx-xxx.us-west-1.compute.amazonaws.com:8000/Bag/bag_count’ xhr.js:177 net::ERR_CONNECTION_REFUSED Uncaught (in promise) Error: Network Error createError.js:16 *** at t.exports (createError.js:16)*** *** at XMLHttpRequest.d.onerror (xhr.js:84)*** my question is Q. what is the problem … -
Django images not showing up
I've spent hours looking for a solution, figured I would post for myself. Django images won't show. models.py: class Item(models.Model): ... image = models.ImageField(default='default.jpg', upload_to='item_pics') urls.py from django.urls import path from . import views from .views import ItemListView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', ItemListView.as_view(), name="site-home"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html-file {% extends "ui/base.html" %} {% load static %} {% block content %} <ul> {% for item in items %} <li> <p><img src="{{ item.image.url }}"></p> <br> </li> {% endfor %} </ul> {% endblock content %} It shows up like this: When I copy image address, I get http://localhost:8000/media/default.jpg -
How to extend base.html in django
Quick question, while extending base.html to my other pages in my django project the base.html page takes over and i can only see the base.html page. i only see the other pages/templates when i remove the extension. what am I doing wrong? I realise this might be a stupid question to some but just help out if you can. Thank you -
Permission denied in jailshell
I'm installing my Django project on my hosting but when I want to activate the virtual environment the console marks this error: jailshell: .virtualenv/bin/activate: Permission denied. And I don't know how to fix it, I'm using it through the cpanel. Thanks -
Not Found: /particles.json
I am trying to build a forum with Django. I want to use an animated background with particles.js. When I write this code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Particles login</title> <link rel="stylesheet" href="style.css"> </head> <body> <div id="particles-js"> </div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', 'particles.json', function(){ console.log('particles.json loaded...'); }); </script> </body> </html> and run it on live server I get what I want. However, I tweaked the code for Django: <!DOCTYPE html> <html lang=en> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> </head> <body> {% include 'snippets/base_css.html' %} {% include 'snippets/header.html' %} <!-- Body --> <style type="text/css"> .main{ min-height: 100vh; height: 100%; } #particles-js{ height: 100%; color:turquoise; } </style> <div class="main"> <div id="particles-js"> </div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', 'particles.json', function(){ console.log('particles.json loaded...'); }); </script> {% block content %} {% endblock content %} </div> </div> <!-- End Body --> {% include 'snippets/footer.html' %} </body> </html> When I run this with Django. I get the following error even though the locations of those files are exactly the same: Not Found: /style.css [28/May/2021 00:21:59] "GET /style.css HTTP/1.1" 404 2263 Not … -
What does Django use as a Cache Key?
I'm caching Wagtail API endpoints using Django's standard cache_page function which looks something like this: @method_decorator(cache_page(600), name="detail_view") @method_decorator(cache_page(600), name="listing_view") class CashedPagesAPIViewSet(PagesAPIViewSet): """Custom API endpoint that can receive a slug.""" pass Very basic. I want to be able to clear the API cache on each page save, but I don't know how to get the cache key. I can clear all the cache with this: from django.core.cache import cache from wagtail.core.signals import page_published def clear_cache(sender, **kwargs): """Clear page cache.""" cache.clear() page_published.connect(clear_cache) What I want to be able to do is: def clear_cache(sender, **kwargs): """Clear page cache.""" page = kwargs["instance"] cache.delete(f"/api/v2/pages/{page.id}") # or whatever the key might be -
Django APP Heroku Log detecting duplicated requests
I have a Django APP running on Heroku. I noticed that when I make some requests, there seems to be a sort of duplicated call with extra info in the url. Which of course is not found. I will explain here showing Heroku´s log details. The first request works fine and the APP does what it´s supposed to do. Notice the path ending: /3/ 2021-05-28T00:05:49.833310+00:00 heroku[router]: at=info method=GET path="/catalog/toma-pedidok-detail/7650/Proxima%20fase/3/" host=www.host.com request_id=ef1018b5-456a-4559-89e6-830b256671fd fwd="181.168.190.149" dyno=web.1 connect=1ms service=1971ms status=200 bytes=160294 protocol=https Then the "ghost" request happens and the path ending has the extra characters: /3/636 2021-05-28T00:06:02.494246+00:00 heroku[router]: at=info method=GET path="/catalog/toma-pedidok-detail/7650/Proxima%20fase/3/636" host=www.host.com request_id=222035b1-2ea8-405d-b8b2-c47fc2376aba fwd="181.168.190.149" dyno=web.1 connect=2ms service=83ms status=404 bytes=11585 protocol=https Finaly we have a logical "not found" response. 2021-05-28T00:06:02.491918+00:00 app[web.1]: Not Found: /catalog/toma-pedidok-detail/7650/Proxima fase/3/636 Some checks It happens sometimes, not always There is no ajax call related with this url target Django´s view only has 1 return statement I don´t include all the view because it´s quite extense. I´m trying to get a clue about why can this be happening first. Any clues welcome. Thanks in advance! -
Is it possible to stack either formset_factory, inlineformset_factory - Django
As the question says, i haven't found any info about stacking either formset_factory, inlineformset_factory into either formset_factory, inlineformset_factory maybe someone in here might know something about it? :o -
Frontend Framework like react, vue in python
I am trying to shift in python for web development. But I love to use React in Frontend Side. I would Love to Know if there is any Frontend Framework or library design in python. Reason I am Shifting is that i am into data science and don't want to remember Lot of logic of different language. If there is any with high working potential it would be great. Thank You