Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can load data variables that accessible to all views but get initialised after data available in database?
I'm creating API with Django rest framework. I've one table which will be used as types for the products. Another table which will map that types with the product. consider it as producttypesmapping table. So, I'm creating product type update endpoint. which will only update the producttypesmapping. The issue is I've used the tuple of tuples variable which will be initialized in util.py directly by querying the producttypes table. So, I only have to query the data only once. But the problem is utils.py executed before the even the producttypes initialized with any data. -
When the command is executed python manage.py runserver
When the command is executed : python manage.py runserver error : C:\Users\Mr-py-dj\Desktop\sageteam-project\venv\lib\site-packages\khayyam\algorithms.py:19: UserWarning: The C extension is not available. Switching to fallback python pure algorithms,so it's about 1000X slower than C implementation of the algorithms. "The C extension is not available. Switching to fallback python pure algorithms," why??? -
Dynamic choice for Foreign Key in Django Model
I'm currently having some difficulty implementing dynamic choice for a field in my model. The model in question is as below. class Item(models.Model): # Fields ... item_type = models.ForeignKey(Type, on_delete=models.PROTECT) What I want is to limit the number of Type returned for this field. Each of my Type entry has a 'group' field, and I only want to return the Type entry that has the same group as the group that the current user is in. For example, an user in Group "g1" when create an Item could only select Type with "g1" in group field. I've checked out limit_choices_to, but I'm not sure how I can get the group of the user opening the form so that I can pass it into limit_choices_to. If anyone can provide an advice or any different approach to solve this it would be appreciated. -
Django annotate model and filter for specific value
I'm trying to get into djangos annotate, but can't quite figure out how it works exactly. I've got a function where I'd like to annotate a queryset of customers, filter them and return the number of customers def my_func(self): received_signatures = self.customer_set.annotate(Count('registrations').filter().count() Now for the filter part, thats where I have a problem figuring out how to do that. The thing I'd like to filter for is my received_signatures, which is a function that is being called in my customer.py def received_signatures(self): signatures = [reg.brought_signature for reg in self.registrations.all() if reg.status == '1_YES'] if len(signatures): return all(signatures) else: return None brough_signature is a DB Field So how can I annotate the queryset, filter for the received_signatures and then return a number? -
How Can I Get Post Details in Django
Now, I am creating a website. In this website, I made a create a post part. I can add new posts - I mean when I add some content, I can see in admin panel - But after I click Save, this happens NoReverseMatch at /post/new/ Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. enter image description here blog/views.py def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {}) def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) blog/post_detail.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} blog/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/new/$', views.post_new, name='post_new'), ] How can I fix this? -
Block.objects.get(id=block_id, 1) get "1" as default if id is null
I'd like to retrieve block from database block = Block.objects.get(id=block_id, 1) if block_id does not exist, get "1" as default value, However, it report error: block = Block.objects.get(id=block_id, 1) ^ SyntaxError: positional argument follows keyword argument How could I achieve such a functionality? -
Django does not show images and render CSS
I am trying to set a background image and some CSS style to my page, but every attempt I tried seems to have no effect: i have a base.hmtl page where I load {% load staticfiles %} in settings.py I have set up STATIC_URL = '/static/' and STATICFILES_DIR = [os.path.join(BASE_DIR, 'webapp/static')] In setting.py 'django.contrib.staticfiles' is under installed apps the CSS folder is located in the main directory under static, and the image is as well under static/img here is how i am trying to load this page: {% extends 'base.html' %} {% block content %} <h1>Welcome!</h1> {%load staticfiles%} <img src="{% static '/img/background.jpg'%}"/> {% endblock %} While in my base.html I load my stylesheet in this way: <link rel="stylesheet" href="{% static 'webapp/CSS/style.css'%}"> and as well in base.html I load statifiles I attach here my folder structure, maybe I have missed something there: -
Jinja's tag 'raw' in Django throws an error - 'Did you forget to register or load this tag?'
I'm using: Django (w/ Jinja) Mustache (for parsing JS vars) The context: I'm trying to use Jinja's {% raw %}{% endraw %} tags in order to escape the similar syntax of the Mustache's markers in the HTML code. Nevertheless, Django throws an error 'Did you forget to register or load this tag?' -
How to remove custom field without breaking Django migrations?
I work on a Django 1.8 project that uses the old django-json-field library. I want to remove the library, update to Django 1.9 and use the native JSONField, but I have migrations that rely on the JSONField from the old library, so I can't remove it. I also can't update Django without removing it because it is deprecated and causes errors when I try to update Django. What's the correct way to proceed in this situation? -
HTTPError at /social-auth/login/twitter/ 403
I am trying to login twitter with oauth. I have included ssl certificate with lets encrypt secure my url,Thus my url is https but still i'm getting this error where should i change in my django code. I have used social-oauth library for twitter login -
Django how to send an email to the drivers after viewing thier form submission?
I am newbie and just see the django documentation of sending mail . i want to send an email to the drivers after seeing their details if they are eligible i want them to send an email using thier email address that they submit while registering to my app . please tell me how do i send a email. i had already set the settings.py email host user all the needs of send an email its working on my other app . but not working on this app . how do i get the driver email and send an email from our company employee. Views.py @csrf_protect def rentacar_carapp_sendmail(request): if request.POST: try: args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = carapp.get('car_app_driver_id.driver_email') join_message = """thankyou we will contact you later """ send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) driver.save() except: pass return HttpResponseRedirect('/mega-admin/rentacar/driver-manager/') Models.py class Driver(models.Model): class Meta(): db_table = "driver" verbose_name = "Driver" verbose_name_plural = "Drivers" ordering = ['driver_firstname', 'driver_lastname'] driver_firstname = models.CharField( max_length=64, blank=False, null=False ) driver_lastname = models.CharField( max_length=64, blank=False, null=False ) driver_email = models.EmailField( blank=False ) -
Multiple bulk updates in Python Process
I am doing bulk updates in 5 tables. It takes a lot of time. So, I decided to do it parallely using python multiprocessing Process object. Here's my code: def bulk_insert_syllabus_data_parallely(self, data_to_insert): syllabus_log.info('inside parallely method') # inserts data using multiprocessing try: processes = [] for key, value in data_to_insert.iteritems(): processes.append(multiprocessing.Process(target=bulk_insert_data, args=(key, value))) for p in processes: p.start() for p in processes: p.join() except Exception, e: syllabus_log.info('Exception=-----%s' % e) def bulk_insert_data(key, value): try: syllabus_log.info('inside insert data-----%s' % key) if key == 'subjects': Table1.objects.bulk_create(value) elif key == 'chapters': Table2.objects.bulk_create(value) elif key == 'goals': Table3.objects.bulk_create(value) elif key == 'los': Table4.objects.bulk_create(value) elif key == 'tus': Table5.objects.bulk_create(value) syllabus_log.info('Successfully inserted0------%s' % key) except Exception, e: log.info('Exception-----%s' % e) log.info('Exception-----%s' % key) I am getting this exception, only 1 process succeeds. Exception is either SSL error: decryption failed or bad record mac or SSL SYSCALL error: EOF detected. WHats the issue here and how to resolve it? Table structure: class TableA(models.Model): s = models.ForeignKey('S') s1 = models.ForeignKey('T', related_name='s_s1') sequence = models.IntegerField(db_index=True) status = models.CharField(default='hidden', max_length=255, db_index=True) modified_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) -
What field in Django Rest Framework allow POST data combining FileField and IntergerField?
I want to write a viewset in Django Rest Framework which allow user upload a list of new Images with these Order number together. But I dont know what field to use in DRF. Hope your guys help me. My serializer: class ContentSerializer(ModelSerializer): fileUpload = FileField(max_length=100000, allow_empty_file=False, use_url=False) order_num = IntegerField(required=False) class Meta: model = Article fields = [ 'fileUpload', 'order_num', ] class ArticleSerializer(ModelSerializer): file_uploads = ListField(child=ContentSerializer(),write_only=True) class Meta: model = Article fields = [ 'file_uploads', ] My Viewset: class FeedEditAPIView(ModelViewSet): ''' Use Form Data to PATCH ''' queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'id' def edit_article(self, request, id): print request.POST.getlist('file_uploads') // This return [u'{"file":{},"order_num":0}'] When I print request POST file_uploads, it return [u'{"file":{},"order_num":0}']. But I want to return [u'{"file":<files_object>,"order_num":0}'] instead of -
Django2. Python vaiable in seperate file
Hello I'm doing a Python Django project and everything is going great so far! I have a separate python file called number.py, and in that file I have a variable named "testvar". I can pass that to my index.html with views.py, but the random number in number.py is always the same when I reload the site and I need it to update everytime. number.py from random import * testvar = randint(1, 100) views.py from django.shortcuts import render from .number import testvar testvar = testvar def index(request): return render(request, 'porsche/index.html', {'testvar' : testvar}) And please tell me if there is a smarter way of doing this, thanks! -
Ajax send request per second and make hight cpu usage
I have application which send request per second to view and there I get data from api and return response from client so Ajax(send request)->View(Send request)->Api(Return response for view)->View(Return response for client), and I saw that's uses a lot of CPU. 1.Why it is usages a lot of cpu? 2.How I can optimization it? - I must press point that I download currencies and I need download data per second 3.Should I use WebSocket? -
Working with pyfirmata via Django views
In my Django views I'm calling an external Python script which imports Pyfirmata and Pyserial like so: django views: # django imports omitted from os import chdir from subprocess import run def index(request): os.chdir('/home/pi') run('python3 script.py', shell=True) print('done') external python script: import pyfirmata, pygame, time port = '/dev/ttyACM0' board = pyfirmata.ArduinoMega(port) ... ... For some reason this works just fine when executed from Django interactive shell. But when I run it from views I get an error saying "function returned with status 1". When I looked into error.log I see only: [Mon Aug 06 12:14:37.948119 2018] [wsgi:error] [pid 16928:tid 1947202608] [client 192.168.1.73:49238] Not Found: /favicon.ico any thoughts ? -
Django search in string value of modelfield
This is a string value that I want to store in a model.CharField: "8;4,8;0;D;0;0;" Is there a way of efficiently querying entries in search for entries where the last value only would be 1? Or for example where one of the two values after the first semicolon would be 6? Or is this a case where it's better to create seperate fields for each value? Which would be unfortunate because than I would need to create 60 or more fields instead of around 10. -
Django update model and related models
I have a Post model with a many to many relationships with a Tag model Here are the definition of the two models Tag model class Tag(models.Model): # fields name = models.CharField(max_length=100, unique=True) # meta class Meta: ordering = ('name',) # str def __str__(self): return self.name Post model class Post(TimeStampedModel): # relations author = models.ForeignKey(User, on_delete=models.CASCADE) tag = models.ManyToManyField(Tag) # fields title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') content = models.TextField() publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10, choices=(('draft', 'Draft'),('published', 'Published')), default='draft') hits = models.BigIntegerField() # get_absolute_url def get_absolute_url(self): return reverse('post_view', kwargs={'pk': self.pk}) # str def __str__(self): return self.title I also setup a form like so: Form class Post_update_form(ModelForm): class Meta: model = Post fields = ['title', 'content', 'tag'] widgets = { 'title': TextInput(), 'content': Textarea(attrs={'rows':'10'}), 'tag': CheckboxSelectMultiple(attrs={) } labels = { "title": "Titolo", "content": "Contenuto", "tag": "Etichette" } The view that controls everything is like so: View class Blog_post_update(UpdateView): template_name = 'blog/post_update.html' form_class = Post_update_form model = models.Post def form_valid(self, form): messages.success(self.request, 'Il post è stato aggiornato') return super(Blog_post_update, self).form_valid(form) def get_success_url(self): return reverse_lazy('blog:post-view', kwargs={ 'pk': self.kwargs.get('pk') }) Finally the template outputs the form. Now, when I try to update the Post model I get the following errors: IntegrityError at … -
Pagination In Django With Postman
I am using Django version 2.1 and I am testing my project using Postman. This is my views.py file :- from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.permissions import AllowAny # Add + List # Retrieve Update Destroy # List: Pagination class ShowAddaView(ListCreateAPIView): from .serializers import AddAddaSerializer from .models import Adda permission_classes = (AllowAny, ) serializer_class = AddAddaSerializer queryset = Adda.objects.all() class RetrieveAddaView(RetrieveUpdateDestroyAPIView): from .serializers import AddAddaSerializer from .models import Adda permission_classes = (AllowAny,) serializer_class = AddAddaSerializer queryset = Adda.objects.all() I am applying GET and POST method in postman. My serializer file looks like this : class AddAddaSerializer(serializers.ModelSerializer): class Meta: from .models import Adda model = Adda fields = '__all__' class UpdateAddaSerializer(serializers.ModelSerializer): mobile = serializers.CharField(required=False) class Meta: from .models import Adda model = Adda fields = '__all__' Now I need to access my data using the GET method in Postman with pagination. Can anyone tell me what changes I need to do to achieve it. -
Django running extra query for __str__ method
I have a models setup like this in django. form django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User) ... def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class SomeOtherModel(models.Model): account = models.ManyToManyField(Account) Now I do query like this. objects = SomeOtherModel.objects.filter(SOMETHING HERE).prefetch_related('account', 'account__user') Everything works fine but where __str__ is called for Account, an extra query runs like this SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 3 Can anyone explain please? -
FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/xvfb-run'
I'm getting this error while running Django test in mac machine, Error: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 696, in run with Popen(*popenargs, **kwargs) as process: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1540, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/xvfb-run' How can install xvfb-run on mac X. I have also installed XQuartz and add path, But problem not solved. Thanks in advanced -
'execfile' not defined in apache2 config
I want to deploy two different Django apps in the same host with the different virtual environment (python2.7 and python 3.6). I had followed the tutorial https://www.thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ to deploy. one of my WSGI scripts is import os import sys import site site.addsitedir('~/.virtualenvs/myprojectenv/local/lib/python2.7/site-packages') sys.path.append('/home/django_projects/MyProject') sys.path.append('/home/django_projects/MyProject/myproject') os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' activate_env=os.path.expanduser("~/.virtualenvs/myprojectenv/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() when I run apache server I get an error ---> Nameserver: name 'execfile' is not defined When I searched for this error I found execfile is not supported in 3.X. But I have 2 Django app to deploy. Please help me to find the solution. Is there any detail you need let me know -
Error during WebSocket handshak
WebSocket connection to 'ws://qa.mytransform.com/inofm1si38rfmdglbgu4453y0hq0r0an/imsindiya' failed: Error during WebSocket handshake: Unexpected response code: 503 -
Upgradingfrom django 1.11 to 2.0.8 python unittests became longer from 18 to 28 minutes
I am updating project which is build on django 1.11 version to django 2.0.8 version and I noticed that backend tests are taking much longer. It is taking now 28 minutes (instead of 18 minutes that was in django 1.11). Do you have any ideas what may cause that problem, because it is crucial for the project to keep the time of the tests less. -
Django server returns empty array when using specific server ip but not another
When I start my Django server with an address of python manage.py runserver 192.168.45.2:8000 and I go to my API endpoint, lets say http://192.168.45.2:8000/api/products/containers then all I get back is an empty array [] even though the server gives a 200 response. But when I close and restart the server using address python manage.py runserver 0.0.0.0:8000 and I go to the exact same endpoint http://192.168.45.2:8000/api/products/containers I get all my API data even though it points to 192.168.45.2 In django settings file I do have the following: ALLOWED_HOSTS = ['192.168.45.2', 'localhost', '127.0.0.1','192.168.1.2'] I get the same results whether I am using my app through Chrome or using Postman to test my Api's. For both they return empty [] with first IP, and no problem with second IP. I must also add that some API's work as expected no matter what address I have, and some do not.