Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
`TypeError: argument 2 must be a connection, cursor or None` in Psycopg2 with Django on Heroku
I have a heroku pipeline set up, and have just enabled review apps for it. It is using the same codebase as my staging and production apps, same settings files and everything. When the review app spins up, it can connect to the created DB and run migrations. When I try to connect to the app in the browser, I get `TypeError: argument 2 must be a connection, cursor or None` in `psycopg2/_json.py, register_json:139` Top of stack is: `django.contrib.sites.models._get_site_by_id`. I've attached the Opbeat output of the error frame at the bottom of this post. Settings file is linked. When I set DEBUG=True, everything works fine. Which might suggest an ALLOWED_HOSTS issue, but when I set ALLOWED_HOSTS to '*' with DEBUG=False, it still errors? What is wrong with my setup? This works in staging, and production, but not the review apps. -
Django Admin filter_horizontal is not working
I cannot set filter horizontal admin.py class ArticleAdmin(admin.ModelAdmin): exclude = ('position',) filter_horizontal = ('key', ) admin.site.register(Article, ArticleAdmin) models.py class Article(models.Model): author = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_DEFAULT) position = models.PositiveSmallIntegerField("Position", null=True) key = models.ManyToManyField(Keyword, blank=True, verbose_name=u"Schlagworte") created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField(default=timezone.now, editable=False) Can someone point me to my issue here? -
How to get django-autocomplete-light to work with smart selects (in 2016)?
I just got organization, a ForeignKey field that is affected b django-autocomplete-light to work, however office location, the following dropdown field, should be populated with an organization's office_locations via smart selects. Instead it returns -----, the signifier for no available choices. models.py class Person(models.Model): ... organization = models.ForeignKey(Organization, related_name='people') office_location = ChainedForeignKey( OfficeLocation, chained_field='organization', chained_model_field='organization', related_name='people', null=True, auto_choose=True, ) class OfficeLocation(models.Model): organization = models.ForeignKey(Organization, related_name='office_locations') ... autocomplete_view.py class OrganizationAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): raise PermissionDenied results = Organization.objects.filter(name=self.q) if len(results) > 0: return results else: return Organization.objects.filter( Q(name__icontains=self.q) | Q(pseudonyms__icontains=self.q) | Q(website__icontains=self.q) ).order_by('name') urls in #urls.py url patterns = [ url(r'', include('contacts.urls', namespace='contacts')), url(r'^chaining/', include('smart_selects.urls')), ] # in contacts/urls.py url( r'^organization_autocomplete/$', OrganizationAutocomplete.as_view(), name='organization_autocomplete', ), forms class PersonForm(forms.ModelForm): class Meta: model = models.Person fields = "__all__" widgets = { 'organization': autocomplete.ModelSelect2( url='contacts:organization_autocomplete', attrs={'data-minimum-input-length': 3}, ) } Some digging revealed a response from 2012 says that won't work together, in which some made the workaround # in urls.py from smart_selects.widgets import ChainedSelect ChainedSelect.Media = None but adding the snippet hasn't solved the issue. I am using Django==1.10.2 django-autocomplete-light==3.2.1 django-smart-selects==1.2.4 and from what I could discern, both libraries are compatible with django 1.10. Let me know if I need to post more … -
How to log in to a different bank for each Django user?
Suppose I have a Django system in a centralized database that does the following: For each user logged in he log in your own database, ie, each user has his seat, and when he log into the system, the system automatically connects to your bank. -
Django - How to save an object from a model in a view
I'm running Django 1.10 on Python 3.7. I have a problem when I try to save an object from a model after applying a function on it. What I want to do is just to substract a certain amount of money (this amount is stored is the class (klient) attribute argent). So I created a method called acheter in this class with an argument id_achat to be able to substract different amounts of money. When I run the command a.acheter(id) (where a is a klient object and id_achat an integer) in the shell, everything is OK, the substraction has been done when I look at a.argent. However, in interface_du_klient.html, I put some links to redirect the user to a view called achat. In this view I call the acheter method on my klient object called with the get_object_or_404 method, but the attribute argent of this klient object is not modified. Here you can see my models.py : from django.db import models from django.contrib import admin import decimal class klient(models.Model): id_klient=models.CharField(max_length=100, primary_key=True) nom=models.CharField(max_length=100) prenom=models.CharField(max_length=100) argent=models.DecimalField(decimal_places=2,max_digits=4) membre=models.IntegerField() # 0 pour non membre, 1 pour membre KFet date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date d'enregistrement") nombre_biere=models.IntegerField(default=0) nombre_pinte=models.IntegerField(default=0) nombre_cafe_ou_the=models.IntegerField(default=0) nombre_canette=models.IntegerField(default=0) def __str__(self): return "{0} {1}".format(self.nom,self.prenom) def … -
Django session is not deleted after logout
I recently discovered that the logout functionality of my Django app seems to be broken. I believe it worked in the past, but I cannot figure out why it is not working now. That's my setup: index.html: ... {% if request.user.is_authenticated %} <a style="position: absolute; top: 0; left: 0;" href="{% url 'auth_logout' %}">Logout</a> {% else %} <a style="position: absolute; top: 0; left: 0;" href="{% url 'auth_login' %}">Login</a> {% endif %} ... urls.py: ... from django.contrib.auth import views as auth_views ... urlpatterns = [ ..., url(r'^accounts/logout/$', auth_views.logout, name='auth_logout'), url(r'^accounts/login/$', auth_views.login, name='auth_login'), ... ] Templates: login.html: {% extends 'simple_logo_base.html' %} {% block content %} <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h2>Login</h2> {% if next %} <form action="/accounts/login/?next={{next}}" method="post" > {%else%} <form action="/accounts/login/" method="post" > {% endif %} {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </div> <div class="col-md-3"></div> </div> {% endblock %} logout.html: {% extends 'simple_logo_base.html' %} {% block content %} <h2 class="text-center">Logged out</h2> {% endblock %} Where "simple_logo_base.html" is just the plain html structure with a div containing a logo. The problem: The logging in works perfectly fine. If I try to access the restricted index.html page, I am redirected to the login page, can login and can access the … -
Datatables - Individual Column Sort not working in Django
Im trying to implement the Individual column sort in my django project. I am able to convert the table into a datatable and the search bar that is displayed works perfectly in searching the table. I modified the code shown in the link a little to allow sorting only selected columns via the select dropdown and also have the select dropdowns appear in a different div. I was able to get the select dropdown in the div: However When I select an option form the dropdown the table displays no matching records found , when clearly data matching the criteria exists. Any help in figuring out the issue will be greatly appreciated. Code is pasted below: $(document).ready(function () { $('#audience-list').DataTable({ initComplete: function () { this.api().columns([1]).every(function () { var column = this; var select = $('<select><option value=""></option></select>') .appendTo($("#sort")) .on('change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search(val ? '^' + val + '$' : '', true, false) .draw(); }); column.data().unique().sort().each(function (d, j) { select.append('<option value="' + d + '">' + d + '</option>') }); }); } }); }); -
use DATABASES while loading settings of django
I need to use inside django's settings.py: ... DATABASES = {...} def get_domain(): from django.contrib.sites.models import Site return Site.objects.get_current().name sth=get_domain() ... DATABASES = {...} # overwrite, which doesnt work ... My settings.py is complex with loading customized settings as well, so the order cannot be changed. The problem is that above function will actually load DATABASES somewhere to django's db layer and it is impossible then to overwrite that with second DATABASES. How to inform django that DATABASES (and only this!) should be loaded again? -
django-leaflet does not appear to allow circle drawing
I'm using django-leaflet and django-geojson in my project, it is on github at: https://github.com/makinacorpus/django-leaflet Using the widget for the Django Admin (LeafletGeoAdmin) I can draw polygon shapes, or rectangle shapes, that I then store as geojson in my models. The leaflet examples I've seen (outside of django) also have a circle shape available (I think it produces a "Circle marker"), but it does not appear as an option here. I can't find any info about adding shape types, in readme/tutorials. Is it possible to do? -
Heroku free quota exceeded issue
My heroku app recently started idling because my dyno quota hours were surpassed. However, I entered my credit card information and got additional hours. I tried restarting my app and the log continues to show the following error message upon starting up. 2016-10-26T17:45:22.125676+00:00 heroku[web.1]: State changed from down to starting 2016-10-26T17:45:28.108808+00:00 heroku[web.1]: Starting process with command `gunicorn NHS.wsgi` 2016-10-26T17:45:30.313014+00:00 app[web.1]: [2016-10-26 17:45:30 +0000] [3] [INFO] Starting gunicorn 19.3.0 2016-10-26T17:45:30.313663+00:00 app[web.1]: [2016-10-26 17:45:30 +0000] [3] [INFO] Listening at: http://0.0.0.0:39806 (3) 2016-10-26T17:45:30.313796+00:00 app[web.1]: [2016-10-26 17:45:30 +0000] [3] [INFO] Using worker: sync 2016-10-26T17:45:30.320489+00:00 app[web.1]: [2016-10-26 17:45:30 +0000] [9] [INFO] Booting worker with pid: 9 2016-10-26T17:45:30.413058+00:00 app[web.1]: [2016-10-26 17:45:30 +0000] [10] [INFO] Booting worker with pid: 10 2016-10-26T17:45:31.854431+00:00 heroku[web.1]: State changed from starting to up 2016-10-26T17:45:31.867417+00:00 heroku[web.1]: Idling 2016-10-26T17:45:31.867904+00:00 heroku[web.1]: State changed from up to down 2016-10-26T17:45:31.875072+00:00 heroku[web.1]: Idling because quota is exhausted 2016-10-26T17:45:36.096415+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2016-10-26T17:45:37.061190+00:00 app[web.1]: [2016-10-26 17:45:37 +0000] [9] [INFO] Worker exiting (pid: 9) 2016-10-26T17:45:37.061294+00:00 app[web.1]: [2016-10-26 17:45:37 +0000] [3] [INFO] Handling signal: term 2016-10-26T17:45:37.069343+00:00 app[web.1]: [2016-10-26 17:45:37 +0000] [10] [INFO] Worker exiting (pid: 10) 2016-10-26T17:45:37.104578+00:00 app[web.1]: [2016-10-26 17:45:37 +0000] [3] [INFO] Shutting down: Master 2016-10-26T17:45:37.176041+00:00 heroku[web.1]: Process exited with status 0 Is there any way to … -
Pythonic way of accessing Django objects
Can any one suggest me the way to do these requests in pythonic way. Customer.objects.get(pk=pk) Customer.objects.get(uid=uid) -
Not running server with browsersync + django + gulp
The page is loading and shows nothing. Version: Python: 3.5.2 Django: 1.10.2 node: 4.2.6 npm: 3.5.2 Gulp run without error: gulpfile.js var gulp = require('gulp'); var browserSync = require('browser-sync').create(); var exec = require('child_process').exec; gulp.task('runserver', function() { var proc = exec('python manage.py runserver'); console.log('runserver'); }) gulp.task('browserSync', ['runserver'], function() { browserSync.init({ notify: false, port: 8090, proxy: 'localhost:8090' }) console.log('browserSync'); }); gulp.task('default', ['browserSync']); -
How to merge multiple QuerySets in django?
I have following models class Molecule(models.Model): mid = models.IntegerField(primary_key=True) mol_name = models.CharField(max_length=2023, blank=True, null=True) class Pubchem(models.Model): molecule = models.OneToOneField('Molecule', primary_key=True, db_column='mid') pnum = models.IntegerField(blank=False, null=False) in the views.py, I am trying to get Query Set which has mid, mol_name and if pnum available. querySet1 = Molecule.objects.all() querySet1 = querySet1.filter( Q(mol_name__istartswith=currentInitial) | Q(mol_name__istartswith=currentInitial.lower()) ).distinct('mol_name') querySet2 = Pubchem.objects.filter(molecule__mol_name__istartswith=currentInitial).select_related('molecule').order_by('molecule') in the querySet2 not all molecules are included, which don't have entries in Pubchem they are ignored. What should be improved in either querySet1 or querySet2 to get all the required information in querySet? Or merging them is better option? if so how? -
how i can introduce a image into of PDF generated with weasyprint?
I can generate a PDF using Django and weasyprint, but, i have a problem with a html, when i need load to image, then, i get a error. My implementation is it: This is my implementation and my html, i call the image with a simple "img src="{{ constancia.imagencita.url }} " and i get "/media/firmas_directores_rrhh/180px-Walt_Disney_1942_signature.svg.png" (Pixbuf error: Unrecognized image file format)" -
Bootstrap layout issue when displaying images
I've been facing this issue for a day or so. Basically I have this code <div class="container"> <div class="row"> {% for post in posts %} <div class="col-md-6"> <div class="thumbnail"> <img src="{{ post.image.url }}" alt="..."> <div class="caption"> <h3>{{ post.title }}</h3> <p>{{ post.body|truncatechars:120 }}</p> <p><a href="#" class="btn btn-primary" role="button">View</a></p> </div> </div> </div> {% endfor %} </div> </div> I would like to have two columns next to each other with an image diplayed. At the moment the first line is alright 2 images are displayed properly but on the second line only one is display. There is no margin or padding which block two images to be displayed on each second row. Image for the issue here -
Manually deploying on Ubuntu a Django application made in Visual Studio
I have installed on the Ubuntu server: apt-get install python-pip apache2 libapache2-mod-wsgi pip install virtualenv mkdir -p /django/projects/prj01 cd /django/projects/prj01 create the virtual environment: virtualenv prj01env activate the virtual environment: source prj01env/bin/activate install django in the virtual environment: pip install django I previously uploaded project folder with winscp now I copy that project in /django/projects/prj01: cp /home/myuser/prj01/ ./ cd prj01 change permissions: chmod +x /django/projects/prj01 chown -R www-data:www-data /django/projects/ convert the text file from windows to linux format: dos2unix manage.py Finally I run manage.py ./manage.py makemigrations And then I receive the follow error message: (prj01env) root@RSR0008:/django/projects/prj01/prj01# ./manage.py createsuperuser Traceback (most recent call last): File "./manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/django/projects/prj01/prj01env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] … -
How do I retrieve the latest foreign key related items by group?
I have the following models: class Employee(models.Model): name = models.CharField(max_length=200) class LogEntry(models.Model) employee = models.ForeignKey(Employee) log_type = models.CharField(max_length=2) entry_date = models.DateTimeField() log_data = models.TextField() In this case, the log_type is a 2 alpha code (there are many options). For a given employee, I would like to retrieve the latest LogEntry for all log_types that the given employee has created. I have seen examples using annotate to grab the latest for all employees, or the latest for all log_types, but not one that restricts on one field, while annotating on another. Everything I have tried thus far has not worked. -
Django - trouble with grouping in table and rowspan
<table style="width:50%"> <tr> <th>Excercise</th> <th>Sets</th> <th>Reps</th> <th>Weight</th> </tr> {% regroup excercises by created_date.created_date as lifts %} {% for group in lifts %} {% for lift in group.list %} {% if lift.created_date == date %} <tr>{%ifchanged %} {% if group.list|length|divisibleby:2%} <td rowspan="{{group.list|length|div:2}}">{{lift}}</td> {% else %} <td rowspan="{{group.list|length|add:1|div:2}}">{{lift}}</td> {%endif%} {%endifchanged%} <td>{{lift.sets}}</td> <td>{{lift.reps}}</td> <td>{{lift.weight}} {{lift.unit}}</td> </tr>{%endif%}{%endfor%}{%endfor%} </table> This is my template for making table. Its hardcoded on the rowspan that's why and dont know how to make it more universal. I want to rowspan by various numbers. If the same lift occurs more than one time i want it to rowspan by number of occurrences. And this is from views.py: def lift_date(request, pk): date = get_object_or_404(Dates, pk=pk,) excercises = Lifts.objects.filter(user=request.user).order_by ('created_date__created_date') return render(request, 'lift/lift_date.html', {'date': date, 'excercises': excercises}) Right now it looks like this:That's how this table should look like If I have 3 "bench presses" I want to show them as one row. But if add other lifts eg single squat it will look like this I know it is because of my way for coding rowspan but I dont know how to do it other way Is there a way to make rowspan depend on number of occurrences? -
DataTables Next button not working
I have a DataTable being initialized in a HTML web page, rendered piecewise by ajax calls to a Django backend. Everything is working great, however, the [Next] and [Last] datatable buttons are not working. Pagination works fine, Prev and First also work fine. DataTable code: var object_table = $('#object_table').DataTable( { "sDom": '<"H"lfr>t<ip>', "sPaginationType": "full_numbers", "iOverlayFade": 100, "processing": true, "serverSide": true, "ajax": '/objects/object_list/', "deferRender": true "aoColumnDefs": [ { "aTargets": [ 0 ], "sWidth": "1%", "searchable":false, "orderable":false, } ], "columns": function ( row, data, index ) {... }] }); And this is what the code looks like as it's passed from django on the datatables ajax call def dt_object_list_loader: r_sequence = int(request.GET.get('draw', 0)) r_length = int(request.GET.get('length', 10)) r_start = int(request.GET.get('start', 0)) objects = djangomodel.objects.filter(...) result_list = [objects[r_start:r_start + r_length] response_data = {} response_data['recordsTotal'] = len(result_list) response_data['draw'] = int(request.GET.get('draw', 0)) response_data['data'] = result_list return HttpResponse(jsonpickle.encode(response_data), content_type='application/json') Pagination works fine, and everything loads without error. But 'next/last' are blurred out, and when I click them, django fires the error: Internal Server Error: /mcontrol/task_list/ Traceback (most recent call last): .... r_start = int(request.GET.get('start', 0)) ValueError: invalid literal for int() with base 10: 'NaN' DataTables also fires a cryptic Error 7 (general ajax error) when the … -
Django filter queryset based on many to many extra fields model
Here is a models example. class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) I want to get all Person objects, and for each one adding a column 'is_member' that values True if the person is member at least of one group. I try with annotate and count, but I'm a bit confused... Thank you. -
Django refresh options of select field form without reload page
Hi guys I hope you can help me to solve this doubt, I have a form and I render on my template a select with several options related to another model, something like {{form.selectfield}} and also I have in the same template a modal to add a new option to my select field in which I make a post through jquery ajax and get a response to display a success or error message, it's posible to reload or refresh the rendered select to add the new option without reloading the page to render again the field? If it's possible can you explain me how to achieve that? The post works fine and display a message in a div. I just need to know if it's possible to refresh the select without reloading the page. Thanks Jquery: function crear_contacto() { console.log("funcion crear contacto!") // sanity check $.ajax({ url : "/contactos/agregar_ajax/", // the endpoint type : "POST", // http method data : { nombre : $('#id_nombre').val(), email1 : $('#id_email1').val(), tel1 : $('#id_tel1').val(), tel2 : $('#id_tel2').val(), direccion : $('#id_direccion').val(), csrfmiddlewaretoken: '{{ csrf_token }}', }, // data sent with the post request // handle a successful response success : function(json) { $('#myModal2').modal('hide'); $(".modal-backdrop").remove(); $('#contactoform').trigger("reset"); … -
django + react deploy on heroku
http://geezhawk.github.io/using-react-with-django-rest-framework I have followed the tutorial above and cannot figure out to deploy to heroku. How can I do this? -
Qpixmap error on using matplotlib in django1.9
Following is the code in my django views.py for plotting a graph from a dat file and viewing through html template. But on running a program through webserver it says error "QPixmap: It is not safe to use pixmaps outside the GUI thread ". Could anyone please help me how to resolve this error? Your help is really appreciated. import numpy as np import matplotlib.pyplot as pl from django.shortcuts import render def contact(request): data = np.loadtxt('media/contact.dat') xdata = data[:,0] ydata = data[:,1] pl.plot(xdata,ydata,color='black',alpha=0.7, lw = 1) pl.fill_between(xdata,ydata, color = 'red') pl.savefig('media/contact.png') pl.close() return render(request, 'personal/contact.html') -
Nginx redirect to 404 dynamic custom template
I'm currently a problem for which I run out of solutions: Quickly resume: The project is write with Django, I have my custom 404 configured correctly and I have some specific urls that are stuck to the nginx 404 rendering instead of my django template. Example: mydomaine.org/en/%20 My django 404 is a template, which means that it's dynamically link to a page within the CMS. I don't have a custom 404.html (or, let's say its writes with {% myheader %} etc ) So, here is my first try: rewrite ^/en/\s.*$ mydomain.org/en/404 permanent; but this return a 302 code and doesn't take the language in consideration. So I tried something else: error_page 404 /404.html; (but of course I don't have a proper template whatever) location ~ /(?:en|fr|de|es|tr|ja)/\s.* { return 404 mydomain.org/$1/404; } doesn't work. location ~ /(?:en|fr|de|es|tr|ja)/\s.* { error_page 404 mydomain.org/$1/404; } doesn't work. location ~ /(?:en|fr|de|es|tr|ja)/\s.* { return 404; } Not the behaviour I want :( Apparently I can only do a rewrite or show nginx 404? Nah I can't believe it, google uses its own template for google.com/%20 . Does anyone have an idea? I'm completely lost. -
Django 1.9 'ascii' codec can't encode character u'\xf1'
I had this same error while working with latin names and i could solve it defining a __unicode__ function in my model like this: class MyModel(models.Model): # fields def __str__(self): return str(self.field) + " - " + self.field def __unicode__(self): return str(self.field) + " - " + self.field but this time, even with that function i cant make it work in other model when i try to display them in a select input: template.html <div class="form-group"> <label for="input_especialidad">Compañero</label> {{ puntual_form.employee }} <!-- the error is detected here --> <div id="help-error" class="hidden"> <p class="help-block">Este campo es obligatorio.</p> </div> <div id="help-info"> <p class="help-block">Los nombres empiezan por su apellido seguido por los nombres.</p> <p class="help-block">Tambien puedes teclear el nombre de tu compañero para buscarlo.</p> </div> </div> forms.py class form_Nom_puntual(forms.ModelForm): class Meta: model = Nom_puntual fields = ['employee'] widgets = { 'employee': forms.Select(attrs={'class': 'form-control', 'id': 'puntual_employee'}), } models.py class Employees(models.Model): num_employee = models.PositiveIntegerField(unique=True, null=True) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return str(self.name) def __unicode__(self): return str(self.name) class Nom_puntual(models.Model): employee = models.OneToOneField(Employees, on_delete=models.PROTECT) ip_nominator = models.GenericIPAddressField() traceback Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character u'\xf1' in position 4: ordinal not in range(128) Exception Location: /home/rortega/smce/votaciones/models.py in __str__, line …