Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset using __in returning empty queryset
I have the following query set defined as: currentaccess = QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1).values_list('sr_datareduce_summary_code', flat = True) Which displays as <QuerySet ['Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003']> I then run it through the following if statement to replace "A00000" with "S00001" if "A00000" in currentaccess: appaccess = 'S00001' else: appaccess = currentaccess print(appaccess) This works fine as the print is still: <QuerySet ['Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003', 'Z31003']> My issues is when I attempt to create a new query set to get the name of the dr_code in a ref table. This gives me the error message: 'QuerySet' object has no attribute 'sr_datareduce_summary_code' datareduceref = QVDataReduceCodeRef.objects.filter(dr_code__in = currentaccess.sr_datareduce_summary_code).values_list('dr_name', flat = True) Trying this gives me an empty query set: <QuerySet []> datareduceref = QVDataReduceCodeRef.objects.filter(dr_code__in = QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1).values_list('sr_datareduce_summary_code', flat = True)).values_list('dr_name', flat = True) My model is defined as: class QVDataReduceCodeRef(models.Model): dr_code = models.CharField(db_column = 'DR_Code', max_length = 100, primary_key=True) dr_name = models.CharField(db_column = 'DR_Name', max_length = 255) class Meta: managed = False db_table = 'QV_DataReduceCode_Ref' def __str__(self): return str(self.dr_code) My QVReportAccess Model is defined as: class QVReportAccess(models.Model): user_status = models.CharField(db_column='User_Status', max_length = 20) # Field name made lowercase. ntname = models.OneToOneField(ADMirror,db_column='NTName', max_length=30,primary_key=True, … -
Django istartswith utf8 not working
I have this query for case insensitive search: groups = Group.objects.filter.filter(name__istartswith=query) It works fine with English characters. But doesn't work with utf-8 Russian characters(no errors- only case-sensitive search with the same code) What do I do? UPD: as a test database I use sqlite. I guess a problem somewhere here. But may be there is some workaround to this? -
Django counting relations for each user
How to count how many "friends" each user has and then display it in the descending order. class Friend(models.Model): to_friend = models.ForeignKey(User) from_friend = models.ForeignKey(User, related_name='owner') I`ve had an idea for counting relationships, but i think its not an effective way to do it. for user in User.objects.all(): user.friend_set.all().count() -
Retrieve all the entries from a specified topic
I tried to fetch all the entries relating to topic question In [17]: topic = Topic.objects.filter(text__icontains='question') It throws errors when issuing the following command: In [15]: questions = Topic.objects.filter(text__icontains='question').entry_set.all() AttributeError: 'QuerySet' object has no attribute 'entry_set' So, the id should be retrieved firstly: In [18]: [ i.id for i in topic] Out[18]: [14] In [19]: Topic.objects.get(pk=14).entry_set.all() Out[19]: <QuerySet [<Entry: Why encapsulate button Finally, get my result. Nevertheless, it's awkwardly cumbersome, how to get it done elegantly? class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) title = models.CharField(max_length=200) text = models.TextField() tags = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return string representation of the model""" return self.text[:50] + "..." -
Initial value in the Django CharField does not have any effect
I've looked at many pages on this site and a few others, but none of the solutions seems to work. Specifically, class twoFieldGeneric(forms.Form): def __init__(self, *args, **kwargs): self.label1 = kwargs.pop('label1') self.label2 = kwargs.pop('label2') self.init1 = kwargs.pop('init1') self.init2 = kwargs.pop('init2') super(twoFieldGeneric, self).__init__(*args, **kwargs) self.fields['field1'] = forms.CharField(required=False, initial=self.init1, label=self.label1) self.fields['field2'] = forms.CharField(required=False, initial=self.init2, label=self.label2) does not result in the initial values being set. What and I doing wrong? -
Django populate field with object id
Currently I'm working on an admin panel for my application which is written in React and Node.js. I already have a MongoDB database so I want to connect the Django app to this database. I read about Djongo connector and I decided to give it a try. There is a connection to the database, which means I can perform simple CRUD operations. The problem is with the poplation of referenced fields. In my database I have a collection of boxes. Each box has an owner field which contains an ID to a Supplier object. In my django application, when I review the boxes collection, I only see the ID of the Supplier. I want to be able to retrieve information from that Supplier object but I don't know how. I tried embed the Supplier model into my Box model but it gives me this error: https://i.gyazo.com/362857feb2fc75065852a53e1dc4f774.png When I try to use ForeignKey, I'm not getting any errors, but the field is just and id, like this: https://i.gyazo.com/989ccdb3799935b4f308314a9fb6c27c.png Here is my models.py file(I omitted irrelevant parts): from djongo import models from django import forms userStatusEnum = ( ('pending', 'pending'), ('active', 'active'), ('removed', 'removed'), ) userTypeEnum = ( ('buyer', 'buyer'), ('supplier', 'supplier'), … -
How to divide a list and delete half of it in python
i need help. Please How can I divide a list in Python, into two equal parts and delete one part. Then assign one part to a new variable. example list = ['name', 'can', 'she', 'men', 'them', 3, 4, 5, 6, 7] How then can I delete half part of this list and assign half to a new variable new_list = ['name', 'can', 'she', 'men', 'them'] -
Django or Flask to develop rest-API's to work with Neo4j
I wanted to know what will be better to make rest API to use with neo4j, Flask or Django. I am currently working on developing some rest APIs to add data coming to my website to a Graph Database (neo4j). I am totally new to python itself but I have been working heavily for past few weeks. A similar question has been asked in past, but all of these are very new technologies and rapidly changing. So, I wanted some fresh advice. Thank you in advance. -
How many JS websockets can a page have open at one time
I'm currently using Django Channels to create a real time web application, and I have tried using two websockets simultaneously in JavaScript successfully. Is there a limit to the number of websockets one webpage can maintain? Is this something you would want? or would would front end logic that can tell the difference between the messages? -
How to remove users as they log out using middleware
I am using the middleware below to generate a list of currently logged-in users. The problem I am having is how to remove users automatically from the online_now and online_now_ids when they have logged out. I have tried to use signals but with no success...any help much appreciated from django.core.cache import cache from django.conf import settings from django.contrib.auth.models import User from django.utils.deprecation import MiddlewareMixin from django.dispatch import receiver from django.contrib.auth.signals import user_logged_out #Set Environment variables for settings.py ONLINE_THRESHOLD = getattr(settings, 'ONLINE_THRESHOLD', 30*1) ONLINE_MAX = getattr(settings, 'ONLINE_MAX', 50) CACHE_MIDDLEWARE_SECONDS = getattr(settings, 'CACHE_MIDDLEWARE_SECONDS', 10) def get_online_now(self): return User.objects.filter(id__in=self.online_now_ids or []) class OnlineNowMiddleware(MiddlewareMixin): """ Maintains a list of users who logged into the website. User ID's are available as `online_now_ids` on the request object, and their corresponding users are available lazzily as the `online_now` property on the request object """ def process_request(self, request): #Get the index uids = cache.get('online-now', []) #multiget on individual uid keys online_keys = ['online-%s' % (u,) for u in uids] fresh = cache.get_many(online_keys).keys() online_now_ids = [int(k.replace('online-','')) for k in fresh] #if user is authenticated add id to list if request.user.is_authenticated(): uid = request.user.id #if uid in list bump to top # and remove earlier entry if uid in online_now_ids: … -
Django Login bizare behavior
I'm using Django to build a web app. I have built both the login and the registration on the home page as I'd like them to be right there, and I have a problem with the login. If I enter the correct credentials, it logs me in without any problem, but if I enter wrong credentials I get no error whatsoever, it just tells me that my view returned none. Here's my Views Code: class MainView(View): def get(self, request, *args, **kwargs): user = request.user return HttpResponse( "Welcome " + user.username + ", You are Logged in!! you can logout <a href=/logout/>here</a>") class HomeView(View): form_class_reg = SignUpForm form_class_login = AuthenticationForm template_name = 'main/home.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated is True: return MainView.as_view()(self.request) if request.user.is_authenticated is False: form_reg = self.form_class_reg(prefix='SignUpForm') form_login = self.form_class_login(prefix='SignInForm') return render(request, self.template_name, { 'form_reg': form_reg, 'form_login': form_login, }) def post(self, request, *args, **kwargs): form_reg = self.form_class_reg(request.POST, prefix='SignUpForm') form_login = self.form_class_login(data=request.POST, prefix='SignInForm') if form_reg.is_valid(): form_reg.save() username = form_reg.cleaned_data.get('username') raw_password = form_reg.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/') if form_login.is_valid(): username = form_login.cleaned_data.get('username') raw_password = form_login.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) if user is not None: login(request, user) return redirect('/') else: return HttpResponse("Wrong credentials") So if user … -
Django order choice field
I've been struggling with Django choice fields in form. I have choices in my forms.py and a radio choice field. DURATION_CHOICES = { (1, '30'), (2, '45'), (3, '60'), (4, '75'), (5, '90'), (6, '105'), (7, '120+'), } duration = forms.ChoiceField(choices=DURATION_CHOICES, widget=forms.widgets.RadioSelect, label_suffix="", label="Trainingsdauer in Minuten",) However when I open the form to create a new training session, the duration radio select field is randomly ordered, i.e. 105 is in the list before 45. The order even changes from testing devices to another I have the very same problem with choice fields from models.py I have already ordered my choices but how do I get the ordered choice list in my form? -
Migrate my project from django framework to flask framework
i am new to the python world, just started couple of moths ago. I have my project on django framework(2.0.5) and i want to shift my complete application to flask(1.0.2). and in backend i want to use kinto as storage layer. my current project is a little big having 10 apps inside. 1)So please tell me about the things that i need to take care of before migration? 2) what are the ideas/method to do this? 3)what will be the impact of using kinto? any other thing that i need to know? thanks in advance. -
How to get link to download file in pdf? (Django)
I have the following structure in the details.html <p>Files: {% for file in files %} <p><a href="{{ file }}">{{ file.name }}</a></p> {% endfor %} </p> This link returns the correct url. http://localhost/media/file.pdf However, every time I click, instead of downloading the file, it returns error 404. What is the correct way to do this operation? -
Sometimes requests are ignored in Heroku where my Django server is deployed
The current server has an image classification model installed, and if I send the request to the uri (this image contains the image), it will return the expected result well. However, using the Heroku server for free does not always give you the exact response to the request, partly because it does not receive many benefits. The log for the error is as follows. yyyy-mm-21T07:17:07.213603+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/myuri/" host=myappuri request_id=5aff7111-1701-4084-a571-96b94700ec9e fwd="11.11.111.1" dyno=web.1 connect=1ms service=18379ms status=503 bytes=0 protocol=http I have verified the Heroku Error document for H13, and I am aware that the request time has been exceeded (because the gunicorn is used, Heroku accepts up to 30 seconds). Is this also the fact that I know? Is this the time between App (after sending the request) and Heroku (just before receiving the request)? Also, what attributes should I add to address this issue? Can not you give me more details about this log? -
Django: Initial format of TimeInput
In my model Even I have a field with a date: class Event(models.Model): ... start = models.DateTimeField() Also, I use a custom widget for this field: class SplitDateTime(forms.SplitDateTimeWidget): template_name = 'split_datetime.html' def __init__(self, attrs=None): widgets = ( forms.SelectDateWidget, forms.TimeInput( attrs={'size': '5', 'placeholder': 'HH:MM', 'maxlength': '5'}) ) # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) My problem: In my admin or in an UpdateView, the initial time is in the form of "HH:MM:SS", but I'd prefer only "HH:MM". Where should I change that? -
Django create instances from class attributes
Suppose such a Topic Model Table class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User) def __str__(self): """Return a string representation of the model.""" return self.text As the structure indicates, text, data_added, owner are class level attribute. However, Django is capable of creating instance from the class attributes In [21]: Topic.objects.create(text='Celery', owner_id=1) Out[21]: <Topic: Celery> In [34]: celery = Topic.objects.get(pk=22) In [35]: isinstance(celery, Topic) Out[35]: True I assume there should be initiating process def __init__() How Django accomplish such an amazing task? -
django-import-export export is slow when there is foreign key
when there is foreign key in model, exporting is very slow, when I exclude the foreign there is no problem, it starts to download quickly. What might be the issue here? Thanks! -
Django paginate for django 2
I need to use pagination to a Django list but I couldn't find any help online,, only old docs from Django version 1.3 here are my files : views.py def home(request): all_dress = Item.objects.all().filter(dress_active=True) all_good_dress = Item.objects.all().filter(dress_special=True) current_user = request.user context = { 'all_dress': all_dress, 'current_user': current_user, 'all_good_dress':all_good_dress, } return render(request, 'fostania/home.html', context) Template(html) {% for item in all_dress %} <div class="card border-info" style="width: 18rem;"> <a href="{% url 'dress_details' item.pk%}"><img class="card-img-top" src="{{ item.dress_image1.url }}" alt="Card image cap"></a> <div class="card-body" align="right"> <h5 class="card-title"><a href="{% url 'dress_details' item.pk%}">{{ item.dress_name }}</a> <br>{{ item.dress_action }}<br>{{ item.dress_price }} جنيه </h5> <p class="card-text">المقاس : {{ item.dress_size }} <br>{{ item.dress_city }}<br> {{ item.created_at|date:"SHORT_DATE_FORMAT" }} </p> </div> </div> <br> <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {% endfor %} -
how to convert datetime.timedelta(0, 79200) to minutes and seconds
+-----------+----------+ | from_time | to_time | +-----------+----------+ | 09:00:00 | 22:00:00 | +-----------+----------+ 1 row in set (0.00 sec) that is my actual SQL table which is in Hours:minutes:seconds format. when I query with select from_time, to_time from Tollapp_configure;, in django I got the out put as ((datetime.timedelta(0, 32400), datetime.timedelta(0, 79200)),). How can I convert ((datetime.timedelta(0, 32400), datetime.timedelta(0, 79200)),) into actual Hours minutes and seconds(22:00:00 format). My django model looks like this.. class Configure (models.Model): from_time = models.TimeField() to_time = models.TimeField() -
Django Ajax: form submit handler only catches the form after you refresh the page
I want all functins to work without refreshing the page. I simply want to add courses, and be able to remove them using AJAX. here are my urls: from . import views from django.urls import path from django.conf.urls import url app_name = 'courses' urlpatterns = [ path('index/', views.index, name='index'), path('create/', views.create, name='create'), path('delete/<int:course_id>/', views.delete, name='delete'), ] creating courses works fine. here is the code for that: from django.shortcuts import render, redirect from courses.models import Course from django.http import JsonResponse from django.forms.models import model_to_dict # Create your views here. def index(request): context = { 'courses':Course.objects.all(), } return render(request, 'courses/index.html', context) def create(request): if request.method == 'POST': course = Course.objects.create(name=request.POST['name'], description=request.POST['description']) return JsonResponse(model_to_dict(course)) else: return render(request, 'courses/index.html') here is the ajax related to it: $(document).ready(function(){ $('.course_form').submit(function(event){ console.log(event.target); event.preventDefault(); $.ajax({ url: '/courses/create/', method: 'post', data: $(this).serialize(), success: function(response){ console.log(response); $('.courses').append(`<p>Name: ${response.name}, Description: ${response.description}</p> <form method="post" data-courseid="${response.id}"> <input class="delete_form" type="submit" value="delete"> </form> `) $('.course_form')[0].reset(); } }); }) $('.delete_form').submit(function(event){ console.log(event.target); event.preventDefault(); $.ajax({ url: `/courses/delete/${event.target.dataset.courseid}/`, method: 'post', // data: { CSRF: csrftoken}, success: function(response){ console.log(response); } }) }) }) and this is how its displayed on the template: <body> <div class="container"> <div class="courses"> {% for course in courses %} <p>Name: {{course.name}}, Description: {{course.description}} {{course.id}}</p> <form action="#" … -
MySQL Client, Django
Ive gone through a lot of posts but still haven't found the right solution to it yet.. I'm using Windows Server to try and connect MySQL with Django... I want to transfer the data from my SQLite db to mysqldb... I've already installed MySQL Client, Made changes to my Settings.py and everything.. I've linked my MySQL to my PhpAdmin as well.. I'm Still a beginner and this is the first time I'm trying to do anything of this sort... Any help would be appriciated Need help ASAP! Thanks in advance (venv) C:\Users\Administrator\PycharmProjects\BugTracker>pip install mysqlclient-1.3.12-cp37-cp37m-win_amd64.whl Requirement already satisfied: mysqlclient==1.3.12 from file:///C:/Users/Administrator/PycharmProjects/BugTracker/mysqlclient-1.3.12-cp37-cp37m-win_amd64.whl in c:\program files\python37\lib\s ite-packages (1.3.12) (venv) C:\Users\Administrator\PycharmProjects\BugTracker> python manage.py syncdb Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Administrator\PycharmProjects\BugTracker\venv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, … -
Unable to connect docker mysql via django
I'm using docker as MySQL server, in docker I use: docker run --name what -e MYSQL_ROOT_PASSWORD=abc123 -e MYSQL_DATABASE=mami -p 3306:3306 -d mysql After that I tested it in MySQL workbench. It works fine with 192.168.99.100:3306 and root/abc123 but when I try to connect it via django: import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'what', 'USER': 'root', 'PASSWORD': 'abc123', 'HOST': '192.168.99.100', 'PORT': '3306', } } It gives me django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'192.168.99.1' (using password: NO)") when I run application or just doing python manage.py migrate I'm Using Windows and Python 3.6, what am I doing wrong? Thanks in advance for any help! -
billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL) error in Django celery
I run celery as a Daemon in Production with celery==4.1.0, rabbitmq-server==3.5.7, django==2.0.4. In local it works fine but makes me stuck with billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL) error which I'm trying to fix. Here are the config /etc/default/celeryd: CELERY_BIN="path/to/celery/bin" CELERY_APP="myproj" CELERYD_CHDIR="path/to/project" CELERYD_OPTS="--time-limit=300 --concurrency=4" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_USER="root" CELERYD_GROUP="root" CELERY_CREATE_DIRS=1 export SECRET_KEY="foobar" /etc/init.d/celeryd: celeryd -
Django/Python - Check if argument was passed to class
I am passing different arguments to a Django form and would like check which argument was passed inside the form's class. How can i do that? views.py ... form = CategoryForm(choose_category =True) ... forms.py class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): self.choose_category = kwargs.pop('choose_category',None) super(CategoryForm,self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' if not self.choose_category: self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) if self.choose_category: do something In the example above- the error is that self is not defined, how can i check for the existence of choose_category outside of __init__ ? Thank you!