Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Inline Formsets - clean() method not working
So I have a django inline formset created by django.forms.inlineformset_factory, which contains a parent: ParentCount, and child: ChildCount. Inside the ChildCount form I have rewritten the clean method as such: class ChildCountForm(ModelForm): class Meta: model = ChildCount exclude = ["name"] def clean(self): cleaned_data = super(ChildCountForm, self).clean() att1 = cleaned_data.get("att1") att2 = cleaned_data.get("att2") if att1 == "I3i" and att2 is None: msg = "Require att2 information for I3i attribute" self._errors['att2'] = self.error_class([msg]) """Returns the cleaned data""" return cleaned_data I thought this would get called for each ChildForm inside the formset, as the inlineformset_factory is defined using a custom form class, which uses the logic: class CustomInlineFormset(BaseInlineFormSet): """used to pass in the constructor of inlineformset_factory""" def clean(self): """forces each clean() method on the ChildCounts to be called""" super(BaseInlineFormSet, self).clean() for form in self.forms: form.clean() ChildFormSet = inlineformset_factory(ParentCount, ChildCount, form=ParentCountForm, extra=1, max_num=30, formset=CustomInlineFormset) However, at this point in the form, the clean method() of each form is not derived from ChildCountForm, it's derived from BaseModelForm. If I instantiate an empty ChildCountForm at that line in the pdb, it says it derives the clean method from ChildCountForm, but the 'form' object in self.forms doesn't. Why is this? How can I get my custom clean() … -
Working with django and sklearn enormous models
I'm working on a django project that uses sklearn SVR models. The training part takes a lot of time and I need to use it relatively fast, so I'm trying to do the training part offline and store it in db / filesystem, and then the online just load it and use the models. Problem is, when I try to use cPickle to serialize the data, I end up with over 500MB at best (and sometimes couple of GBs at worse). I can't load so much data online fast enough, it will make requests very slow. So my question is, whats the recommended way to use sklearn SVR with django, when I want high performance? Should I use cPickle to serialize / deserialize or something else? Should I zip it? And what about loading, obviously I can't load this whole data per request, so is the way to go is putting it in cache? Thanks, -
Index of / cgi-bin/ error. Nginx. Gunicorn. Django
I've followed this tutorial for deploying a Django / Nginx / Gunicorn application. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04 All is working.. most of the time.. Every so often (random to say the least) the application doesn't load and I end up with an Index Of / page. There is only one option. 'cgi-bin' which just loads a page and states I don't have permissions. I do get this note though. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. I've looked in the Nginx logs. Nothing. Are there other logs I can look in to discover more? -
compare django template tag to integer
I want to compare the django template tag to integer in javascript in html. Here's my html. <script> {% for schedule in schedules%} if({{schedule.get_month}}<10){ { title: '{{schedule.title}}', start: new Date({{schedule.get_year}},0{{schedule.get_month}},0{{schedule.get_day}},{{schedule.get_hour}},{{schedule.get_minute}}), allDay: false, className: 'success' }, } else{ { title: '{{schedule.title}}', start: new Date({{schedule.get_year}},{{schedule.get_month}},0{{schedule.get_day}},{{schedule.get_hour}},{{schedule.get_minute}}), allDay: false, className: 'success' }, } {% endfor %} </script> My return schedulre.get_year is 6. So result of if({{schedule.get_year}}<10) is if(6<10). But the part get an error (index):213 Uncaught SyntaxError: Unexpected token if. What's the problem of if? If it can't be solved. I want to return the month and day by django datetimefield like 6 ->06, 11->11. Here's my models.py class Schedule(models.Model): Trainer = models.ForeignKey(User, null=True, related_name='schedule', on_delete=models.SET_NULL) title = models.CharField(max_length=12) start = models.DateTimeField() def get_year(self): return self.start.year def get_month(self): return self.start.month-1 def get_day(self): return self.start.day def get_hour(self): return self.start.hour def get_minute(self): return self.start.minute But I don't know how return 6 -> 06 in model. So I tried it in template but I get 'if' error. Any advice will be very helpful to me, thanks! -
How to make facebook authentication pop-ups using python-social-auth
I'm using social-auth-app-django with FacebookOAuth2 backend what is based on python-social-auth and trying to set display=popup at facebook authentication trought app settings. Found this old issue for django-social-auth what is deprecated in favor of python-social-auth, but that options doesn't work. -
The URL is not being matched/found: django
In my urls.py, i have this entry: url(r'^get-advice/(?P<groupid>[0-9]+)/(?P<catid>[0-9]+)/(?P<style>[a-zA-Z]{6,11})/(?P<zone>[0-9]+)/$', views.give_insight, name='get-advice'), I was hoping this would work: http://localhost:9000/tips/get-adivce/6/1/sqare/1200 http://localhost:9000/land/get-adivce/6/1/sqare/1 http://localhost:9000/land/get-adivce/6/1/sqare/13 But nothing is being matched. The following works fine: http://localhost:9000/tips/view-tips/6/1/ for url: url(r'^view-tips/(?P<groupid>[0-9]+)/(?P<catid>[0-9]+)/$', views.give_insight, name='view-tips'), -
generating static site from mezzanine
There is a tested way to generate a static site from a mezzanine app? Currently I m working on this simple html static site, but mostly in future it will have feature like blog and admin area. So, I decided to design it in Mezzanine. But so far, I need just a simple static file, without any db. Any suggestion? Thank you so much! -
Django create a Datatable using MSSQL
Hello I am new to using Django and would like to create a datatable with data that is stored in a database of an MSSQL server. I have managed to connect Django via django_mssql but I do not know how to access a table since there are many in the database. Thanks for your help. -
IntegrityError :Not Null constraint failed
Please help me out .I have deleted a class from model.py but when ever i run python manage.py migrate ,i get this intergrityerror : not null constraint failed: appname_modelclassfieldname.user_id . The most challenging thing is that i had already deleted the model class of the related field django is pointing error at . -
Swisscom Appcloud S3 Connection reset by peer
We have a Django Webservice that uses Swisscom AppCloud's S3 solution. So far we had no problems, but without changing anything on the application we are experiencing ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer')) errors when we are trying to upload files. We are using boto 2.41.0. The error occures after about 15s so I don't think it's the uwsgi that shuts down the connection. from django.conf import settings from boto3 import session from botocore.exceptions import ClientError class S3Client(object): def __init__(self): s3_session = session.Session() self.s3_client = s3_session.client( service_name='s3', aws_access_key_id=settings.AWS_ACCESS_KEY, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, endpoint_url=settings.S3_ENDPOINT, ) . . . def add_file(self, bucket, fileobj, file_name): self.s3_client.upload_fileobj(fileobj, bucket, file_name) url = self.s3_client.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': bucket, 'Key': file_name }, ExpiresIn=60*24*356*10 # signed for 10 years. Should be enough.. ) url, signature = self._split_signed_url(url) return url, signature, file_name Could this be a version problem or anything else on our side? -
LocaleMiddleware redirects on a non-i18n url pattern
I'm using Django's LocaleMiddleware to internationalize a part of the website I'm working on. Here is my project's urls.py: from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns urlpatterns = patterns('', url(r'^api/stuff/(?P<stuff_id>)\d+/$', ApiStuff.as_view()), ) urlpatterns += i18n_patterns('', url(r'^stuff/', DoStuff.as_view()), ) The problem is, when ApiStuff.as_view() returns a 404 response (other error codes behave as expected), the LocaleMiddleware operates the request to make it redirect to /en/api/stuff/<stuff_id>, even though the /api namespace is clearly not in the i18n_patterns (at the end, it generates a 404 error too, but the content of my original response is lost). Here is the code of ApiStuff: import django.http from django.views.generic import View from project.stuff.models import Stuff class ApiStuff(View): @staticmethod def get(request, *args, **kwargs): stuff_id = kwargs['stuff_id'] try: stuff = Stuff.objects.get(pk=stuff_id) except Stuff.DoesNotExist: return response({"error": "stuff not found"}, 404) result = stuff.serialize() return response(result) def response(data, status=200): data = json.dumps(data) return django.http.HttpResponse(data, status=status, content_type='application/json') I'm using django 1.6.10 (I know, it's late, but I can't update the version right now). Am I missing something? -
Best practice for Websocket authentification - Django Channels
Is there any ready to use Django Channels authentication method for the websocket client? So far I did following, the client connects normally via websocket and the first message he should send is an authentification message: import json from channels import Group def login(params, message): print "login" if "Username" in params and "Password" in params and "ApplicationName" in params: if params["Username"] == "dummy" and params["Password"] == "1234" and params["ApplicationName"] != "": message.reply_channel.send({"text":json.dumps({"authentification":"succeeded"})}) return message.reply_channel.send({"text":json.dumps({"authentification":"unsucceeded"})}) message.reply_channel.send({"close": True}) routing.py from . import consumers from channels import route channel_routing = [ route('websocket.connect', consumers.ws_connect), route('websocket.receive', consumers.ws_receive), route('websocket.disconnect', consumers.ws_disconnect), ] consumers.py @channel_session def ws_receive(message): text = message.content.get('text') dict = json.loads(text) if "connect" in dict: login(dict["connect"], message) -
How to get string value of user id type <class 'str'> [facebook messenger bot]
I'm creating facebook messenger app that is text based but does not require user to write specific commands. I'm using python 3.6 and django 1.11. The app asks for user's input and updates the phase that user has accomplished to database. This system requires me to save user id to database and I have done that already. It works. Instead.. when I try to create a database query it won't return any rows if I use the data from user's messenger message. Here's how I create a record to database: feedback_object, created = Feedback.objects.update_or_create( source_created_at=feedback_start_at, user_id=message['sender']['id'], defaults={ 'message': message['message']['text'], 'phase': feedback['phase'] } Here's query that I CAN get the data from database: r = Feedback.objects.filter(user_id='12345').latest('source_created_at') Here's query that DOES NOT work but I need something similar: r = Feedback.objects.filter(user_id=message['sender']['id']).latest('source_created_at') -
How to create file and write input content and save it inside the project folder using Python
I need one help. I need to create one file (.txt) and write the contant inside it and save it into that project folder. I am explaining my code below. if request.method == 'POST': param = request.POST.get('param') param1 = cgi.escape(param) uid = uuid.uuid4() new_id = uid.hex Here param variable is containing my input value. Here I also save that file using uniqueid. I have also one requirement Sanitize the parameter to be used in file. so finally that input value will write in the new file and that file will save inside the project folder. -
Django - unavailable field of model while doing migration
maybe I am exhausted and don't see something simple, but in Django 1.9.7, while doing the migration I found something strange, and I am looking for an explanation. While getting a model class by apps (it is (django.db.migrations.state.StateApps) in RunPython operation I have AttributeError for the field which exists. My model: class Weight(models.Model): INF = 2**31-1 minimum = models.PositiveIntegerField() maximum = models.PositiveIntegerField() carrier = models.ForeignKey(Carrier) class Meta: ordering = ['carrier__name', 'minimum'] in migration method runned from RunPython, I have: Weight = apps.get_model('calc.Weight') then have exception, but only for some fields. from debugging (inside method runned by RunPython): >>> Weight.maximum Traceback (most recent call last): File "<pudb command line>", line 1, in <module> AttributeError: type object 'Weight' has no attribute 'maximum' >>> Weight.minimum Traceback (most recent call last): File "<pudb command line>", line 1, in <module> AttributeError: type object 'Weight' has no attribute 'minimum' >>> WeightRange.INF Traceback (most recent call last): File "<pudb command line>", line 1, in <module> AttributeError: type object 'WeightRange' has no attribute 'INF' but: >>> WeightRange.carrier <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7f8dcca692d0> >>> Weight._meta.fields (<django.db.models.fields.AutoField: id>, <django.db.models.fields.PositiveIntegerField: minimum>, <django.db.models.fields.PositiveIntegerField: maximum>, <django.db.models.fields.related.ForeignKey: carrier>) type(Weight) <class 'django.db.models.base.ModelBase'> so somehow only carrier field is available, why? a syntax and names are OK, … -
KeyError: 'title' on cleaned_data
I've been unable to find a solution to my problem from searching. So I'd like to ask what might be wrong with my code. I'm trying to validate a form from forms.ModelForm but in my views function it'll pass me KeyError: 'title' Model: class Paper(models.Model): title = models.CharField(max_length=100, help_text='Hello World!') forms.FormModel class eventCreateForm(forms.ModelForm): class Meta: Paper = Event fields = ['title'] widgets = { 'title': forms.TextInput(attrs={'class' :'form-control', 'placeholder' : 'Place title'}), } Views def create_paper(request): context = {} if request.method == 'POST': form = paperCreateForm(request.POST or None, request.FILES or None) if form.is_valid(): form_data = form.cleaned_data t1 = form_data['title'] print(t1) else: form_data = form.cleaned_data t1 = form_data['title'] #<--- error print(t1) context['paper_event_form'] = form form_template = "user/paper-event-template.html" return HttpResponse(render_to_string(form_template, {'context' : context})) The form dosen't get validated, and in the else clause it'll pass the error when trying to retrieve it from the cleaned_data I did try and print the form, and it shows -
url with multiple optional arguments
right now I have a view to show info about some tickets and I'm trying to add a functionality to filter those tickets. Say I will have 4 filters: Date Owner Category Status Category Status I want to give the option to use some of those filters, all or none, the thing is I'm kinda lost in how can I make it work in the urls. So far I found that you can add some optional arguments but they appear in some sort of succession like: /May/Jack/Gas/Accepted But if I only select 2 filters like /Jack/Accepted/ it grabs the filters incorrectly. Is there a way I can achieve this? Or some other method I can use instead of this. Ty -
mail utility sends the message, but django no
I have the some problem. I want to send email via django application, but i can't: "smtplib.SMTPRecipientsRefused: {'': (451, 'Temporary local problem - please try later')} So, i tried to send via mail utility: echo -ne "Some test body letter" | mail -s "Test subject" '<my email>' and it sends the email on my email address. But the following script print error messages: #! /usr/bin/python2.7 # -*- coding: utf-8 -*- import os import time import urllib2 import django from datetime import datetime os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' os.environ['EMAIL_BACKEND'] = 'django.core.mail.backends.smtp.EmailBackend' os.environ['EMAIL_HOST'] = 'localhost' django.setup() from django.core.mail import EmailMultiAlternatives from email.MIMEImage import MIMEImage import time import sys import datetime from django.template.loader import get_template from django.template import Context from django.core.mail import send_mail import smtplib subject, from_email, to = 'Test subject', 'root@<server hostname>', '<my email>' html_content = "Some test body letter" print "Attempt 1. smtplib" try: s = smtplib.SMTP('localhost') s.sendmail(from_email, [to], html_content) s.quit() except Exception as e: print "ERROR: %s" % str(e) print "Attempt 2. send_mail" try: send_mail( subject, html_content, from_email, [to], fail_silently=False, ) except Exception as e: print "ERROR: %s" % str(e) print "Attempt 3. EmailMultiAlternatives" try: msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() except Exception as e: print "ERROR: %s" % … -
Distinct values with multiple Sum aggregations on reverse relation
According to the Django docs combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries. They furthermore note, that Count has a distinct parameter that may help. Is there something similiar to Sum? I end up with wrong results in this stripped down example. The amount values are too high in most cases. qs = Client.filter('project__date__year=2017').annotate( isum=Sum('project__ioffer__amount', distinct=True), esum=Sum('project__eoffer__amount', distinct=True) ) The distinct=True parameters don't make any difference. -
How to Remove validation from left table data in django
API Sample Screenshot I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation but i want to remove validations from company_name, location, title and user_location fields how to do? Please find the above api screenshot and -
Django admin/template does not change the value that changed in mysql?
On the production appeared a strange bug, there is a table blog_category_translation with fields id | language_code | name | master_id sql query: mysql> select * from blog_category_translation; +----+---------------+------------------+-----------+ | id | language_code | name | master_id | +----+---------------+------------------+-----------+ | 1 | ru | New Category RU | 1 | in field name there is value New Category RU Then through the admin area I change this value to New Category RU1, again sql query: mysql> select * from blog_category_translation; +----+---------------+------------------+-----------+ | id | language_code | name | master_id | +----+---------------+------------------+-----------+ | 1 | ru | New Category RU1 | 1 | That's fine. But not in admin-panel: admin panel, don't change value But there is an old value. If reload page there is new value, if i yet reload page there is new value, if i yet reload page there is old value, etc. Django toggle value in view. Sorry for my bad english (((. I used Emperor mode:digitalocean.com Emperor mode -
Python Try: except: else: deleting temporary variables
In my Django views.py, I potentially build around 50 derived time series for any given instance of my Project model; depending on its attributes. Only if each parameter required for a derived attribute is valid, I then append the label/cost/start/end to the their corresponding list. To try and handle this, I put each calculated variable into a temporary variable and only fill the df_ lists in the else: section if they all have valid values. However, this means that I'm manually clearing the temporary variables each time (del cost, del start, del end). I'm guessing there is a better way...?! views.py #... df_label=[] df_cost=[] df_start=[] df_end=[] #First potential derived elements for DataFrame try: cost= #custom calculation here start= #custom calculation here end= #custom calculation here except: error_message.append("Warning1") else: df_label.append('Label here') df_cost.append(cost) df_start.append(start) df_end.append(end) del cost del start del end #Second potential derived elements for DataFrame try: cost= #custom calculation here start= #custom calculation here end= #custom calculation here except: error_message.append("Warning2") else: df_label.append('Label here') df_cost.append(cost) df_start.append(start) df_end.append(end) del cost del start del end #...repeat ~50 times #Create DataFrame from all the df_ lists df = pd.DataFrame() df['label']=df_label df['cost']=df_cost df['start']=df_start df['end']=df_end -
How to find all week numbers that are first week of month in a year python
I want to create a event that fall on Sunday of every first week of months. This is what i am doing for a particular week number which is first week of june to get date. from datetime import datetime myDate = "2017 22 0" # here `2017` is year, `22` is week number and `0` =sunday is week day datetime.strptime(myDate, "%Y %W %w") #Desired output... datetime.datetime(2017, 6, 4, 0, 0) So i need list of all week numbers that are first week of month so i can loop on it and get desire dates. Please help me out and let me know if i am not clear. -
Email admins when 4XX error occurs in a certain app
How to email admins when 4XX error occurs in a certain app? Is there any logging configuration which allows this? -
Filter JSON data in TextField
Version that I use: psycopg2==2.6.2 django=1.10.5 postgres=9.3 I want to store JSON data to the database using Django, but I can't use JSONField() because it needs jsonb type that only present in PostgreSQL >=9.4. My Django model is as follows: class Inspection(models.Model): data = models.TextField(null=False, blank=False) In the data field I want to store JSON data. The data is as follows: Record1: { "url": "some_url", "user": [ { "id": "1", "email": "myemail@hotmail.com", "first_name": "My_First_Name", "last_name": "My_Last_Name" } ] } Record2: { "url": "some_url", "user": [ { "id": "2", "email": "myemail_2@hotmail.com", "first_name": "My_First_Name_2", "last_name": "My_Last_Name_2" } ] } Can I filter on user id?