Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django - only admin account can login
I created a function for users to log in to my website. However, it only works if I log in with an admin account, otherwise it cannot detect a registered user exist and said "This is user does not exist". Here is the code: class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data["username"] password = self.cleaned_data["password"] if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This is user does not exist") if not user.check_password(password): raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is not longer active") return super(LoginForm, self).clean(*args, *kwargs) Thanks for any help! -
How to rewrite the APIView's `post` method?
How to rewrite the APIView's post method? I try to rewrite the post method like bellow, but seems it miss something. class CloudServerShutdownAPIView(APIView): """ shut down the server """ serializer_class = CloudServerShutdownSerializer def post(self, request): cloudserver_id = request.data.pop("cloudserver_id") try: openstackServerShutdown(server_or_id=cloudserver_id) except Exception as e: return Response(data="shut down server fail", status=HTTP_404_NOT_FOUND, exception=e) How can I rewrite the post method correctly? -
endpoint that returns a json with all django api endpoints and its structure
I'd like to know if it's possible to get an endpoint that returns all the endpoints of a django api with its structure. I had this in a previous company on a php symphony app. This is what it would look like: Call to /api/expose would return: {/user/{id}: ["name", "age", "bday"], /user/{id}/photos: ["url", "format"].... } thanks -
Django annotate sub-group with totals of parent grouping - optimising the query
I am trying to annotate groupings of a model with totals of a broader group. One reason is to allow me to return percentages rather than raw counts. I have the below subquery and query which give me the desired output, however, it requires making three calls to the Subquery, which is really inefficient; it more than triples the query time. What I think I really want here is to effectively perform a JOIN on the subquery and the main query but I have no idea how to do so in the ORM? It may be that there is not an efficient way to do this using the ORM? I am using Python 3.5, Django 1.11.6, PostgreSQL 9.3.8 subquery = Typing.objects.filter( cell=OuterRef('cell'), ) .values( 'cell', ) .annotate( SumReads=Sum('NumReads'), SumCell=Count('NumReads'), ) Typing.objects.values( 'cell', 'Gene').\ annotate( PerGeneMeanReads = Avg('NumReads'), PerGeneTotalReads = Sum('NumReads'), PerCellSumReads = Subquery(totals.values('SumReads')), CellCount = Subquery(totals.values('SumCell')), GenePercReads = Cast(Sum('NumReads'), FloatField()) * 100 / Cast(Subquery(totals.values('SumReads')), FloatField()), GeneCountPerc = Cast(Count('NumReads'), FloatField()) * 100 / Cast(Subquery(totals.values('SumCell')), FloatField()), ) -
Django WebTest - I fill and save a form, data are updated in the new page but not in the database
I have a test in which I create a Profile model with factory_boy and a biography with value 'Starting biography'. Then I get the form from the page and I fill it the bio field with 'Test Updated Bio' and I see that the response has the updated value, but the database has not. When I get the profile page after update I have the 'Test Updated Bio' in the HTML and 'Starting biography' in the biography field of the Profile model. class ProfileFactory(DjangoModelFactory): class Meta: model = 'profiles.Profile' #user = SubFactory(UserFactory) user = SubFactory('users.tests.factories.UserFactory', profile=None) bio = 'Starting Bio' def test_user_change_biography(self): test_bio = 'Test Updated Biography' form = self.app.get( reverse('profiles:update'), user=self.profile.user, ).form form['bio'] = test_bio tmp = form.submit().follow().follow() print('\n\n\n', tmp, '\n\n\n') print('\n\n\n', self.profile.__dict__, '\n\n\n') self.assertEqual(self.profile.bio, test_bio) I thought that there could be some caching mechanism but I don't know. Some ideas ? -
Django - wkhmltopdf - CalledProcessError (only works with sudo from command line)
I'm trying to render PDF from Django template using django-wkhtmltopdf. The problem is that wkhtmltopdf started raising: Command '['/usr/bin/wkhtmltopdf', '--encoding', u'utf8', '--quiet', u'False', '/tmp/wkhtmltopdfRDyi61.html', '-']' returned non-zero exit status 1 Can't figure out where the problem is but I noticed that I can't even do in command line (I'm in virtualenv): wkhtmltopdf http://www.google.com g.pdf Loading pages (1/6) QPainter::begin(): Returned false============================] 100% Error: Unable to write to destination Exit with code 1, due to unknown error. It works only with sudo privileges (but I'm in PyCharmProject my users directory): sudo wkhtmltopdf http://www.google.com g.pdf I also noticed that some of the temporary html files from /tmp/ folder wasn't deleted. This is a whole traceback Django returns: TRACEBACK: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/render/ Django Version: 1.11.7 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'agreements', 'weasyprint'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/django/template/response.py" in render 107. self.content = self.rendered_content File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/wkhtmltopdf/views.py" in rendered_content 78. cmd_options=cmd_options File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in render_pdf_from_template 186. cmd_options=cmd_options) File "/home/milano/.virtualenvs/maklerienv/local/lib/python2.7/site-packages/wkhtmltopdf/utils.py" in convert_to_pdf 124. return wkhtmltopdf(pages=filename, … -
Wagtail: Can i use the API for fetching read-only drafts of pages for review?
The title pretty much sums up the question, the early docs talk about a /revision endpoint but i cannot find if it was ever implemented. Wagtail have excellent functionality to edit and save the pages, i just need to preview how the draft looks when consumed by my application. -
Web Appliation that works completely offline
i started creating a TaskManger/ProjectManager in C#. It s about managing tasks and project as efficient as possible. This Project included a SQL DataStorage for Text and Images (RichTextBox).Played also with OCR. Tasks have been ranked similar like on TaskWarrior (https://taskwarrior.org/). The database is growing pretty fast. I am trying to implement this at Work. My Question anyway is moving away from desktop application to Web Appliation: Can i create this kind of project as an WebApplication that could work completely offline? I mean lets say my co worker having a link of the (lets say) html file (that would be saved on a global folder of our company) and the are able to work completely offline? Thank you all for your time and effort! BR Nasuf