Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'NoneType' object is not callable - save()
I'm working on Django project and I have to get title from external URLs provided by user. I'm able to get title, but when I want to save it to DB, it gives me "'NoneType' object is not callable" error. When I make hard coded title in code, it save it without any error. Here's my view: form = ShrinkURL(request.POST or None) if form.is_valid(): url = form.save(commit=False) url.user = request.user url.link = form.cleaned_data['link'] site = url.link hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} req = Request(site, headers=hdr) source = urlopen(req).read().decode('utf8') bs = BeautifulSoup(source, 'html.parser') t = bs.find('title') url.title = t url.clicks = 0 url.revenue = 0.000 url.shrink = get_random_string(length=5) url.active = True url.save() -
ModelForms for updating and creation
I have a view/form that's working great to edit Assessment objects; it pulls in a list of Standard objects to be chosen, based on the Standards associated with the current Course. I'm trying to implement this now to open in a modal to add a new assessment, but I'm getting "RelatedObjectDoesNotExist at /gbook/1-1/1 Assessment has no section." This scheme has worked just fine with other objects, but I wasn't doing the filtering thing for those, and that's where the error is coming. view (not working): assessmentaddform = AssessmentAddForm(prefix='assadd') modal: <div class="modal fade" id="AssessmentAddModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header" style="padding:5px 10px;"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4>Add Assessment in {{this_course.Name}}/{{active_section.Name }}</h4> </div> <div class="modal-body" style="padding:10px 10px;"> <form data-parsley-validate method="post" id="assessmentaddform" action="" enctype="multipart/form-data" data-parsley-trigger="focusout"> {% csrf_token %} {{ assessmentaddform.as_p }} <p id="login-error"></p> <input type="submit" class="btn btn-info submit" name="AddAssessment" value="Add Assessment" /> </form> </div> <div class="modal-footer"> </div> </div> <script> $(document).ready(function(){ $("#AddAssBtn").click(function(){ $("#AssessmentAddModal").modal(); }); }); </script> </div> </div> view (working): if to_edit == "ass": if request.method == "GET": assessment_list = Assessment.objects.all().filter(section__in=[active_section]).order_by('-Date')[:4] if pk: this_assessment = Assessment.objects.get(pk=pk) else: this_assessment = None #announcementeditform = UpdateAnnouncement() details = {'instance': this_assessment, 'sectionid': active_section.pk} form = AssessmentAddForm(None, instance = this_assessment) context = {'active_courses':active_courses, 'this_course': this_course, … -
"This session is in 'prepared' state; no further" error with SQLAlchemy using scoped_session in threaded mod_wsgi app
I recently updated to SQLAlchemy 1.1, which I'm using under Django 1.10 (also recently updated from 1.6), and I keep getting sqlalchemy/mysql errors that This session is in 'prepared' state; no further SQL can be emitted within this transaction. How do I debug this? It's running in single process, multi-threaded environment under mod_wsgi - and I'm not sure if I've properly configured SQLAlchemy's scoped_session. I use a request container, such that each incoming request, gets this class which sets up the session and cleans it up. I'm assuming each request (in Django), is on it's own thread. # scoped_session as a global variable Engine = create_engine(host, pool_recycle=600, pool_size=10, connect_args=options) Session = scoped_session(sessionmaker(autoflush=True, bind=Engine)) RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver') # Session.remove() fails in dev # Created in my API, once per request (per thread) class RequestContainer(object): def __init__(self, request, *args, **kwargs): self.s = Session() def safe_commit(self): try: self.s.commit() except: self.s.rollback() raise def __del__(self): if self.s: try: self.s.commit() except: self.s.rollback() raise if not RUNNING_DEVSERVER: Session.remove() self.s = None And the prepared state error pops up in the code, usually in the same place, but not all the time, and sometimes in other places: ... rs = request_container.s.query(MyTable) ... … -
Django post_save signal, created argument
I'm having trouble accessing the created argument, from my post_save signal receiver. @receiver(post_save, sender=Facility) def add_times(sender, **kwargs): instance = kwargs.get('instance', None) created = kwargs.get('created', False) if isinstance(instance, Facility) and created: instance.add_opening_times() When I call save() on a Facility instance, I receive the following error: Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\bin\Python35\lib\site-packages\django\db\models\base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "C:\bin\Python35\lib\site-packages\django\db\models\base.py", line 745, in save_base update_fields=update_fields, raw=raw, using=using) File "C:\bin\Python35\lib\site-packages\django\dispatch\dispatcher.py", line 192, in send response = receiver(signal=self, sender=sender, **named) File "C:\git\SimplySport\facility\models.py", line 53, in update_stock instance = kwargs.get('instance', None) NameError: name 'created' is not defined https://docs.djangoproject.com/en/1.9/ref/signals/#post-save -
Running code on Django application start
I need to run some code every time my application starts. I need to be able to manipulate models, just like I would in actual view code. Specifically, I am trying to hack built-in User model to support longer usernames, so my code is like this def username_length_hack(sender, *args, **kwargs): model = sender._meta.model model._meta.get_field("username").max_length = 254 But I cannot seem to find the right place to do it. I tried adding a class_prepared signal handler in either models.py or app.py of the app that uses User model (expecting that User will by loaded by the time this apps models are loaded). The post_migrate and pre_migrate only run on migrate command. Adding code into settings.py seems weird and besides nothing is loaded at that point anyway. So far, the only thing that worked was connecting it to a pre_init signal and having it run every time a User instance is spawned. But that seems like a resource drain. I am using Django 1.8. How can I run this on every app load? -
User login, authentication, and sign up in Django 1.10
I am having trouble distinguishing between logins and signups in Django. I was able to successfully create a signup form (that also logs the user in upon sign up.) I am struggling to make a separate sign in form. The following code successfully renders a form with 'username' and 'password' fields. Upon clicking "submit" the info gets stored as the user object, then gets normalized, then gets saves to the database, and then is used to log in the user. I tried to delete the user.save() line because I thought that would make the difference between adding a user and logging in a user. However, my terminal shows an unsuccessful post request ("POST /polls/ HTTP/1.1" 200 1227) when this happens. Please let me know what I can do to simply let the user sign in if his account info already exists in the database. Thanks! class LoginFormView(View): form_class = LoginForm template_name = 'polls/login_form.html' #display blank form using get def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #process the form data using post def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned and normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #return user … -
Django - Static files not fetching in Heroku
I made a webpage using Django, and hosted it in Heroku Cloud. This is my second app I successfully hosted one application earlier. But for this application the static files are creating some issues. It not fetching the static files in the production environment. I tried several things but still not working. The following is few codes of my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['promagcareer.herokuapp.com'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' I have given {% load static %} in the template html. I have tried many things, but still its not loading the static files. What might be the problem. This is the link of the site. The link of github project. Kindly help. Thanks in advance. -
oTree: How to access the player's id from the player class in model.py?
I would like to define a parameter variable via the default attribute id_in_group of the player. However, this attribute does not seem to be accessible via the ways I could think of (such as via BasePlayer.id_in_group). The code of the class player: class Player(BasePlayer): investment_amount = models.CurrencyField( doc=""" Amount invested by this player. """, min=0, max=Constants.endowment ) random_number = BasePlayer.id_in_group def set_payoffs(self): for p in self.get_players(): p.payoff = 110 How could I access the attribute id_in_group? Or is it impossible due to the fact that it is a default attribute preset by oTree? -
How can I handle Django login and signup/registration on the same page?
I want to handle login/registration on the same page. I have one template 'home' with 2 django forms. I want to submit redirect to the same page, show errors if there are any. How can I do this without default separate urls for login/registration ? Many thanks for advices. -
Django - add a function to an admin form under a particular field
Ive made a function that i want to be able to run on the fly in my admin form, also that it would be resuable for multiple fields. Basically, we have a dmvpn ip and a subnet. i would like to be able to click, find free ip/subnet then run my function against the current values other records have for the field so findfreeip would sit next to both fields and find me the next available dmvpn IP in the 4th octect and it would find me the next available subnet in the 3rd octect. then maybe a pop showing the free ips/subnet and on click it would populate the field for me Heres the model and the function models.py class ShowroomConfigData(models.Model): location = models.CharField(max_length=50) dmvpn_dsl_ip = models.GenericIPAddressField(protocol='IPv4') subnet = models.GenericIPAddressField(protocol='IPv4') ... functions.py def FindFreeIP(list_of_ips, octect): #get the required octect from all IPs and put them in a list octect_list = [] for item in list_of_ips: octect_list.append(getXOctect(item,octect)) octect_list = sorted(octect_list) #go through the list and find the smallest free no usable = [] for i in range(1,254): if i not in octect_list: usable.append(i) return min(usable) I get all the subnets in a list and then send that list to the … -
django-haystack order_by not working
I have a query like SearchQueryset().all().models(Show).order_by('title') This will return list of objects. But in the title names there might be the special characters like ./hack:twilight and also numbers like 009:absolute. According to order_by documentation, the priority goes to special characters. But when I see the output, it starts from the numbers. Basically I need this output using that query >> list = ['apple', 'zebra', '.hack', 'orange', 'car', 'funk', 'python'] >>> list.sort() >>> list ['.hack', 'apple', 'car', 'funk', 'orange', 'python', 'zebra'] Any idea? -
Can't find the way to have diffent content from differents view function in a inheritance template in django
I'm new working with Django and there's something I need to do that looks simple but can't do it yet. Here is the issue, I have the idea to create a big project with a lot of templates and want to have same bar with username include in all templates. So I create a base.html template with some content like the username and some others. Also I have a child.html with another content like a cities list who extends my base.html. My problem is that when I run my child.html template the views function content in my base.html like the username doesn't show. Here is what I am doing: My View for the username : def userview(request): a = User.objects.get(pk=1) return render(request,'base.html',{'a': a}) My base.html template: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <title>{% block title %}My amazing site{% endblock %}</title> </head> <body> {{a.username}} <div id="sidebar"> {% block sidebar %} <ul> <li><a href="">Home</a></li> <li><a href="">Blog</a></li> </ul> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> </body> </html> My view for cities list: def regionesli(request): regioneslista = Regiones.objects.all() return render(request,'child.html',{"resultados": regioneslista}) My Child.html template: {% extends "base.html" %} {% block title %}My amazing blog{% endblock … -
Tinymce Django textarea doesn't input tags
I need some help implementing the TinyMCE textarea, to make it function in on my page. Example: This is how it looks html code: <textarea class="replytextarea" id="textarea-edit" placeholder="..." name="text"></textarea> JS code: <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script>tinymce.init({ selector: '#textarea-edit', height: 300, theme: 'modern', plugins: [ 'advlist autolink lists link image charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen', 'insertdatetime media nonbreaking save table contextmenu directionality', 'emoticons template paste textcolor colorpicker textpattern imagetools' ], toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', toolbar2: 'print preview media | forecolor backcolor emoticons', image_advtab: true, templates: [ { title: 'Test template 1', content: 'Test 1' }, { title: 'Test template 2', content: 'Test 2' } ], content_css: [ '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i', '//www.tinymce.com/css/codepen.min.css' ] }); </script> -
Virtualenv gives different versions for different os
I am working on a django project on two separate systems, Debian Jessie and Mac El Capitan. The project is hosted on github where both systems will pull from or push to. However, I noticed that on my Debian, when I run python --version, it gives me Python 3.4.2 but on my Mac, it gives me Python 2.7.10 despite being in the same virtual environment. Moreover, when I run django-admin --version on my Debian, it gives me 1.10 while on my Mac, 1.8.3. This happens even when I freshly clone the projects from github and run the commands. Why is it that the virtual environment does not keep the same version of python and django? -
Django Advanced tutorial: How to write reusable apps
According to Django Advanced tutorial: How to write reusable apps, "2. With luck, your Django project should now work correctly again. Run the server again to confirm this." How to run the server? Having moved polls app from "mysite" to "django-polls" without manage.py and settings? Please help with further instruction. -
Django TastyPie nested resource creation
I am exposing in a tastypie Api a high level resource ( called Parent in the example below). Based on the type of the parent I need to create one or more Child objects. #the models class Parent(models.Model): some_general_description = models.TextField() type = models.IntegerField() class Child(models.Model): parent = models.ForeignKey(Parent, related_name='details') detail_description = models.TextField() #the resource class ParentResource(ModelResource): def hydrate(selfself, bundle): # !! can't create Children (based on type) # since I do NOT yet have a valid Parent object # and I can't save a Child object without a valid Parent pass class Meta: queryset = Paren.objects.all() I do not want to expose the Child objects in the Api since they are an implementation detail that does not concern the consumer of the Api. My initial approach was to try to create the necessary child resources in the hydrate method. Looking at the implementation of tastypie BaseModelResource.obj_create I noticed that hydrate is called before object.save which makes it imposible to save the Child resources inside hydrate. class BaseModelResource(Resource): def obj_create(self, bundle, **kwargs): # ... bundle = self.full_hydrate(bundle) return self.save(bundle) What is the proper (recommended ?) way of creating (non exposed) nested resources? Thank you for your help. -
How to pass a queryset from django to javascript function?
I want to pass a queryset from a view to a javascript function throught the template: my view.py: def myview(request): lista=Mymodel.objects.filter(tipo=mytipo) context_dict['lista']=lista return render(request, 'mytemplate.html', context_dict) my template.html: <script> <!-- window.onpageshow = function() { myfunction('{{lista}}'); }; --> </script> my javascript.js: function myfunction(lista) { for (i=0; i<lista.length; i++) { console.log(lista[i].name) } } The problem is that lista become a string. I tried with JSONEncoder but i'm not sure how to use. I would like to avoid JsonResponse because I wwant to use that view for my template (if possible). -
Invalid SMTPAPI Header: send_at must be a timestamp
I am scheduling the emails through SMTP API. This is what I have tried uptil now: from smtpapi import SMTPAPIHeader from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Template, Context def campaign_email(lg_user, template): user = lg_user.id email = user.email fname = lg_user.id.first_name lname = lg_user.id.last_name mobile = lg_user.contact_no purchase = lg_user.active_user_subjects.values_list('subject', flat=True) expiry = str(lg_user.active_user_subjects.values_list('at_expiry', flat=True)) filename = '/tmp/campaign_mailer.html' opened_file = open(filename, "r").read() temp = Template(opened_file) c = Context({'fname': fname, 'lname': lname, 'subject': subject, 'email': email, 'mobile': mobile, 'purchase': purchase, 'expiry': expiry}) header = SMTPAPIHeader() html_content = temp.render(c) send_at = {"send_at": 1472058300} header.set_send_at(send_at) msg = EmailMultiAlternatives(subject, html_content, sender, [email], headers={'X-SMTPAPI': header.json_string()}) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=True) In order to check, if my header (which on printing header.json_string() resolves to this: { "send_at": { "send_at": 1472051700 } } ) was valid or not, I checked on https://sendgrid.com/docs/Utilities/smtpapi_validator.html and it came out to be completely valid. But the failure mail that I got from sendgrid's support stated the reason of failure to be: send_at must be a timestamp. I believe, that in the documentation, it's clearly stated that the timestamp should be in UNIX format - which is what I have supplied as the value to my … -
How can I convert following derived table query to django ORM?
SELECT count(user_min.user_id_id), date(user_min.date_time) from ((SELECT MIN(date(date_time)) as date_time,user_id_id FROM `pied_visit` WHERE branch_id_id IN (5,6,9) GROUP BY user_id_id) user_min) GROUP BY date(user_min.date_time) Searched at lots of places. But couldn't find anything useful. -
no pycharm database window
I'm following a tutorial on Django. I'm using PyCharm 2016.2.1. There is a file in my project called db.sqlite3. The icon next to this file in the project explorer shows a question mark which indicates PyCharm does not know what this file is. In searching the web I find many references to clicking View > Tool Windows > Database. In my setup there is no Database option under View > Tool Windows. Sqlite3 is supposed to be native to Python/PyCharm yet I don't seem to even have a Database option. What am I doing wrong? -
Django 1.8.7 get_readonly_fields seems like have a bug
I try something with readonly field in Django 1.8.7, let say I have some code like the following: class MyAdmin(admin.ModelAdmin): readonly_fields = ('a', 'b') def get_readonly_fields(self, request, obj=None): if not request.user.is_superuser: self.readonly_fields += ('c') return super(MyAdmin, self).get_readonly_fields(request, obj) first I login with super admin and access that admin page change_form, the code is works well, then I login with staff user, then still works well, again, I try login with superadmin, but the read only fields rendered is for the non-superadmin user, again I clear the browser cache, try again with super admin, but still not work correctly. I try restart the server, then it work normally until I repeat the same step above I do, this weird thing come again. Anyone know why this happen ? I think this is looks like some bug but not sure. Thanks in Advance. -
Django-taggit tags with backspace in name?
How can I use tags with backspace in their name with django-taggit? For example, "Some simple tag"? Because if I ctrl-c=>ctrl-v some phrase to tags fieldin my admin panel, on page with this tag i get something like this: Reverse for 'posts_by_tag' with arguments '()' and keyword arguments '{u'tag': u'\u0411\u0430\u043d\u043a \u0422\u0430\u0432\u0440\u0438\u043a\u0430'}' not found. 1 pattern(s) tried: ['blog-list/posts/(?P<tag>\\w+)$'] , but if I try add tag with backspace-it just cut on backspace char and starts new tag. How can I fix it? -
Pass data from django middleware.process_view to the template context
I have a custom middleware and during its process_view I get some token. And I need to pass this token to the rendered result html. I thought that context_processor is a good place to modify context, but looks like it's hard to pass some data from middleware into processor. But it seems that the only way to communicate for process_view and context processor is request object. And if set any field to the request I get 'WSGIRequest' object does not support item assignment' error. So, looks like I'm doing something wrong. Is there a way to communicate middleware.process_view and context_processor? Or I should change another way to pass data into html from middleware? -
Constrain fk relationship so it can only have one of a type
I have Booking and Payment models. Each Booking can have more than one Payment. There are more types and fields but this should be enough to illustrate what I'm trying to do. class Booking(models.Model): cost = models.IntegerField(...) class Payment(models.Model): TYPE_THIRD_PARTY 'thirdparty' TYPE_STRIPE = 'stripe' TYPES = [ (TYPE_THIRD_PARTY, 'Third party payment'), (TYPE_STRIPE, 'Stripe online payment') ] payment_type = models.CharField(..., choices=Payment.TYPES) amount = # ... Our system accepts third party Bookings and automatically creates TYPE_THIRD_PARTY Payments for accounting. If the amount on a third party Booking changes, we just bump the amount in the existing payment. We have had some issues with admins creating additional TYPE_THIRD_PARTY payments. This breaks things when the automated updates come through. I know I can dummy the forms to remove the third party payment choice, but is there a sensible way I can constrain Payment at database level so that there can only be one with payment_type=TYPE_THIRD_PARTY per Booking? Other Payment types are okay not being unique. -
Django. Specific url based on choices field
How can I get specific url based on choice field? For example I have the following model: class MyModel(models.Model): FIRST = 1 SECOND = 2 CHOICES = ( (FIRST, 'first'), (SECOND, 'second'), ) choice = models.IntegerField(choices=CHOICES, default=first) In views I want to get count for all objects based on their choice field, so I do follow: def my_view(request): choices = [] for c, dname in MyModel.CHOICES: count_for_this_choice = MyModel.objects.filter(choice=c).count() choices.append((dname, count_for_this_choice)) return render(request, 'template.html', {'choices': choices}) So, I need specific url, that give me availability to access all objects with certain choice. Now my template.html looks like this, but from my point of view it's ugly: .... {% for dname, count in choices %} <tr> <td><a href='/page/{{ dname }}/'>{{ dname }}</a></td> <td>{{ count }}</td> </tr> {% endfor %} .... Any ideas? I think about another model for choices and define get_absolute_url method for it.. But I new to django and don't know best practices for this situation.