Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django parameter via get not working while forming direct url
Base URL: path('api/product/', include(('store.urls', 'store'), namespace='api-product')), Store URL: path('invoice-pdf-get/', invoice.InvoiceToPdf.as_view(), name='invoice-pdf-get'), HTML: <html> <body> <form method="get" action="{% url 'api-product:invoice-pdf-get' %}?R={{ invoice.invoice_unique_number }}"> <input type="submit" value="Generate PDF"> </form> </body> </html> When I hit the button, I get the url in browser as: http://localhost:8000/api/product/invoice-pdf-get/? Where as expecting: http://localhost:8000/api/product/invoice-pdf-get/?invoice_number=SOMEKEY Though if I submit a hidden type input via form, I get the expected result but I was reading: Daniel Roseman SO answer. to pass parameter via GET. Though inspect shows the URL (see image) but why am I not getting expected result? -
Django in template timeuntil if statement
i would like to have kind of a todo list, where i have a model called "projekt" and i want colorize the html output depending on the timeuntil tag (if less then 7 days it should have the bootstrap class "danger" and if its more then 7 days it should have the class "success" here my models.py: class Project(models.Model): name = models.CharField(max_length=100) active = models.BooleanField(default=True) beginning_project = models.DateField() beginning_project_time = models.TimeField(blank=True, null=True) deadline = models.DateField() deadline_time = models.TimeField(blank=True, null=True) beschreibung = models.TextField() def __str__(self): return self.nam here's my views.py: def Home(request): proj = Project.objects.filter(active=True) context = { 'proj':proj } return render(request, "home.html", context) and as last my template: home.html: {% for proj in proj %} <div class="row mx-auto text-center"> <div class="col-12 projcard"> <a href="{% url 'apps:Project' %}"> <p class="display-4 mx-auto"> {{ proj.name }}x </p> {% if proj.beginning_project|timeuntil > 7 %} <button class="btn btn-success"> <u> starts in {{ proj.beginning_project|timeuntil }} </u> </button> {% else %} <button class="btn btn-danger"> <u> starts in {{ proj.beginning_project|timeuntil }} </u> </button> {% endif %} </a> </div> </div> {% endfor %} -
Django debug toolbar works only in admin interface
I've did all the steps which are described in the docs and got the toolbar in admin site. However, I can't get it work in the project frontend side. Here is my settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ... ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INTERNAL_IPS = ('127.0.0.1', 'localhost',) I've googled a lot already and non of the proposed solution are not working for me: workaround that shows toolbar even if debug=False, playing with different parameters like INTERCEPT_REDIRECTS=False/True, specifying JQUERY_URL since there is a local jquery which is used by frontend. I've asked for help from frontend dev, but he can't understand why there is no any configs for client side. Frontend is using nodes.js and listens on 3000 port than forwards to localhost:8081. Django version 1.10, django-debug-toolbar 1.9.1. -
Removes braces from variable
I am comparing two list: gp_yu = set(agencys_sp2).intersection(gp_list_t) the output is in braces like this {900}. What can i do to remove the braces -
django/nginx upstream prematurely closed
i'm trying to get a response from a WSDL server using zeep library this is my python code in one of my views: zeep.Client(wsdl=wsdl_url, transport=zeep.Transport(cache=None, timeout=300,)) this problem only appears in the view that i'm trying to call a WSDL soap service. and it appears when i'm sending the request to WQSL sever. i've also tried to connect to WSDL server from python shell, but it has delay, and i am sure that line of code cause's the problem. 2018/08/07 08:28:31 [error] 9629#9629: *200 upstream prematurely closed connection while reading response header from upstream, client: client_ip, server: server_name, request: "POST /api/part1/part2/part3/?id=148 HTTP/1.1", upstream: "http://unix:/path/to/socket.sock:/api/part1/part2/part3/?id=148", host: "server_name" this is my nginx.conf : user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } and this is my sites-enabled config of my website: upstream app_server { server unix:/path/to/socket.sock fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server; return 301 https://servername.x; } server { server_name servername.x www.servername.x; keepalive_timeout 5; client_max_body_size 1G; access_log … -
Uploading and displaying an image in Django
I am currently learning Django. I am building a system that gets input from the user as image and throws back the damage level. I have the python files all caught up. But I am having difficulty doing the Django part. How do I get an image as input from the user ? And how will I throw back the result of the code that does the damage level prediction to the front end ? Thanks in advance -
OperationalError at /admin/ no such table: IEL_user when browse for admin
I have a error which I am unable to detect, I am learning Django, at start I was working with Django default user model, but then I need to have a custom user model, so I have dropped my db(deleted sqlite db file), make new user model in models.py and then makemigrations and then migrate it.But,when I switched to admin page I have got an error which I am unable to resolve.The error I got is: django.db.utils.OperationalError: no such table: IEL_user Models.py file class user(AbstractUser): is_student=models.BooleanField(default=False) is_teacher=models.BooleanField(default=False) I have added AUTH_USER_MODEL = 'IEL.user' in settings.py -
Django filter query item is in list filed
My model has a field, this field is a list of strings, and I need to filter a value is in that list field? Can I do it with filter? I read about type_list__in=['M', 'C'] that check type_list is in ['M'] or not, but I need opposite, check 'M' is in type_list Is it possible to filter query set in django that a value is in a list field? if yes how? -
How to access request variable in django.test.client.login()
I am trying to test django-axes using django.test.client. But it says, that is missing request. So I decided to inherit new class and override login method of djang.test.Client class. How I can access request and pass it to authenticate method? Original django.test.client.login() method: def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible; False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True else: return False My overwritten method: class NexchangeClient(Client): def login(self, **credentials): request = ***THERE SHOULD GO REQUEST*** from django.contrib.auth import authenticate user = authenticate(request, **credentials) if user: self._login(user) return True else: return False -
Add queryset to __init__ in django
I am getting the following error: Exception Type: TypeError Exception Value: init() missing 1 required positional argument: 'queryset' It relates to the bottom row of the following code. forms.py Class FieldDefinitionTypeField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): self.field_definitions = kwargs.pop('field_definitions', []) self.group_by_category = kwargs.pop('group_by_category', False) super(FieldDefinitionTypeField, self).__init__(*args, **kwargs) Hope someone can help. -
custom calculation returns 'NoneType' object is not callable django
I'm trying to do some calculation for my system, I need to get all location count for a superuser like so location = LocationData.objects.filter(email=self.request.user.email).count(), then I need to count all licences for that user, like so count = MyUser.objects.filter(location_count=self.request.user.email).count(), and I need to check if the location == count and to * location with some price, if count == location: context['social'] = location * FRISTPRICE when I get the price I need to display it on a template. The complete view is class AdminDashboard(TemplateView): """ """ template_name = 'administration/admin.html' @cached_property def get_context_data(self, **kwargs): context = super(AdminDashboard, self).get_context_data(**kwargs) user = MyUser.objects.get(pk=self.request.user.pk) # check if user is superuser if not don't include him if user.is_superuser: # check how much locations does user have location = LocationData.objects.filter(email=self.request.user.email).count() # check how much user have licences payed for count = MyUser.objects.filter(location_count=self.request.user.email).count() # if count is == to location then the location is proper # so count * package = application sales if count == location: context['first_package'] = location * FIRSTPRICE if count == location: context['second_package'] = location * SECONDPRICE if count == location: context['third_package'] = location * THIRDPRICE return context and the full error is HERE, my first guess is that context can not be … -
Django query - combine two different cases in filter
I'm using Django 1.10 I have a query that depends on the received parameter - it depends on whether 'job_name' is None or not: def delete_jobs_by_age_and_name(days_ago, job_name=None): date_to_delete_from = datetime.today() - timedelta(days=days_ago if job_name is not None: jobs_to_delete = AsyncJob.objects.filter( name=job_name, created_at__lte=date_to_delete_from ) else: jobs_to_delete = AsyncJob.objects.filter(created_at__lte=date_to_delete_from) I would like to do that in one query. For example something like: job_name = ANY if job_name is None jobs_to_delete = AsyncJob.objects.filter( name=job_name, created_at__lte=date_to_delete_from ) Is there such option? -
Make browser submit additional HTTP-Header if click on hyperlink
Is there a way to make the webbrowser submit additional HTTP header if the user clicks on a link? Background: In our environment every http-request has a unique ID on the server side. See https://serverfault.com/questions/797609/apache-x-request-id-like-in-heroku If your web application receives a http-request, I would like to know which page was the page before. The http referrer is not enough, since the user could use several tabs in his browser. I would like to avoid to put the ugly request-id into every GET/POST request which gets send from the browser to the server. My prefered solution would be some JavaScript magic which adds the request-id of the current page into the next http request. Steps in detail: browser access URL http://example.com/search web server receives http request with request ID 123 web server sends content of the URL to the browser (a search page). The page includes the request ID 123 somewhere the user searches for "foobar". the web browser submits a http request to the server and includes the previous request id somehow. web server receives second http request (ID 456) and can access the value of the first request (ID 123) somehow. Web server can store the relation "123 --> … -
Cannot resolve keyword 'user_id' into field
from django.shortcuts import render, redirect from django.http import HttpResponse, request from shop.models import * class UserView(): def user(request): template = 'shop/detail_user.html' return render(request, template) def wishlist(request): template = 'shop/customer_wishlist.html' return render(request, template) def profile(request): user_id = '' if 'user_id' in request.session: user_id = request.session['user_id'] user = User.objects.get( user_id = user_id ) user_details = User_detail.objects.get(fullname = fullname, phone_number = phone_number) template = 'shop/profile.html' data = { } return render(request, template, data) from django.shortcuts import render, redirect from django.http import HttpResponse, request from .shop import ShopView from shop.models import * from django.db.models import Q,Count import hashlib import json class RegisterView(): def register(request): if request.method == 'POST': data = request.POST user_count = User.objects.filter(email = data['email']).count() if user_count > 0 : print(user_count) return redirect(RegisterView.register) user = User.objects.create( email = data['email'], password = hashlib.md5(data['password'].encode('utf-8')).hexdigest(), available = True, role = 0 ) user_details = User_detail.objects.create( user = user, fullname = data['fullname'], phone_number = data['phone_number'], ) request.session['user_id'] = user.id request.session['user_email'] = user.email request.session['is_login'] = True return redirect(ShopView.index) else: template = 'shop/registrasi.html' return render(request, template) -
Django render with context to VueJS
I have a django view, that renders a template with context that includes data based on a form input. Now i want to access that context data. View function: def view_function(request): ... ... context = { 'dataList': datalist } return render(request, 'template.html', context = context) Template: var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { search: "", dataList: [], }, created(){ this.dataList = ... } }) Is there a way to get context from Django to VueJS 'dataList'? -
How to display RealTime Leaderboard for 100000 using Python
I'm trying to implement a realtime Leaderboard for my django web-app , I also take help with one python package which is Leaderboard :- https://github.com/agoragames/leaderboard-python But in this Case I have to implement it by LOOP , but it will take time for 100000 users ,So what will be the best aproach for this , Here you can check my code views.py def Index(request): a=Score.objects.all() highscore_lb=CompetitionRankingLeaderboard('sdfs') for index in a: highscore_lb.rank_member(index.name, index.score) b=highscore_lb.all_leaders() return render(request,'index.html',{'b':b}) Models.py class Score(models.Model): name=models.CharField(max_length=211) score=models.IntegerField() def __str__(self): return self.name -
Django Channels - Update Screen with change in DB in real-time
consumer.py import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): self.other_user = self.scope['url_route']['kwargs']['username'] self.me = self.scope['user'] self.thread_obj = await self.get_thread(self.me, self.other_user) await self.channel_layer.group_add( self.channel_name # this is a default attribute of channels ) await self.send({ "type": "websocket.accept" }) # when you send something from the front-end, you need to receive it async def websocket_receive(self, event): front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') my_response = { 'message': msg, 'username': self.me.username, } await self.create_chat_message(self.me, msg) # broadcasts the message event to be sent await self.channel_layer.group_send( { "type": "chat_message", "text": json.dumps(my_response) } ) async def chat_message(self, event): # sends the actual message await self.send({ "type": "websocket.send", "text": event['text'] }) @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] @database_sync_to_async def create_chat_message(self, me, msg): return ChatMessage.objects.create(thread=self.thread_obj, user=me, message=msg ) I made a chat website for practice. This is something very similar to this chat website. Currently my version of code does exactly what the demo website does. One user sends a message, and the message will automatically appear on the other user's screen in real-time, and the chat message is saved in Thread object. However, … -
when i upload a image if it be big i got this message 403 Forbidden when i want to show it
my model is this class Image (model.Model): Image = models.ImageField(upload_to='pic_folder/', default='', help_text='') my form is this class Image(form.Form): Image = form.ImageField() my view is this def Image(request): if request.method=="POST": form =Image(request.POST,request.FILES) if form.is_valid(): cd =form.cleaned_data t = Image(Image=cd["Image"]) t.save() else: form=Image() return render(request,"template.html",{'form':form} template <form method="post" enctype="multipart/form-data">{%csrf_token%} <input type="file" name="Image" > <input type="submit" name="" valu="ok"> </form> if the image be small it will be ok but if it be large i got this enter image description here -
Send email with attachment django
I have the file url in my db. I want to send the file as an attachment in email. I have tried the below code def mail_business_plan(sender, instance, created, **kwargs): if created: ctx = {"ctx":instance} from_email = 'info@some_email.in' subject = 'Business Plan by' + instance.company_name message = get_template('email/business_team.html').render(ctx) to = ['some_email@gmail.com'] mail = EmailMessage(subject, message, to=to, from_email=from_email) mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type) return mail.send() I am getting error as "AttributeError: 'FieldFile' object has no attribute 'content_type'" What's the best way to send mail with attachment, if the file path is stored in the database. -
Debugging not running on PyCharm for my Django project
I am not able to run with debug option for my Django project after an recent update of PyCharm. The last line of stacktrace gives error Process finished with exit code 134 (interrupted by signal 6: SIGABRT) the first few lines of stacktrace gives error Fatal Python error: Cannot recover from stack overflow. Here is the full stacktrace - pydev debugger: process 21976 is connecting Connected to pydev debugger (build 181.5087.37) Fatal Python error: Cannot recover from stack overflow. Thread 0x000070000ee34000 (most recent call first): File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 101 in _on_run File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 303 in run File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916 in _bootstrap_inner File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 884 in _bootstrap Thread 0x000070000e931000 (most recent call first): File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 365 in _on_run File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 303 in run File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916 in _bootstrap_inner File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 884 in _bootstrap Current thread 0x000070000e42e000 (most recent call first): File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1238 in current_thread … -
Django startup storage in memory
My requirement is ,whenever I start my server one polling operation should get data from another server and store that data in memory,so that all apps in my project can access those data for certain kind of validation and perform some task. -
Filter 2D list with template tag in Django
I'm trying to write a template tag that will filter a 2D list. This is my template tag: from django import template register = template.Library() @register.filter def index_two(seq, position1, position2): return seq[position1][position2] This is my list that I'm passing to my template: summary = [[50, 0, 0], [50, 100, 100]] I'm trying to reference the first element of the first list in summary, like so: {{summary|index_two:0 0}} However, I received a template syntax error: index_two requires 3 arguments, 2 provided. I've tried to adjust my template tag to the answer here, but I can't get it to work for me. Any suggestions? Thanks -
Django not able to run manage.py
I'm not able to run my Django server in local. I'm trying to setting my djongo database instead of default sqlite3 .db Here I followed the below URL for djongodjongo on python set up System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb554b61bf8> Traceback (most recent call last): File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 56, in table_names return get_names(cursor) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 51, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/djongo/introspection.py", line 34, in get_table_list for c in cursor.db_conn.collection_names(False)] File "/home/iradmin/anaconda3/lib/python3.6/site-packages/pymongo/database.py", line 715, in collection_names nameOnly=True, **kws)] File "/home/iradmin/anaconda3/lib/python3.6/site-packages/pymongo/database.py", line 674, in list_collections read_pref) as (sock_info, slave_okay): File "/home/iradmin/anaconda3/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1099, in _socket_for_reads server = topology.select_server(read_preference) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/pymongo/topology.py", line 224, in select_server address)) File "/home/iradmin/anaconda3/lib/python3.6/site-packages/pymongo/topology.py", line 183, in … -
How to make the id auto increasing by 2 in the Model of Django?
Since the auto_increment setting in the MySQL is for the global, which cannot be set to a specific table? I'm considering if it's possible to make the id auto increasing by 2 in the Model of Django? models.py class Video(models.Model): name = model.CharField(max_length=100, default='') upload_time = models.DateTimeField(blank=True, null=True) def __str__(self): return self.name What should I do? Thanks for ur help. -
Django/Nginx 502 badgateway when trying to set SOAP client
i'm trying to receive a response from WSDL service sometimes it works so fast but most of the time it wont work.. i'm sure this line causes this issue: client = zeep.Client(wsdl=WSDL_URL) i also tried from python shell, and saw delay in initializing zeep client i know this delay may be from WSDL server, but that server is a payment API server, so it is not logically true. anyone can help?