Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError 'tuple' object is not callable
I got an error, TypeError at /ResultJSON/v1/results/ 'tuple' object is not callable . I wrote a method in views.py, results = OrderedDict([ ('id',x.id) ('name', x.name) for x in Post.objects.all() ]) When I browsed this error,I read the error happen because there is no comma (,). But I added commas between ('id',x.id) and ('name', x.name) and last of ('name', x.name),I got an error No Python interpreter configured for the project. So,I cannot understand why this error happen.How can I fix it? In views.py,I wrote import json from collections import OrderedDict from django.http import HttpResponse from accounts.models import Post def render_json_response(request, data, status=None): json_str = json.dumps(data, ensure_ascii=False, indent=2) callback = request.GET.get('callback') if not callback: callback = request.POST.get('callback') if callback: json_str = "%s(%s)" % (callback, json_str) response = HttpResponse(json_str, content_type='application/javascript; charset=UTF-8', status=status) else: response = HttpResponse(json_str, content_type='application/json; charset=UTF-8', status=status) return response def UserResult(request): results = OrderedDict([ ('id',x.id) ('name', x.name) for x in Post.objects.all() ]) data = OrderedDict([ ('results', results) ]) return render_json_response(request, data) -
Make All hashtags clickable in Template with Templatetags
I want to turn every hashtag in the comment textfield to url so that it will be clickable. For example, a user submit, s = "I can't get enough of #SO because #developers are very #supportive" I want it to return like this in template, I can't get enough of #SO because #developers are very #supportive Where whole text will display and all hashtag will be clickable by embedding {hashtag}. I tried the below templatetags code but it won't return the hashtags with the text. It will only return this, <a href='http://example.com/tags/SO'>SO</a> app_extras.py import re register = template.Library() @register.filter(name='hashchange') def hashchange(value): vx=re.findall(r"#(\w+)", value) for n in vx: pm="<a href='http://example.com/tags/{0}'>{0}</a>".format(n) return pm In the template, I did, {{object.comment|safe|hashchange}} What am I missing? -
Django template not working properly
In django 1.10 I tried these two different code snippets. The difference was in <script></script> tag in <head>. <!DOCTYPE HTML> <head> <title> Live Exchange Rate </title> {% load static %} <script src="{% static 'insights/js/main.js' %}" ></script> </head> <body> <div> Loading Charts </div> <button> This is button text </button> </body> and <!DOCTYPE HTML> <head> <title> Live Exchange Rate </title> {% load static %} <script src="{% static 'insights/js/main.js' %}" /> </head> <body> <div> Loading Charts </div> <button> This is button text </button> </body> It renders correctly in first case but not in second. Here are the screeshots. Why is that? -
Setting the form value when the form is initiated
I am trying to set a field value when a form is initiated. The value of this field is retrieved when we enter the view - the view being the timesheet. Then for each Time set in the view, I want to relate it back to the timesheet. @login_required @requires_csrf_token def timesheet(request, timesheet_id): timesheet = TimeSheet.objects.get(pk=timesheet_id) NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet) if request.method == 'POST': newtime_formset = NewTimeFormSet(request.POST, request.FILES) for form in newtime_formset: if form.is_valid(): form.save() #then render template etc So, to make sure the form validates I want to set this field when the form is initiated. When I try to set this field after POST in the view, I haven't been able to get the field to set or form to validate. My code gets the timesheet_id when the model instance is initiated on entering the view def __init__(self, *args, **kwargs): # this allows it to get the timesheet_id print "initiating a timesheet" super(TimeSheet, self).__init__(*args, **kwargs) And then the form is generated and I run the form init. So this is what I've tried class TimeForm(forms.ModelForm): class Meta: model = Time fields = ['project_id', 'date_worked', 'hours', 'description', 'timesheet_id',] # some labels and widgets, the timesheet_id has a hidden β¦ -
How to add periodic functions in django application?
I like to add a function which will run once in a month in my django application. In django every views function is a request method. I want the function without request method. Can somebody suggest an existing solution? I want this for sending monthly mails to the users. Thanks, -
How to django-auth-ldap achieve authentication with cn (common name) in AD?
I'm using Active directory with windows server 2008 R2. I have an application running with Django and python 2.7. Now I need to use active directory authentication to access into my application. To do that, i'm using this packages: sudo apt-get-update sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev sudo pip install django-auth-ldap sudo pip install python-ldap I used the full name to have a successful bind. import ldap from django.conf import settings username='my full name in AD' password= 'my password' l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI) l.simple_bind_s(username,password) My problem is when i'm trying to use my cn attribute for bind, i got this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 207, in simple_bind_s return self.result(msgid,all=1,timeout=self.timeout) File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 422, in result res_type,res_data,res_msgid = self.result2(msgid,all,timeout) File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 426, in result2 res_type, res_data, res_msgid, srv_ctrls = self.result3(msgid,all,timeout) File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 432, in result3 ldap_result = self._ldap_call(self._l.result3,msgid,all,timeout) File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 96, in _ldap_call result = func(*args,**kwargs) INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1', 'desc': 'Invalid credentials'} Can I use my cn (common name)attribute for authentication to my Active directory? Thanks. -
Slow django model instance creation with Docker
I have django application with some model. I have manage.py command that creates n models and saves it to db. It runs with decent speed on my host machine. But if I run it in docker it runs very slow, 1 instance created and saved in 40-50 seconds. I think I am missing something on how Docker works, can somebody point out why performance is low and what can i do with it? docker-compose.yml: version: '2' services: db: restart: always image: "postgres:9.6" ports: - "5432:5432" volumes: - /usr/local/var/postgres:/var/lib/postgresql environment: - POSTGRES_PASSWORD=postgres - POSTGRES_DB=my_db - POSTGRES_USER=postgres web: build: . command: bash -c "./wait-for-it.sh db:5432 --timeout=15; python manage.py migrate; python manage.py runserver 0.0.0.0:8000; python manage.py mock 5" ports: - "8000:8000" expose: - "8000" depends_on: - db dockerfile for web service: FROM python:3.6 ENV PYTHONBUFFERED 1 ADD . . WORKDIR . RUN pip install -r requirements.txt RUN chmod +x wait-for-it.sh -
Pythonanywhere ImportError: No module named 'backend'
I am trying to deploy a Django code to pythonanywhere and when I try to go to site, I see 'someting went wrong'. Here is my error log file: File "/var/www/jinxed_pythonanywhere_com_wsgi.py", line 15, in <module> application = get_wsgi_application() I know these type of questions already asked but I checked my wsgi.py file in pythonanywhere and I think the path is true, or I just cant see it. Here is my project layout. project βββ .git/ βββ .idea/ βββ .gitignore βββ backend β βββ manage.py β βββ backend β β βββ __init__.py β β βββ __pycache__/ β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β β β βββ indexapp β β βββ __init__.py β β βββ __pycache__/ β β βββ admin.py β β βββ urls.py β β βββ models.py β β βββ views.py β β βββ tests.py β β βββ forms.py β β βββ apps.py β β βββ requests.py And here is my wsgi.py file in /var/www/jinxed_pythonanywhere_com_wsgi.py import os import sys # path = u'/home/jinxed/project/backend' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'backend.settings' # ## then, for django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I dont understand what is wrong. My settings.py file's β¦ -
About Django's widget design principles
This is a question I've from time ago, as I just don't understand why was this decission headed that way. When we render a widget (manually, 'cause of using a form, etc.), its render functions has a name arg. Why, if a HTML tag name is an attr, cannot be specified as part of the attrs dict passed to that function? Should make more sense to use name only when you no specify an attr name. For understanding, if I set an attrs {"name": "no_one_knows[]"}, when I render the widget its name should be "no_one_knows[]", not the one passed by arg. That way I could have a HTML tag that can be parsed directly as a list (getlist(..)) in the server side (for example). -
chart.js django - options doesnt work for chart
I just made my first chart using chart.js in django. But I cant edit it with any options. The code in template looks like: $.get('{% url "line_chart_json" %}', function(data) { var options = {showTooltips: true, tooltipTemplate: "<%= value %>"}; var ctx = $("#myChart").get(0).getContext("2d"); new Chart(ctx).Bar(data, options); }); For example when I change "new Chart(ctx).Bar(data, options);" to "new Chart(ctx).Line(data, options);" it works, but other options doesnt work. Thanks for help! -
Overloading error message stemming from wrong GET-request
I have a view that looks like this: class Foo(APIView): def get(self, request, format = None): #... So my question is very simple: how do I override the error message that is returned in case of POST-request? -
Django admin how unlock your own account?
In Django admin I have by mistake locked myself by attempting the wrong password. I later of deleted the user and created another one using manage.py createsuperuser. However, it still says that I'm locked. How do I unlock myself? It gives the following error when I try to log in using Django admin.. Account locked: too many login attempts. Contact an admin to unlock your account. -
Urllib in docker: Network is unreachable
I am trying to access the Entrez database from NCBI through Biopython from my django 1.10 application running in a docker with Python 3.5. My django application is running behin my company proxy. Basically, I am running the following code: from Bio import Entrez Entrez.email = "A.N.Other@example.com" # Always tell NCBI who you are handle = Entrez.einfo() But I get the following error: urllib.error.URLError: <urlopen error [Errno 101] Network is unreachable> with and without setting the proxy in os.environ. Running the exact same code works fine on the following configs: the server hosting the docker container, with python 3.4 and proxy set up dev machine, with python 3.5 and proxy set up Using requests in docker works though. -
Overloading obtain_jwt_token in Django REST framework to return customized error messages
My goal is to overload the obtain_auth_token as described in the doc so that the procedure returns a customized error messages (f.e., in case of wrong password or username) instead of { "non_field_errors":[ "Unable to login with provided credentials." ] } I have come across this post, but unfortunately my expertise in Django did not suffice to figure out what needs to be done. Could you bear with me guys, and provide a short code snippet that would enable to return a wrong password error message which would look like: {'success': False, 'detail': _('Wrong password or username'), 'error_code': None, 'object': None} -
ajax inside ajax not working in django
Modal popup form open on my page for registration of user. After successful registration of user one prompt-box is open for OTP input so here all OTP validation is happened in my django views i just have to send OTP response to my view using ajax i have tried but it is not working. I have used two ajax function one for my user registration form and other for accepting OTP. here is my code Django view for OTP validation def activate_user_via_otp(request, otp_code): if otp_code: user = request.user otp = models.OTPTransactions.objects.filter(user=user) if otp: if otp[0].otp == otp_code: user.is_active = True user.save() otp[0].delete() #Activate User Profile activate_profile = RegistrationProfile.objects.filter(user=user.id)[0] key = activate_profile.activation_key RegistrationProfile.objects.activate_user(key) obj = '1' return HttpResponse(json.dumps({'success': obj})) else: obj = '0' return HttpResponse(json.dumps({'error': obj})) (Registration form serve through bellow code) <form novalidate method="post" id="register-form"> #{ render_form(form) } :: if service_data: <input type="hidden" value="${ service_data }" name="service_data" /> :: #endif <button class="btn btn-primary" type="submit" style="margin-left: 55px;">Register</button> </form> Ajax function $('#register-form').submit(function(e){ e.preventDefault(); var csrftoken = getCookie('csrftoken'); var name = $('#id_name').val(); var email = $('#id_email').val(); var phone = $('#id_phone').val(); var password1 = $('#id_password1').val(); var password2 = $('#id_password2').val(); $.ajax({ url : "/roles/consumer/registration/form/", type : "POST", data : { csrfmiddlewaretoken : csrftoken, name : β¦ -
Django 1.10 - subdomain is not workig with django_hosts
I am following this tutorial on youtube here about implement subdomain with django_host, I think I did everything right but still not working when I type the Url: blog.tirr.com:8000 and an error is raised: "Invalid HTTP_HOST header: 'blog.tirr.com:8000'. You may need to add 'blog.tirr.com' to ALLOWED_HOSTS." settings.py ALLOWED_HOSTS = ['tirr.com', 'www.tirr.com'] (in the youtube video shows adding only these 2) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'shortener', ] ROOT_URLCONF = 'kirr.urls' ROOT_HOSTCONF = 'kirr.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL = "http://www.tirr.com:8000" hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'(?!www).*', 'kirr.hostsconf.urls', name='wildcard'), ) hostsconf/ urls.py from django.conf.urls import url from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect), ] views.py from django.conf import settings from django.http import HttpResponseRedirect DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.tirr.com:8000") def wildcard_redirect(request, path=None): new_url = DEFAULT_REDIRECT_URL if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) -
Meta ordering orders in wrong order
i have very basic model like this; class City(models.Model): geographic_area = models.ForeignKey('setting.GeographicArea',default="1",blank=True,null=True,verbose_name=u"CoΔrafi BΓΆlge") name = models.CharField(blank=True,null=True,max_length=200,verbose_name=u"Ad") plaka = models.IntegerField(blank=True,null=True,verbose_name=u"Plaka") class Meta: verbose_name_plural = u'Εehirler' verbose_name = u'Εehir' ordering = ['name'] def __unicode__(self): return self.name In another class i called city model like this; class Activity(models.Model): ... city = models.ForeignKey('setting.City',verbose_name=_('City')) ... Problem is when im using ModelForms for Activity class city model needs to be ordered. Its actually seems ordered by doing ordering = ['name'] but since my city names include Δ°,Γ,Γ and Ε, cities which are starting with these characters are on the end of the list but actually they should be ordered in following order A B C Γ D E F G Δ H I Δ° J K L M N O Γ P R S Ε T U Γ V Y Z; Im already using unicode and utf-8 coding in all of the project(forms, models and views). Thank you everyone. -
How to declate intialize and increment variable in django Template. not talking about forloop.counter
This is what i want . my case is not of forloop.counter because i need to increment it conditionally <div class="row text-left"> /////some counter=0 {% for article in article_list %} /////{% if counter == 4 %} </div> <div class="row text-left"> {% endif %} {% if article.published %}enter code here /////// counter++ {% include "aldryn_newsblog/includes/general-article.html" %} {% endif %} {% empty %} <p>{% trans "No items available" %}</p> {% endfor %} </div> -
How to handle object reference in CreateView
I have an item. An item can have many reviews. I expect a review to be created within the context of an item. Therefore, I capture the pk from the url and add it to the context. This is where I get stuck, I'm unsure how to access the context in form_valid and, more importantly, I'm concerned the path I'm trying to go down seems hacky. Essentially when the user prepares to submit a review, the application will know what item it's in reference to. What's the most pythonic/django-onic way to do this? Models class Item(models.Model): name = models.CharField(max_length=100) source = models.ForeignKey('Source') class Review(models.Model): rating = models.CharField(max_length=30) value = models.CharField(max_length=30) date = models.DateField(auto_now_add=True) comment = models.CharField(blank=True,max_length=100) item = models.ForeignKey(Item,blank=True) user = models.ForeignKey(User) Urls url(r'^review/create/item/(?P<itempk>\d+)',views.ReviewCreate.as_view(),name='review_create'), Views class ReviewCreate(CreateView): model = Review fields = ['rating', 'value', 'comment'] def get_context_data(self, **kwargs): context = super(ReviewCreate, self).get_context_data(**kwargs) itempk = self.kwargs['itempk'] item = get_object_or_404(Item, pk=itempk) context['item'] = item return context def form_valid(self, form): review = form.save(commit=False) review.user = self.request.user context = super(ReviewCreate, self).get_context_data(**kwargs) '''doesn't work''' review.item = context['item'] return super(ReviewCreate, self).form_valid(form) template_name = 'food/review_form.html' -
Copy/move linked file when changing model instance owner in Django admin
I have a very simple Image model class Image(Model): owner = ForeignKey(User) img = ImageField(upload_to=image_file_path) the image_file_path resolves to <username>/images/ where username is the Image model instance's owner.username Now, when using Django admin to change the owner of the image, I want the physical image file to be moved to the appropriate path, i.e. <new_username>/images/. What is the simplest / "correct" way of doing this? -
Form isn't validating even though all fields are populated
I have a form that I can't get to validate even though all of the fields are populated. I have printed each field to check that the content is correct and it seems that the field content is also fine. I am using a formset because I allow the user to add multiple rows and then submit (I have some javascript for this). But to keep it simple, I am just trying to submit one record to the database and it won't validate. Here is my form and my clean method where I check all the fields: class TimeForm(forms.ModelForm): class Meta: model = Time fields = ['project_id', 'date_worked', 'hours', 'description', 'timesheet_id',] labels = { 'project_id': _('Project'), 'date_worked': _('Date'), 'hours': _('Hours'), 'description': _('Description'), } widgets = { 'description': forms.TextInput( attrs={'id': 'post-description', 'required': False, 'placeholder': 'Description'} ), 'project_id': forms.Select( attrs={'id': 'post-project', 'required': False} ), 'date_worked': forms.TextInput( attrs={'id': 'post-date', 'required': False} ), 'hours': forms.TextInput( attrs={'id': 'post-hours', 'required': False} ), # this is for the formset save to save new records separately to hidden records 'add_row': forms.HiddenInput( ), 'timesheet_id': forms.HiddenInput( attrs={'required': False} ), } def clean(self): cleaned_data = super(TimeForm, self).clean() description = cleaned_data.get("description") project_id = cleaned_data.get("project_id") hours = cleaned_data.get("hours") date_worked = cleaned_data.get("date_worked") timesheet_id = β¦ -
Django error reporting with Gmail
I'm trying to set up my Django account to receive the Error reporting (docs here). I have added ADMINS to my settings.py. Then, as per the documentation: In order to send email, Django requires a few settings telling it how to connect to your mail server. At the very least, youβll need to specify EMAIL_HOST and possibly EMAIL_HOST_USER and EMAIL_HOST_PASSWORD, though other settings may be also required depending on your mail serverβs configuration. Consult the Django settings documentation for a full list of email-related settings. But here is when I get lost. I have a Business Gmail account, which is the one I would like to link here. This post was explaining it wonderfully, EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@mydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' but it says: In 2016 Gmail is not allowing this anymore. Apparently, the problem is in the EMAIL_HOST_PASSWORD setting, which has to be an specific password, as noted in this other post. However, it is hard to believe that Gmail does not allow that in any way, especially with a Business account where you are paying money for the service. Unfortunately, all related info I found is older than 2016 and β¦ -
Django Annotate price by month
I'm trying to summarize price for each month and display it in a template, so I'm annotating this inside my view using generic ListView and trying to display it in my template, the problem is that I have {'total_price_aux': None} displayed inside my tr, so can someone see if I'm doing the right thin or not, how can I make this work. models.py: price_aux = models.DecimalField('price aux', max_digits=20, decimal_places=2, default=0, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) in views I'm trying to annotate price_aux like this context["price_aux"] =\ Project.objects.filter(created__year="2015").values_list("created").aggregate(total_price_aux=Sum("price_aux")) and in the template I have: <th class="align-left">{{ price_aux.price_aux__count}}</th> -
How to Upload Files With Django
i am getting such type of error when extracting the file data object in Django technology. data = stream.read().decode(encoding) AttributeError: 'NoneType' object has no attribute 'read' Could you explain? -
Password reset with django.config.auth reset view does not work with custom MongoEngine BaseUser model
I try to use the django.config.auth module to add a reset password view on my website. The thing is I am using a custom User model which inherits from mongoengine_django_auth.auth.BaseUser model. The GET works fine (I get the password reset form in my browser) but when I POST to be e-mailed a password reset link I get a 500 error. It seems that Django can't get the user based on e-mail with my User model. More precisely, the User.get_meta() returns a MetaDict whereas Django implementation expects an Options type. Do you know if I can use mongengine User model with this module or should I rewrite the view myself?