Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could you pls explain me this django/html expression?
I am learning django using a book. But now I faced an expression that is does not explain. Could you explain how it works? <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button"> I read that data-id and data-action are html5 features which allow us to send data to JS. But what is this "un" between the if's: %}un{% I appreciate further explanations about the whole thing. -
Django in production
I have some doubts about django, let's suppose I have a web site with 50 html web pages, and I would like to use django just for one single web page. how the urls file would look ? I asked that because I'm trying to use django, but suddenly I just remember that I have more web pages actually working fine. I will create more pages with django but, what happen with those already created?. I'm very curious to know how the urls file would it look. ¡Thank you! -
What do I need to have a website running on the web?
After a couple hours of searching top lists of free "web servers" and "web frameworks" on google, I realized I'm not sure what I'm looking at. Let's take a couple of example softwares I have come across : IIS Apache HTTP server Apache Tomcat Socket.io Node.js Django Questions : Do all these work on the same scope/do the same thing? If not, what is absolutely necessary to have my "helloworld.html" acessible from anywhere with internet? Let's consider I already have a server and a domain Also if not, how do these work together/compliment eachother? Each of this software has a different description on their website for what it does, what it is, who should use it, it really gets confusing when you're trying to find what is "fresh", what the cool kids are using -
jQuery ui datepicker not shown in inline django formset
In the normal form jquery datepicker worked fine. When I add child form dynamically to parent form, the datepicker not shown as well as not work in the date field of child form. Here is my child model: class Children(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) child_name = models.CharField(max_length=150, blank=False) slug = AutoSlugField(populate_from='name') child_birth_date = models.DateField(null=True, blank=True) blood_group = models.CharField(max_length=5, blank=True) Here is my fomrset: class ChildrenForm(ModelForm): child_birth_date = forms.DateField(('%d/%m/%Y',), label='Birth Date', required=True, widget=forms.DateInput(format='%d/%m/%Y', attrs={ 'class': 'input', 'size': '15' }) ) class Meta: model = Children fields = '__all__' def __init__(self, *args, **kwargs): super(ChildrenForm, self).__init__(*args, **kwargs) self.fields['child_birth_date'].widget.attrs['placeholder'] = 'format:mm/dd/yyyy' PersonFormSet = inlineformset_factory(Person, Children, extra=0, min_num=1, fields=('child_name', 'child_birth_date','blood_group' )) Here is my script: <script type="text/html" id="children-template"> <div id="children-__prefix__"> {{ formset.empty_form }} </div> </script> $(function() { $('.add-children').click(function(ev){ ev.preventDefault(); var count = parseInt($('#id_children_set-TOTAL_FORMS').attr('value'), 10); var tmplMarkup = $('#children-template').html(); var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count) console.log(compiledTmpl); $('div.children').append(compiledTmpl); $('#id_children_set-TOTAL_FORMS').attr('value', count + 1); $('#id_child_birth_date').datepicker(); $('#id_child_birth_date').datepicker('show'); }); }); my form.html: <form action="." method="post" enctype="multipart/form-data"> {{ formset.management_form }} {% csrf_token %} <legend>Person</legend> <div class="event"> {{ form|crispy}} </div> <legend> <div class="pull-right"><a class="btn btn-inverse add-children" href="#" ><i class="icon-plus icon-white"></i> Add Children</a></div> Children Information </legend> <div class="children form-inline"> {% for form in formset %} {{ form|crispy }} {% endfor %} </div> <div class="form-actions"> <button … -
How to avoid hardcoded urls in IOS/Android app
I'm developing a django web-project and I'm going to develop its IOS and Android API. Is there a way to avoid using hardcoded url addresses in the app code?Something like django url name system The following problem faces me if there isn't any solution to my question: If I want to change some of my urls, I should change the app code and also all the previous installed apps on peoples' devices won't work and should be updated. -
Django static won't load
This is driving me crazy for the last 2 hours. Please help. Django 1.10 settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [] STATIC_URL = '/static/' project_folder/static/images/abc.png is working through "{ static 'images/abc.png' }" I've just added project_folder/static/images/def.png but it DOES NOT work through "{ static 'images/def.png' }" Both were tested in the same file so {% load static %} was always there. I had also tried to copy abc.png to def.png just in case my original def.png was bad. But it's still not working. I hope what I said make sense. Thank you for your help -
Django template {% with %} using variable as object value
I have a django template where I'm assigning a value to a template variable but I need to use that value to access a specific object. Ie: {% with operations.type as type %} {{ models.{{type}} }} <!-- HOW DO I DO THIS? --> {% endwith %} Is there a tag/filter that I'm unaware of? Thanks. -
Why does xlsxwriter export the data in my database from Django admin to Excel in the wrong order?
I am using xlsxwriter to export the contents of my database from Django admin to an Excel file. The headers in the Excel file are supposed to be my model field names, followed by the rows of data from my db. I've gotten the export process to work, however when I open the downloaded Excel file it shows all the columns/data from my database in a seemingly random order. They do not appear in the same order as the fields as seen in Django admin. In Django admin the info displays in the proper order of a table, Column A - Column B - Column C - Column D - Column E - etc. whereas in my exported Excel file I am seeing it all scrambled up, Column B - Column E - Column A - Column D - Column C - etc. Here is my code. I don't understand why it wouldn't be exporting the column names and data in the right order. Any help appreciated! def dump_attorneys_to_xlsx(request): if request.GET.get('export'): output = BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet('Summary') attorneys = Attorney.objects.all().values() # Write header worksheet.write_row(0, 0, attorneys[0].keys()) # Write data for row_index, row_dict in enumerate(attorneys, start=1): … -
How to store and retreive auth_token object when trying to retreive Google Contacts in Django?
My app is registered in Google and I have enabled the contacts API. In the first view I am getting the access token and I am redirecting the user to the Google confirmation page where he will be prompted to give access to his contacts: SCOPE = "https://www.google.com/m8/feeds/" CLIENT_ID = "xxxxxxxx" CLIENT_SECRET = "xxxxxxxxx" SOURCE = "http://example.com" USER_AGENT = 'dummy-sample' def import_contacts(request): auth_token = gdata.gauth.OAuth2Token( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=SCOPE, user_agent=USER_AGENT) APPLICATION_REDIRECT_URI = 'http://example.com/oauth2callback/' authorize_url = auth_token.generate_authorize_url( redirect_uri=APPLICATION_REDIRECT_URI) return redirect(authorize_url) If the user clicks Allow, then Google redirects to my handler which shall retrieve the contacts: def oauth2callback(request): code = request.GET.get('code', '') redirect_url = 'http://example.com/oauth2callback?code=%s' % code url = atom.http_core.ParseUri(redirect_url) auth_token.get_access_token(url.query) client = gdata.contacts.service.ContactsService(source=SOURCE) auth_token.authorize(client) feed = client.GetContactsFeed() As you can see, my problem is how to get the auth_token object in the second view, because this code is failing on the line auth_token.get_access_token(url.query). I have tried without success multiple options like putting the object in the session but it is not serializable. I tried also gdata.gauth.token_to_blob(auth_token) but then I can retrieve only the token string and not the object. Working with gdata.gauth.ae_save() and ae_load() seem to require in some way Google App Engine. The alternative approach that I see in order … -
After updating APNS certificate, How to solve SSL error in django push notification
I updated iOS APNS certificate in my production environment, But I am getting below error stack while I am trying to send the push notification to iOS devices. _apns_send(registration_id, alert, **kwargs) File "/home/ubuntu/rest_api/venv/local/lib/python2.7/site-packages/push_notifications/apns.py", line 150, in _apns_send with closing(_apns_create_socket_to_push()) as socket: File "/home/ubuntu/rest_api/venv/local/lib/python2.7/site-packages/push_notifications/apns.py", line 55, in _apns_create_socket_to_push return _apns_create_socket((SETTINGS["APNS_HOST"], SETTINGS["APNS_PORT"])) File "/home/ubuntu/rest_api/venv/local/lib/python2.7/site-packages/push_notifications/apns.py", line 49, in _apns_create_socket sock.connect(address_tuple) File "/usr/lib/python2.7/ssl.py", line 433, in connect self._real_connect(addr, False) File "/usr/lib/python2.7/ssl.py", line 414, in _real_connect self.ca_certs, self.ciphers) SSLError: [Errno 336265225] _ssl.c:355: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib I am using django-push notitication in my django project. How can I solve this error. -
How to make a Django ManyToManyField point to multiple child models
What I would like to do is have something like this: class Parent(models.Model): class Meta: abstract=True class ChildA(Parent): pass class ChildB(Parent): pass class Test(models.Model): m2m = models.ManyToManyField(Parent) However, this doesn't appear to work. I get errors: testing.Test.m2m: (fields.E300) Field defines a relation with model 'Parent', which is either not installed, or is abstract. testing.Test.m2m: (fields.E307) The field testing.Test.m2m was declared with a lazy reference to 'testing.parent', but app 'testing' doesn't provide model 'parent'. testing.Test_m2m.parent: (fields.E307) The field testing.Test_m2m.parent was declared with a lazy reference to 'testing.parent', but app 'testing' doesn't provide model 'parent'. This is a simplified test of what I want to do in my main app. I was wondering why this is happening and if there is some way to have a model's ManyToManyField have the ability to inherit multiple types (children) of the model Parent? -
django admin inline - add another inline when current inline value is changed
i have an inline admin object that represent 'tags': i need that on change of the current inline values (select a value in the inline), a new inline will automatically added (instead of pressing the 'Add another Tags'). i tried to add some javascript code in the change_form.html of the parent inline object. -
Javascript ajax request not running with Selenium tests
I'm trying to test the following use case with Selenium: - when user types something into a textarea, an ajax request is fired, text is added to the database (I'm using django and process request in a view.py), after a redirect the page displays entered text in a table row. - I use selenium LiveServerTest and sendKeys function to enter text into a textarea. However, it seems that Javascript is not triggered during the test at all. If I pause my test and enter text by hand, I again don't get my text displayed as I do when I run an actual server with django. Can anyone suggest what can cause this and/or the best way to test pages with Javascript using Selenium? -
firebase - django like admin panel
I am new to Firebase and want to provide an easy to use panel to my client for adding, editing and removing posts. In my earlier apps, I used Heroku - Django combo that gave me a pre-built easy to customize admin panel that was very friendly for my client to use I want something similar for my Firebase app that can be used to make modifications to database, I know there is database console to deal with this stuff but its just not user friendly, specially for someone with no technical background -
Bootstrap Jumbotron CSS Template is not working on Django Project
I am newer on Django projects and trying to apply Bootstrap to my Django website. First of all, let me show you the screen that I get because it gives a better understanding in this way. This page is "about" ("hakkimizda" folder in my project structure) page of the website and it is a flatpage of Django. Page result image My project structure is like this; my project home myproject pages static assets css dist images favicon.ico templates flatpages hakkimizda index.html jumbotron.css In my index.html file, paths are like this; <!-- Bootstrap core CSS --> <link href="/static/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="/static/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="/templates/flatpages/hakkimizda/jumbotron.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="/static/assets/js/ie-emulation-modes-warning.js"></script> Static folder contains Bootstrap's files. Pages folder is an application which is created for only flatpages. Can you help me on this problem? Thank you. -
How to use python-logstash on Django
I'm trying to use python-logstash for ElasticSearch (localy). But the statistics is not logged. I'm making this according the readme in https://github.com/vklochan/python-logstash logstash.conf input { tcp { port => 5000 codec => json } } output { stdout { codec => rubydebug } } Django settings.py LOGGING = { 'version': 1, 'handlers': { 'logstash': { 'level': 'DEBUG', 'class': 'logstash.LogstashHandler', 'host': 'localhost', 'port': 5959, 'version': 1, 'message_type': 'logstash', 'fqdn': False, 'tags': ['catalog'], }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True, }, }, } Ports Elasticsearch: 9200 and 9300 Logstash: 5000 Kibana: 5601 Where could be the mistake? -
Django: selenium functional test doesn't work after change database to PostgreSQL
All functional tests works before converting to PostgreSQL. selenium works too but jquery code, such as ajax doesn't work in selenium test. But in real test, using chrome or Firefox, all things works really good. Why does it happen? I used dj_database_url -
Django - static method is not being executed?
I can't figure out why my static method which sends email isn't executed. The reservation_cancel view changes the attribute cancelled to True if it's called. So when it "cancel" the reservation it should send an email to admin but it doensn't send anything and doesn't even execute the method probably. This is a reservation_cancel view. As you can see I've added prints to see where the code is - it prints everything including the last 'save'. It is called by AJAX. @csrf_exempt def reservation_cancel(request): id = request.POST.get('reservation_id') reason = request.POST.get('reason') reservation = reservation_models.Reservation.objects.get(id=id) if reservation.customer.id != request.user.id: return HttpResponseForbidden() reservation.reason_of_cancellation = reason print 'CANCELLING' reservation.cancel() print 'notifications.AdminNotifications.reservation_cancelled(self)' notifications.AdminNotifications.reservation_cancelled(reservation) print 'sent' return JsonResponse({'status_code': 'success'}) I've put print into the AdminNotifications.reservation_cancelled method and it doesn't print anything like the method isn't being executed. EmailThread works correctly @staticmethod def reservation_cancelled(reservation): print 'reservation_cancelled_called' subject = u'[{}]Rezervácia zrušená - {}'.format(CURRENT_DOMAIN,reservation.id) message = u'Rezervácia číslo {} bola zrušená.' \ u'\n\n\n' \ u'Dôvod: ' \ u'\n' \ u'{}'.format(reservation.id,reservation.reason_of_cancellation) EmailThread(subject,message,[ADMIN_ALERTS_EMAIL]).start() Do you know why the method isn't being executed? -
Where do I start with writing a web front end for an application using Python/Flask/Django
I really need some guidance on where to begin with this one. I am very new to programming but have managed to get a few simple Django/Flask apps up and running using documentation online. However, I am now trying to start building on my experiences by creating a web GUI for an application but I am struggling to understand the concepts required to edit an applications configuration files from within a web front end. Please could somebody point me in the direction of some resources online that I can read as I have tried a number of different google searches but I am clearly not understanding what I am searching for. Sorry for such a NOOB question, any help will be much appreciated. Thanks! -
Django view decoding danish chars from CSV
I have a csv file that contains some strange encoding of danish characters (å-ø-æ). In my Django view I'm trying to grab a string from the first row, and the date from the second row in the file. The file looks like this if I copy paste it. *01,01,Project Name: SAM_LOGIK_rsm¿de_HD,,,Statistics as of: Sat Oct 01 17:09:16 2016 02,01,Project created: Tue Apr 12 09:10:16 2016,,,Last Session Started: Sat Oct 01 16:59:22 2016* The string SAM_LOGIK_rsm¿de_HD - looks different in a text editor, where one of the characters doesn't appear at all (it won't appear in this post either) The string should be SAM_LOGIK_Årsmøde_HD - which is the value I want to store in the DB. I am decoding the file with iso-8859-1 (otherwise I get an error). with open(latest, 'rt', encoding='iso-8859-1') as csvfile: for i, row in enumerate(csvfile): if "Project Name:" in row: this = row.split(',') project_list.append(this[2][14:]) # gets the project name as is if i >= 1: break else: this = row.split(',') date = datetime.strptime(this[5][22:-1], '%c') # datetime object project_list.append(date) if i >= 1: break # break at row 2 csvfile.close() This stores the string 'as is', and I'm not sure what to do to convert it back into … -
How to declare a function "to do nothing" in Django
I'm learning Python and Django and i have a question. I would like to know how to define an function to do nothing and continue with the flow of program execution while i read an archive. while True: empty() with open(r'archive.txt') as myfile: for line in myfile: print(line) ¿ FUNCTION to do nothing how can i do it? def empty(): -
Django + IIS Windows Server 2012 R2 error
I am new into the server "world" and I have to make a django project work from a Windows Server 2012 R2. I followed this tutorial: Installing Django on IIS: A Step-by-Step Tutorial. I have a basic django project. When I start running my server it worked. Before I removed my custom handler and leave the StaticFile handler as the most important one (according to the tutorial), I tested my site to see if it works: ->If I have added in the FastCGI Settings Monitor changes to file option, then I got HTTP 500.0 Internal Server Error: File monitoring is enable for a file which could not be found - error code: 0x80070003. ->If I removed the Monitor changes to file option then I got HTTP Error 500.0- Internal Server Error C:\Python27\python.exe - The FastCGI process exited unexpectedly error code - 0x00000002. After I followed the next step from tutorial and I added virtual directory for media and static, and I also removed the previous handler to leave the StaticFile handler as the most important one, I got this result, and when trying to access the admin page, got: HTTP Error 404.4-Not Found The resource you are looking for has … -
Django migrations - django.db.utils.IntegrityError: Field may not be NULL
I altered some fields in the sqlitedb to allow fields to be Null, I then altered a field to allow null is true in the models DB. When I run the migrations i get the error: django.db.utils.IntegrityError: networks_circuitinfodata.circuit_bearer may not be NULL So ive edited the migrations file to include it, then i get django.db.utils.IntegrityError: networks_circuitinfodata.circuit_speed may not be NULL But I have both of them in the migrations file # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-10-20 13:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('networks', '0053_auto_20161020_1202'), ] operations = [ migrations.AlterField( model_name='circuitinfodata', name='circuit_speed', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='circuitinfodata', name='circuit_bearer', field=models.IntegerField(blank=True, null=True), ), ] But it seems it errors on which ever field is second in that list, I can swap them round so circuit_bearer is first, then I would error on circuit_speed. Why would the migrations only take into account whatever is first in the list and not go to the second alteration? Thanks -
How to setup Travis CI for a Django project hosted on Heroku?
I'm trying to setup TravisCI on my Django project. I'm using Heroku where a classic pattern is to use env var to get postgres database URL: settings.py DEBUG = (os.environ['DJ_DEBUG'] == 'True') import dj_database_url DATABASES = {'default': dj_database_url.config(conn_max_age=500)} example of .env file for my local env DJ_DEBUG=True DATABASE_URL=postgres://root:captainroot@127.0.0.1:5432/captaincook Now, here is my .travis.yml conf file, that tries to use the locally created db: language: python python: - 3.5 addons: - postgresql: "9.5" before_install: - export DJ_DEBUG=False - export DABATASE_URL=postgres://postgres@localhost/travisdb install: - pip install -r requirements.txt before_script: - psql -c "CREATE DATABASE travisdb;" -U postgres - python captaincook/manage.py migrate --noinput env: - DJANGO=1.9.10 script: python captaincook/manage.py test --keepdb The project works everywhere, except when deployed on travis, where I got this Django error: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Any idea? Thanks. -
How to change template names in django listview according to url request?
I have 2 templates to render one listview and I am choosing the template according to the request url given by the user. I know that, I can add 2 classes for 2 templates on 2 seperate urls respectively. For example class MyListView1(generic.ListView): template_name = 'myapp/list_one.html' ..... ..... class MyListView2(generic.ListView): template_name = 'myapp/list_two.html' ..... ..... But is there a way if I could check the url request inside one class and render the template according to it inside one listview class ? something like class MyListView(generic.ListView): if request.path == '/list1' template_name = 'myapp/list_one.html' if request.path == '/list2' template_name = 'myapp/list_two.html' I know this is not a valid code but just to visualise