Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FIle handling and delivery in a Django ELastic Load Balancer deployment
So I have a Django app deployed in AWS Elastic Beanstalk that generates a web page and collects user data for various tables when the user loads the page, clicks a link, etc. All this data is currently recorded on an RDS database. At periodic intervals, the data for the day is collected (potentially several million rows) and stored in a series of CSV files. The data is then sent to an FTP server to be analysed later. There are also cleaning operations ran to delete data a few days old from the database as well. I'm thinking that I can potentially remove some overhead and complexity from the project by removing the DB aspect altogether. I shall instead write out the data to files located on the instance, gzip them and send the file over. A few potential issues occur to me though: If my load balancer scales up to more than one instance (currently just one), how can I make sure that each instance receives a command at X hour in the day to get the current file, zip it and send to the FTP? How can I uniquely identify which instance the file came from? They have … -
Unable to install pycrypto on ubuntu 14.04 with python3
I'm trying to install stream package with pip install stream_django which has pycrypto dependency. So while installing pycrypto dependecy it returns me RuntimeError: autoconf error error. How can i install pycrypto on ubuntu 14.04 with python3 -
Django thread don't read valor updated
In my models.py I hace a class how control the thread life: class Repartidor(models.Model): thread_active = models.BooleanField(default=False) def launch_thread(self): self.thread_active = True self.save() def kill_thread(self): self.thread_active = False self.save() def get_thread_state(self): if self.thread_active: return True else: return False In repartidor.py I declare the thread: class RepartidorThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(RepartidorThread, self).__init__() self.target = target self.name = name def run(self): repartidor = Repartidor.objects.get(pk=1) while True: condition = repartidor.get_thread_state() print(condition) if condition: do_something() time.sleep(1) else: pass time.sleep(1) And launch the thread in wsgi.py from printers.repartidor import RepartidorThread thread_repartidor = RepartidorThread(name='Thread_Repartidor') thread_repartidor.start() But I have a problem, I read the condition in repartidor.py with get_thread_state() and it return True or False. If I change the condition through the django_admin or through my frontend, the value of the database is updated, and all my project read the new valor, except the thread, which always reads the first one. If I stop and start the server, the thread read the new valor. Why is this happening? -
Django wagtail 1.9 API V2
I am new to Wagtail and i have managed to follow the documents here and here. I am able to get page information, however how do i return images (their path)? All the solutions online seem to be amended for V1. { id: 46, meta: { type: "wagtailimages.Image", detail_url: "http://192.168.0.38:8002/api/v2/images/46/", tags: [ ] }, title: "a", width: 409, height: 307 } How do i get the URL? -
are django model queries cached?
Let's say I have a model_a that has foreign key to model_b and I am accessing model_b's properties like so: model_a = ModelA.objects.get(id=id) x = model_a.model_b.x y = model_a.model_b.y z = model_a.model_b.z Is Django going to the DB and joining the tables to get x, y, and z fields on each line? Or does Django store the result of the first join and then no more joins are needed? Is this in any way, performance-wise? model_b = model_a.model_b # only one join x = model_b.x y = model_b.y z = model_b.z Just curious -
Django blog post view
What is the best to create class based post view with post details, comments, comment form? I tried somethink like that: class PostView(DetailView, FormView): ... and in the post method if required.post is form, I create comment in the view. What you think about? Do you have any examples blog post + comment form in one view in class based views? -
[Django]: How can i read next entry from MySql upon clicking a button from HTML form.
I am new to Django as well as HTML, I have 5 entries in database (MySql) x.objects.all returns all in one go but as per requirement i want to read each row upon clicking of a button from HTML form. Tried x.object.get(pk=var) by changing var on each click but somehow not able to do it. Any pointer will be helpful here, thanks in advance. Madhur -
filter using a many to many (through) field django model
I have this definitions into models.py: class Group(models.Model): created = models.DateTimeField(auto_now_add=True) products = models.ManyToManyField(Product, through='ProdGroup') class ProdGroup(models.Model): groups= models.ForeignKey(Group, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) is_prd_main = models.BooleanField(default=False) class Product(models.Model): id = models.CharField(primary_key=True, default='', max_length=12) I want to check if I already have a Group with the same products in the database. (and also check if the prd_main is the same). I don't know if it's a problem with the through option but this doesn't work: group = Group.objects.all()[0] # an instance already in the db Group.objects.filter(products__exact=group.products) <QuerySet []> it's there a way, given an object group to check of its already in the db?, it's there a way to obtain all the products and filter all the Groups with the same unique set of products? -
global list on Celery with Django
I'm using Celery to save global list since I cannot use global variable in Django. I add items to that list on demand. The problem is that when I try to get the global list from Celery, sometimes I don't get the updated list. For example, I might get empty list when I know I already inserted items to it. I saw here that Celery run with multiple process so I edited the running command of Celery to - celery -A tasks worker -c1and now I should have only one process but still for some reason I have the same problem. Note: when I fail to get the right list and I refresh the page few time I do get the updated list. I think maybe Celery is still run few process instead of one or running few threads but it really shouldn't since I use the flag -c1 -
JSONDecodeError, when use json.loads in Django
JSONDecodeError, when use json.loads in Django. def post(self, request): data = json.loads(request.body) pprint(data) return HttpResponse(data) -
Default value not setting Boolean Field Pgsql
In my project I have created a boolean field with default value as false using django models. But whenever I am trying to save into that table I am getting the error saying that null value in column "dmz" violates not-null constraint what could be the reason. What am doing wrong This is my model field dmz = models.BooleanField(default=False, blank=False) -
Nested serializers in drf throws error with one to one field
My input json is : { "availability": "Current", "drive_type": [{ "drive_name": "drive1", "requirements": { "performance_unit": "by_iops", } }] } I am getting error Cannot assign "OrderedDict([('performance_unit', 'Basic')])": "DriveType.requirements" must be a "Requirements" instance.I am not able to figure it out to map in create method for one to one fields in tables Below are my models.py class ProductLine(models.Model): availability = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = "product_line" class DriveType(models.Model): drive_name = models.CharField(max_length=20, blank=True, null=True) product_line = models.ForeignKey(ProductLine, related_name="drive_type") class Meta: db_table = "drive_type" class Requirements(models.Model): performance_unit = models.CharField(max_length=100, blank=True, null=True) drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name="requirements") class Meta: db_table = "requirements" Serializers.py : class DriveTypeSerializer(serializers.ModelSerializer): requirements = RequirementsSerializer(many = True) class Meta: model = DriveType fields = ( "drive_name","workload_type") class ProductLineSerializer(serializers.ModelSerializer): drive_type = DriveTypeSerializer(many=True) class Meta: model = ProductLine fields = ('availability', "drive_type") def create(self, validated_data): print("validate_data",validated_data) drive_type_data = validated_data.pop("drive_type") product_line = ProductLine.objects.create(**validated_data) for drive_data in drive_type_data: drive_type = DriveType.objects.create(product_line=product_line, **drive_data) return product_line -
How to setup supervisor of my django application and libapache2-mod-wsgi with out gunicorn
I am deploying my django app and setup apache, wsgi and django and its working fine on my ec2 instance. The urls are routed from web server to application server. Now I want to setup supervisor for the same, but with no luck, I researched a lot and every article has explained config with gunicorn. I do not want to go with gunicorn. Please help -
Passing pickle file or Python object between two Django servers
I'm building a small application which requires two serves to exchange pickle file or a python object , anyone will do. As i am new to Django, i having hard time doing so. Please look at the code. Sender: def get(self, request): message ="hello" pickle.dump(message, open("test.p", "wb")) filename = "test.p" #content = 'any string generated by django' response = HttpResponse(message, mime_type='application/python-pickle') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response Receiver: with open("sample1.p", 'wb') as fd: for chunk in response.iter_content(): fd.write(chunk) with open("sample1.p", 'rb') as handle: var = pickle.load(handle) -
Django is it the best to develop an online game? [on hold]
I have to realise a web application : game"superbuzzer" in a short period two weeks but I don't know if Django is the best one or you advise me to use another framework ? -
How do I set up Angular 4,webpack and Django together?
I am having Angular 4 application and django running separately. Angular application gets the data from HTTP request where the django has RESTful API which exposes JSON data. Now I need to integrate Angular 4 and django with Webpack running as single application.How do i do that?? -
circular dependency in Django models
I have 2 apps named social and instagram. The structure of models.py file is as follows : In social app : from instagram.models import User as instagramUser class User(models.Model): # some fields class Meta: abstract = True class Foo(models.Model): # Some fields def save(self, *args, **kwargs): # some validation on User models from instagram app (instagramUser) super(Foo, self).save(*args, **kwargs) and in instagram app : from social.models import User as socialUser class User(socialUser): # Some additional fields Conceptually this structure is correct and the model Foo should be located in social app. But as expected when running circular dependency occurs. I want to keep conceptual correctness while resolving the circular dependency. How can I do that? -
pymongo skip and limit is giving inconsistent response
I am using django and mongodb. In mongodb collection there large no of records. So for pagination purpose I am using skip() and limit() but it is not giving expected results. queryObject = Notification._get_collection().find({"email_id": email_id}).sort([("timestamp",-1)]).limit(limit_records).skip(skip_records) where, display_records = 10 , skip_records = (page_no-1)*display_records, limit_records = display_records + skip_records In this case I expect to get 10 records for every page request, but it is not working this way. Sometimes I get 10 records, sometimes 20,30. Collection has around 10000 records. Kindly suggest me solution. Thanks in advance. -
Start django app as service
I want to create service that will be start with ubuntu and will have ability to use django models etc.. This service will create thread util.WorkerThread and wait some data in main.py if __name__ == '__main__': bot.polling(none_stop=True) How I can to do this. I just don't know what I need to looking for. If you also can say how I can create ubuntu autostart service with script like that, please tell me ) -
django group by foreign
This is my model.py class SubService(): name = ................. class SubServiceReportField(): sub_service = models.ForeignKey(SubService,related_name='labtest_for_report') This is my serializers fields = ( 'SubServiceReportField', 'sub_service', ) I want to group it by 'sub_service' like.... [ { SubServiceReportField: [{SubServiceReportField 1}, {SubServiceReportField 2}], subservice: name }, { SubServiceReportField: [{SubServiceReportField 1}, {SubServiceReportField 2}, {SubServiceReportField 3}], subservice: name } ] Please help with any type of operation...... Thanks -
python/django validate email
i'd like to validate an email address in django, I'm using validate_email and this is the function i wrote. def check_email(self, email): # import pdb; pdb.set_trace() import re try: return validate_email(email) except: return False Here is where this is function is called deco = mapped_data['email_receiving'] email = deco.encode('ascii', 'ignore') if not self.check_email(email): return Response({"errors": {"error": ["Incorrect email address!"]}}, status=status.HTTP_400_BAD_REQUEST) The validation seems to be buggy, return 404 even though the email is correct, any help ? -
Sending multiple arguments with "or" to a class?
how are the instances of a class created if we send arguments to a class using "or". views.py form_ = SchoolForm(request.POST or NONE) form.py class SchoolForm(forms.Form): name = forms.CharField() location = forms.CharField(required=False) -
want to output a list of dictionaries as a single dictionary in django rest api using modelserializer
from rest_framework import serializers from .models import NewsFeed class NewsFeedSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" model = NewsFeed fields = ('title', 'description', 'image', 'source_url','source_name','metadata','created_date') returns This is what is returned While I want enter image description here notice how a list of dictionaries are sent as one single dictionary under "feeds". -
Can't delete images from media library in admin interface in Mezzanine
I'm trying out Mezzanine on Windows 10. When I try to delete images from the media library in the admin interface, it says "An error occurred" and doesn't delete them. The browser's developer tools and django-debug-toolbar don't indicate anything wrong. I found these two threads: Mezzanine 3.1.10: Can't delete the media files in the admin page Filebrowser can't delete files on Windows #53 The first isn't resolved and I don't understand the solution in the second. I'm new to Django and Mezzanine so maybe I'm missing something. Can someone explain the problem? Thanks. -
UpdateView showing blank forms and not save the previous data in Django
I'm using UpdateView to edit data using forms. After I click to edit the popup using modal is showing a few forms with blank data! It doesn't retrieve the previous data that was in the Database. Anyone know what should I add? I am stuck with this edit for about 2 weeks.. Does anyone have a clue what should I add? I did instance=post in the new form... views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() forms = {} if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() for post in posts: forms[post.id] = HomeForm(instance=post) args = {'form' : form, 'forms': forms, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post …