Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while confirm by the mail
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' Url: from allauth.account.views import confirm_email as allauthemailconfirmation url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, name="account_confirm_email"), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), I just read about this, but I don't understand how to modify my code -
Jinja range raises TemplateSyntaxError in Django view
In a django jinja2 tempate with the code {% for i in range(10) %} foo {{ i }}<br> {% endfor %} a TemplateSyntaxError is raised with the error message Could not parse the remainder: '(10)' from 'range(10)' What do I need to do in order to loop over a range in a jinja2 template. I found a link in the django documentation explaining that Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display. but I don't think that this applies to the range function. -
Link html text to Leaflet popup
I have my leaflet markers set up to load from geojson pointfield model with the code. The popups work perfectly by clicking on it. But i want to be able to fire each popup from its corresponding slug in geojson using html text. Thanks <div id="featured"> <h1> Featured Properties </h1> {% for place in places %} <p><a id="{{ place.slug }}" href="#"> A {{ place.name }} by {{ place.owner }} </a> </p> {% endfor %} </div> <script type="text/javascript"> var collection = { { places | geojsonfeature: "popupContent" | safe } }; function onEachFeature(feature, layer) { if (feature.properties && feature.properties.popupContent) { layer.bindPopup(feature.properties.popupContent); } } function map_init(map, options) { L.geoJson(collection, { onEachFeature: onEachFeature }).addTo(map); } </script> -
How to add a non standart report in model edit view?
Here is a models: class Car(models.Model): ... id = models.IntegerField(unique=True) ... class Colour(models.Model): car = models.ForeignKey(Car, related_name='colour', null=True) How can i add non standart report while editing model fields in admin site: /admin/private//1/colour/ list_display fields ... my report(All cars - Their colours) car - colour car - colour What algorithm i should use? -
How do i read multiple json objects in django using POST method
I am sending multiple json object to server and django views how to get this multiple json objects and extracting each key value. -
Adding a dict if the query set is empty
I need to check if the Django query has values if not I need to append a dict to the query set for validation purpose. So, I don't want to create a entry in the database. Obviously, since I can't append to the queryset(Attribute Error) is there any other way to add this? listing = Listing.objects.values() if len(listing) < 1: listing.append({ 'address': 'some string', 'range': 'some other string' }) -
Error when using argparse in django project
Firstly, I wrote python code to solve my own problem, it was fine and I saved in Test.py file. A peace in this code, i use google API code at: https://developers.google.com/gmail/api/quickstart/python. You can see at quickstart.py at Step 3 in that page. Now, I must write a RestAPI webservice for this code. I'm using django rest framework to do it. I follow this example: http://agiliq.com/blog/2014/12/building-a-restful-api-with-django-rest-framework/. I run it successful. Now, I copy Test.py into this project to combine its. I just import it to views.py and don't use anything to write in views.py. Now I run again and get an error in local server: File "/../Desktop/rest_example/restapp/urls.py", line 3, in <module> from . import views File "/../Desktop/rest_example/restapp/views.py", line 7, in <module> from .Test import workWithGmail File "/../Desktop/rest_example/restapp/Test.py", line 26, in <module> flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() File "/usr/lib/python3.5/argparse.py", line 1738, in parse_args self.error(msg % ' '.join(argv)) File "/usr/lib/python3.5/argparse.py", line 2394, in error self.exit(2, _('%(prog)s: error: %(message)s\n') % args) File "/usr/lib/python3.5/argparse.py", line 2381, in exit _sys.exit(status) SystemExit: 2 and this error in client: A server error occurred. Please contact the administrator. I'm sure that Test.py raise this errors because when I don't import it, django example is fine. As you can see in this … -
django-tables2: Changing default column title of a foreign key column
How do I change the column title for a foreign value in django-tables2? My code class EmployeeTable(tables.Table) class Meta: model = EmployeeTable fields = ('name', 'employer.name') Employee.employer is a foreign key Output Name | Name Bill | Steve I would like to override the default column headers to provide more meaningful information. Preferred output Employee name | Employer name Bill | Steve Pseudo code class EmployeeTable(tables.Table) name = tables.Column(verbose_name='Employee name') # <-- Works! employer.name = tables.Column(verbose_name='Employer name') # <-- Doesn't work! class Meta: model = EmployeeTable fields = ('name', 'employer.name') -
how can I deploy multiple django cms projects under same domain.I am using apache 2.2 and mod_wsgi
I need to deploy two Django Cms projects under the same domain name. I need to retrieve the two sites when calling the following domain. http://rndbkw.tk http://rndbkw.tk/blog I have two wsgi configurations included in the httpd.conf for http://rndbkw.tk ServerName rndbkw.tk WSGIDaemonProcess rnd python-path=/home/rndbkw/djangocms:/home/rndbkw/virtualenv2.7/lib/python2.7/site-packages/ WSGIProcessGroup rnd WSGIScriptAlias / /home/rndbkw/djangocms/rnd/wsgi.py ServerName rndbkw.tk WSGIDaemonProcess blog python-path=/home/rndbkw/projects/djangocms:/home/rndbkw/projects/virtualenv2.7/lib/python2.7/site-packages/ WSGIProcessGroup blog WSGIScriptAlias / /home/rndbkw/projects/djangocms/rnd/wsgi.py But i cannot get back http://rndbkw.tk/blog -
Using django and redmine together on the same server
I'm searching for a way to configure apache correctly so that my django user can add bug in redmine without setting up multiple server. I have two half working apache configuration : The classic one : WSGIScriptAlias / /home/my_project/settings/wsgi.py The django server can run, but if I try to call a redmine url, it makes an error 404. And I tried to use a regex to protect the Redmine url pattern from Django : WSGIScriptAlias ^\/(?!redmine(.*)) /home/my_project/settings/wsgi.py For this one Redmine works, but I get the default apache page as if the configuration was'nt done for all the Django URL. Is there something wrong with my regex ? Is this the wrong approach to this problem ? Any idea ? -
I got an error while using git commit -m "Added a Procfile" on heroku
I'm using heroku for deploying a python-django project.I used git add . command and after that I gave git commit -m "Added a Procfile" .I got an error error: pathspec 'a' did not match any file(s) known to git. error: pathspec 'Procfile”' did not match any file(s) known to git. My procfile is like this. web: gunicorn resume.wsgi --log-file - How can I solve this error? -
Logging exceptions in Django commands
I have implemented custom commands in Django, and their exceptions aren't logged in my log file. I created an application my_app_with_commands which contains a directory management/commands in which I implemented some commands. A sample command, could be like this, which crashed due to an exception: import logging from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Do something usful' log = logging.getLogger(__name__) def handle(self, *args, **options): self.log.info('Starting...') raise RuntimeError('Something bad happened') self.log.info('Done.') And my logging configuration is like this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'normal': { 'format': '%(asctime)s %(module)s %(levelname)s %(message)s', } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, '..', 'logs', 'my_log.log'), 'formatter': 'normal', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'my_app_with_commands': { 'handlers': ['file', 'mail_admins'], 'level': 'INFO', 'propagate': True, }, }, } When I run the command, the calls to the logger are successfully saved to my_log.log file: 2016-09-22 11:37:01,514 test INFO Starting... But the exception with each traceback, is displayed in stderr where the command had been called: [mgarcia@localhost src]$ ./manage.py test Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/mgarcia/anaconda3/envs/my_env/lib/python3.5/site-packages/django/core/management/__init__.py", … -
Unable to run AppEngine django application locally
I am on windows 10, Installed python 2.7.11.I have a app engine application.I am able to run it locally with django, It is working perfectly.But when I am trying to run it via dev_appengine.py I am getting this error. Already tried this -
Django selenium test hanging between tests
I can't figure out why my django selenium tests are so slow. I have been working on test speed improvement in a Django application. I have written a number of Selenium tests but they have dramatically slowed down test turnaround time, with each selenium test taking approximately 25-40 seconds. I have been reading a lot about selenium test speed up and the vast majority of speed improvements are already implemented: PhantomJS headless browser, explicit waits, browser reuse between tests, find by css selector and atomic tests I have added some timers to understand where the time is lost and I was surprised to find out that setUp takes on average 1.3s, teardown takes 0.001s and the entire test function from beginning to end ranges between 1s and 4s. test_xyz(research.tests.abcde) ... /home/userxyz/.virtualenvs/xyz/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:734: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning) Time taken to setUp(): 1167 ms Page being opened: http://localhost:8081/abc/research/ Time taken to tearDown: 0 ms ok What really confuses me is the fact that after the test succeeds, with 'ok' being reported, the terminal holds on an empty row with the blinking bar for over 20s, before printing out the next test's … -
SMTPServerDisconnected error during user registration
When I try to registrate new user by using: /rest-auth/registration/ I get error: SMTPServerDisconnected at /rest-auth/registration/ Connection unexpectedly closed: [Errno 104] Connection reset by peer Settings: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.beget.ru' EMAIL_PORT = 2525 EMAIL_HOST_USER = 'order@roseonly.ru' EMAIL_HOST_PASSWORD = 'password' SECURE_SSL_REDIRECT = 'true' os.environ['wsgi.url_scheme'] = 'https' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') Error LOG Internal Server Error: /rest-auth/registration/ Traceback (most recent call last): File "/home/k/klimaku9/justforfree.ru/public_html/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/k/klimaku9/justforfree.ru/public_html/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/k/klimaku9/justforfree.ru/public_html/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/rest_framework/views.py", line 456, in dispatch response = self.handle_exception(exc) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/rest_framework/views.py", line 453, in dispatch response = handler(request, *args, **kwargs) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/rest_auth/registration/views.py", line 50, in create user = self.perform_create(serializer) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/rest_auth/registration/views.py", line 64, in perform_create None) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/utils.py", line 183, in complete_signup signal_kwargs=signal_kwargs) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/utils.py", line 143, in perform_login send_email_confirmation(request, user, signup=signup) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/utils.py", line 310, in send_email_confirmation signup=signup) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/models.py", line 62, in send_confirmation confirmation.send(request, signup=signup) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/models.py", line 172, in send get_adapter(request).send_confirmation_mail(request, self, signup) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/adapter.py", line 420, in send_confirmation_mail ctx) File "/home/k/klimaku9/.local/lib/python2.7/site-packages/allauth/account/adapter.py", line 141, in send_mail msg.send() File "/home/k/klimaku9/justforfree.ru/public_html/venv/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in … -
Datatables pagination with Elasticsearch
How can you setup pagination on Datatables with Elasticsearch? I've already populated the Datatables with Elasticsearch result but it's not rendering pagination properly. clicking on the numbered links will yield same data Here's my JS code: var searchResultTable = $('#search-results').DataTable({ "processing": true, "serverSide": true, "ajax": "elasticsearch/", "dom": "<'row'<'col-sm-6'l>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-5'i><'col-sm-7'p>>", }); Here's my views.py (An excerpt; I'm using Django): def elasticsearch_result_json(request): search_query = request.GET.get('search[value]', None) results = search_service.get_remittances_json(search_query) return JsonResponse( { 'data': results } ) -
Django, assign ForeignKey from form
I want to create a character and assign a character-class to it from a dropdown. If anybody can help me out i'm new to django. models.py: class CharClassWarrior(models.Model): strength = models.IntegerField(default=7) agility = models.IntegerField(default=6) intelligence = models.IntegerField(default=2) class CharClassHunter(models.Model): strength = models.IntegerField(default=4) agility = models.IntegerField(default=7) intelligence = models.IntegerField(default=4) class CharClassMage(models.Model): strength = models.IntegerField(default=2) agility = models.IntegerField(default=6) intelligence = models.IntegerField(default=7) class Character(models.Model): user_created = models.ForeignKey(User) name = models.CharField(max_length=50) #char_class = models.ForeignKey() attribute_points = models.IntegerField(default=10) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name forms.py class CharacterCreationForm(forms.ModelForm): CHOICES = ((CharClassHunter,'Hunter'), (CharClassWarrior,'Warrior'), (CharClassMage,'Mage'), ) name = forms.CharField(max_length=50) char_class = forms.ChoiceField(choices=CHOICES) class Meta: model = Character fields = ("name", 'char_class',) def save(self, commit = True): character = super(CharacterCreationForm, self).save(commit = False) if commit: character.save() return character Something that would look like name: _______ class: [dropdown] [submit] -
Configure Sentry for different environments (staging, production)
I want to configure Sentry in a Django app to report errors using different environments, like staging and production. This way I can configure alerting per environment. How can I configure different environments for Raven using different Django settings? The environment variable is not listed at the Raven Python client arguments docs, however I can find the variable in the raven-python code. -
Django Twitter-bootstrap : collapse not working
I am trying to include a very simple collapse in my Django project. I tried to reduce it to the minimum and it still didn't work. FYI, I tried installing jquery with pip install django-static-jquery==2.1.4 and in the end, included jquery script inside my <head>. Here are my files : 1. A simple base.html file extended in my other html template files {% load static %} <!DOCTYPE html> <html> <head> <link href="{% static 'confWeb/confWeb.css' %}" rel="stylesheet" type ="text/css" /> <link href="{% static 'confWeb/bootstrap.css' %}" rel="stylesheet" type ="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"> </script> <title>Configuration Amplivia</title> </head> <body> <ul> <li><a class="active" href="{% url 'confWeb:index' %}">Accueil</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> {% block content %} {% endblock %} </body> </html> Here is my test file, that extends from the base.html file and has two types of collasping in it, to test if any of them would work (and it doesn't) {% extends "./base.html" %} {% block content %} <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <span class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Header </span> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse " role="tabpanel" aria-labelledby="headingTwo"> <div class="list-group"> <a href="#" class="list-group-item">Item1</a> <a href="#" class="list-group-item">Item2</a> </div> </div> </div> <p> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> … -
model field not rendering on html page
I want to show title or description on html page but i am not getting. how can i do that ? models.py class Event(models.Model): title = models.CharField(max_length=100) description = models.TextField() views.py def get_event_list(request): model = Event.objects.all() return render_to_response('events.html', {'model':model}) urls.py url(r'^events/get_event_list/$','events.views.get_event_list', name ='get_event_list' ), events.html <h4>{{ model.title }}</h4> <p>{{ model.description }}</p> -
Django Rest framework JWT with custom model and fields
I am using Django Rest framework JWT. My problem is that I have to generate token based on other model rather than auth_user. For example, there is a model "Program" and it has fields "api_key" and "token". I want to generate JWT from these fields rather than "username" and "password" of "auth_user". Is there any easy way to do this? Best Regards -
Is there a way to avoid default database setting in Django project ?
According to Django we can keep default database as empty dictionary {} but when we run it , raises Improperly configured database settings. I have used automated routers in my app files and registered them on settings.py . Django cannot avoid default database . Even when we define multiple databases with default db , Django will search for queries in default database and gives error table not found in default database. Adding auth_db for auth routers bad idea cause I have 2 apps and 2 databases in one project file . Thanks in Advance :) #hope -
Django Restul return absolute URL's
So I have a fairly straight forward serializer class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = FrozenSchedule fields = ['startDate', 'endDate', 'client', 'url'] startDate = serializers.DateField(source='start_date') endDate = serializers.DateField(source='end_date') client = serializers.StringRelatedField(many=False) url = serializers.URLField(source='get_absolute_url') And it's related ViewSet class ScheduleViewSet(viewsets.ReadOnlyModelViewSet): queryset = FrozenSchedule.objects.not_abandoned().future()\ .filter(signed=False).order_by('start_date') serializer_class = serializers.ScheduleSerializer It returns JSON which looks like this: [ { "startDate": "2016-10-01", "endDate": null, "client": "Abscissa.Com Limited", "url": "/clients/abscissac/frozenschedule/1", } ] But I'd like it to return the complete URL, not just the relative path [ { "startDate": "2016-10-01", "endDate": null, "client": "Abscissa.Com Limited", "url": "http://localhost:8000/clients/abscissac/frozenschedule/1", } ] Could I serialize URL's this way inside my Serializer? The Restful documentation states that the rest_framework reverse function does exactly what I need. But it requires the request object to build the UR http://www.django-rest-framework.org/api-guide/reverse/ -
find second match jinja string
I am trying to find the second occurrence of my pattern from Jinja2. Currently have the below MACRO to find the first http URL inside my string, but I need the second one. {%- macro getHREF(key) -%} {%- set key_split = key.split(" ") -%} {%- for k in key_split -%} {%- if 'http' in k -%} {{k}} {%- endif -%} {%- endfor -%} {%- endmacro -%} I am very new to Jinja and being unable to assign inside loop, I am lost. Please advise. Thank you -
how to improve performance
I am trying to improve performance so I may need minimum number of comparisions inside template. I want to decrease number of comparisions but I dont know how I can do it. Please help me. Thanks in advance for help. {% for printNum in print %} <tr {% if printNum.number == 1 %}onclick="window.location.href='{% url 'new_print' %}'" {% else %} onclick="window.location.href='{% url 'new_reprint' %}'" {% endif%}> <td>{{ number }}</td> <td>{{ status}}</td> <td>{{ data }}</td> <td>{{ warehouse }}</td> <td>{{ printer }}</td> <td>{{ qty}}</td> </tr>