Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django datetime format different from DRF serializer datetime format
I am trying to understand why this is happening. I have a Django DateTime field and Django Rest Framework serializer that uses the field. I am trying to compare the dates for both of them and get the following results from JSON endpoint and model result: DRF: 2018-12-21T19:17:59.353368Z Model field: 2018-12-21T19:17:59.353368+00:00 Is there a way to make them similar? So, either to make both of them be "Z" or "+00:00." -
How to make a query to get only the data from each user
I have a query using 3 tables. The law, article and marked. I have a website where the user can choose one law to read all the articles. For each article, the user can marked it or type some description for this article. The marker and description is saved on the marked table. So, when the user open his law again, all his markations and descriptions will be loaded. The problem is that in my query, I dont know how show the descriptions and markations of the user logged in. My query is showing the descriptions and markations for all users registered in marked table. An example of marked table content: id is_marked description article_id law_id user_id "0" "0" "test1" "1100" "3" "1" "1" "0" "test2" "1102" "3" "1" If I access the law = 3 with the user_id =2, all the description of the user_id = 1 is showing. My query: law = get_object_or_404(Law, pk=pk) articles = Article.objects.filter(law=pk) articles = ( Article .objects .filter(law=pk) .annotate( is_marked=Exists( Marked .objects .filter( article_id=OuterRef('id'), usuario=request.user, is_marked=1, ) ) ) .annotate( description=(F('markedLaw__description')) ).order_by('id') My model: class Law(models.Model): name = models.CharField('Nome', max_length=100) description = models.TextField('Description', blank = True, null=True) class Article(models.Model): article = models.TextField('Article') id_article_law … -
Error:lokswar: ERROR (spawn error) in deploying of Django app on Digitalocean
I am deploying the django app on digitalocean but when i configure the supervisor Then i run the command sudo supervisorctl start lokswar,so i got an error.Help me to figure out the error. (urban.new1) urban@ubuntu-s-1vcpu-1gb-blr1-01:~/urban.new1$ sudo supervisorctl start lokswar lokswar: ERROR (spawn error) -
Unable to get authorization token of a User
In my django-rest-application, I successfully register a user using post method. However, when I am trying to login or get the Authorization token for the user I am getting unauthorize error. I am updating Token database using the post_save receiver as below. @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Even when I am checking the model in the python shell I could successfully verify the user and token data by the following method. from django.contrib.auth.models import User from rest_framework.authtoken.models import Token user = User.objects.get(username='user1') token = Token.objects.get(user__username='user1') The user.password and token data are verified and exist. And the user is active. However, I could not able to get the authorization token using curl method. Even I am not able login in the browser using the credentials. Curl request curl -X POST http://127.0.0.1:8000/api-token-auth/ -d "username=user1&password=password" My settings.py file is given below. # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'c8x*pc%c$0-_k-wx5&u42m3k8k1jv!^o27&-*1w3u*v!ut3-5b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True … -
Permission denied trying to save python-docx file on Ubuntu
I want to save a python-docx document to a directory with 777 privileges on Ubuntu, but I get this error: [Errno 13] Permission denied: 'media/Rooming Grand Oasis Cancun 2018-11-01-2018-11-30.docx'. This is the code of the Django Rest Framework view: def get_hotel_document(self, request, start_date, end_date, confirmed, hotel, bookings): from django.core.files import File from django.urls import reverse from docx import Document from docx.shared import Inches, Pt document = Document() section = document.sections[-1] section.left_margin = Inches(0.5) section.right_margin = Inches(0.5) style = document.styles['Normal'] font = style.font font.name ='Arial' font.size = Pt(10) ... more code ... file_name = "media/Rooming {} {}-{}.docx".format(hotel, start_date, end_date) document.save(file_name) return file_name Here you can see the permissions of the directory: The error rises when calling document.save(file_name). -
django request.POST.getlist is empty sometimes... when it shouldn't be
I have a list in a form on an html page: <label for="group_add_insurance">Click on name to remove </label> <div class="col-md-12"> <select id='group_add_insurance' name='group_add_insurance' class='form-control' size="5" multiple='multiple'> {% for ins in associated_insurances %} <option value="{{ ins.value }}">{{ ins.label }}</option> {% endfor %} </select> </div> Simple stuff, there is some javascript that if you search for an insurance and click add it will add it to the list with a simple jquery append. If i submit this form, this list in the view has stuff in it: print request.POST.getlist('group_add_insurance') Has stuff! If you click on the list where we remove an item via this: $('#group_add_insurance').change(function(){ if (confirm('Are you sure you want to remove this?')) { // Save it! $('#group_add_insurance option:selected').remove(); alert($("#group_add_insurance option").length) //just testing sanity } else { // Do nothing! alert($("#group_add_insurance option").length) //just testing sanity } }); It indeed removes the right thing! The lengths of the list also confirm the remove didn't get over zealous and the right number of items exists. But if you ever do a remove, and click submit, the print request.POST.getlist('group_add_insurance') Comes back totally empty?! even if you just remove one item. for completeness the javascript to add to the list $('#group_add_insurance').append( $("<option></option>") .attr("value",$("#insurance_search_name_id").val()) .text($("#insurance_search_name").val()) ); … -
Django localhost server refusing connection
Unable to connect to django server(refusing connection). Running below command: python manage.py runserver cant see anything after running the command. -
Overriding Django Default Authentication Form
I am trying to override the canned error message for the Django AuthorizationForm. Instead of it saying this field is required I am trying to get it to say Username is required. I have tried to subclass the AuthorizationForm with the standard LoginView and it doesn't pick up my custom clean method. I looked at this SO similar issue, Change default django error messages for AuthenticationForm and tried to follow the tips in there but still can't get it to work. Thanks in advance for any tips on what I might be doing wrong. class AuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(AuthenticationForm, self).clean() username = cleaned_data.get('username') password = cleaned_data.get('password') if username and password: pass else: self.add_error('username','Username and Password required.') pass I am trying to get it to show Username and Password Required instead of the canned default This field is required messages. No matter what I do I can't seem to get it to pick up my code above. I have it stored in my project forms.py file. I believe I'm subclassing it incorrectly. I've tried a lot of different combinations but can't seem to get it see this form. I'm running Django 1.11 -
How can I adapt form (relaive auth form) in html
I want make login form using django but I don't know how adapt django form in html. when i use only {{form.username}}, that is good working, but that method can't applying CSS style. <div class="form-group"> <div class="form-label-group"> <input type="text" id="inputEmail" class="form-control" placeholder="username" required="required" autofocus="autofocus" value ="{{form.username}}" }}"> <label for="inputEmail">Account</label> </div> -
Django - how to return a variable in template to the view as a POST request
I want to return a variable from my template to the view as a POST request. The variable is dynamic and defined by a jquery script. I dont really know much about javascript, so I dont know how to get the variable minutes and seconds to my view, so I can display them at the next site as a POST request. Here is my template in which I want to get the variables minutes and seconds to my view: {% extends "base_generic2.html" %} {% block content %} <!-- Timer function --> <script type="text/javascript"> var sec = 0; function pad ( val ) { return val > 9 ? val : "0" + val; } setInterval( function(){ $("#seconds").html(pad(++sec%60)); $("#minutes").html(pad(parseInt(sec/60,10))); }, 1000); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id="minutes"></span>:<span id="seconds"></span> <form action="results" id=results method="POST"> <!-- after clicking on this button the minutes and seconds should also be sent as a POST request --> <div class="command"> <button type="submit" name="ctest_submit">Submit solution</button> </div> </form> {% endblock %} And here is my view in which I want to use the minutes and seconds: def viewtest(request): if request.method == 'POST': minutes = request.POST['minutes'] seconds = request.POST['seconds'] return render(request, 'results.html', {'minutes': minutes, 'seconds': seconds}) else: #this section should not be … -
Rendering Django view via ajax request
Currently using ajax to monitor a long running task in a Django application. While the task runs, a progress bar is displayed, and when it finishes I'd like the ajax to make a request and load a view with the results, to render a page for the user displaying these results. How can I load the view via ajax and jquery from the front end, passing the data to the user? current (broken) solution: in my template: <script> var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; document.addEventListener("DOMContentLoaded", function () { CeleryProgressBar.initProgressBar(progressUrl); }); function customResult(resultElement, result) { $.ajax({ type: 'POST', url: '/show_results/', data:{ results:$('result').val(), 'csrfmiddlewaretoken': "{{ csrf_token }}" } }) } $(function () { CeleryProgressBar.initProgressBar(progressUrl, { onResult: customResult, }) }); </script> views.py: def show_results(request, results): template = 'fv1/fv.html' form = FVForm(request.post) if request.method == 'POST': results = request.POST.get('results') return render(request, templates, context = results) -
How customize django_wysiwyg with ckeditor flavor?
I'd like to customize the options to format the text. I like to show only the options to set bold, italic, font-size, font-background and a little bit more. I google it a lot, but I didn't figured out how to do it. To use it, I just did it: I installed the components: pip install django-wysiwyg pip install django-ckeditor I added them in Installed app in settings.py like shown below. INSTALLED_APPS = ( ... 'django_wysiwyg', 'ckeditor' ) Set the flavor in settings.py DJANGO_WYSIWYG_FLAVOR = "ckeditor" Added in my template {% load wysiwyg %} {% wysiwyg_setup %} ...... <textarea id="foo"></textarea> {% wysiwyg_editor "foo" %} -
Deployment requirements Django App on AWS
I think I have drastically underestimated my know-how for hosting a website with Django. I think I'm now at a point where I understand what parts all the pieces play, but I want to double check that knowledge. The goals / desired features of my website are: Registration / Login features Static files are served reasonably well Users are able to upload images for profiles / avatars (media files) Sections of the page automatically reload Data is stored in and accessed from the database The website is tied to my domain The main app is basically a chat room with non-numerical dice rollers, where users create very simple profiles and can use different images and names (avatars) in different rooms. Of course, I am trying to do this for as little money as possible. This is (currently) a hobby / learning thing, not a business venture. I am not expecting high traffic / that is not the main concern for launch (but, of course, I know I should be thinking about scalability). I have been able to develop the app / site on localhost. But, when it comes to production, I am really coming up against my lack of knowledge. … -
Django admin, cannot create superuser and login with custom User model
I created a custom user model by name Shop into django and when i create the super user with this command python manage.py createsuperuser it creates the super user but still setting is_staff to False, is_superuser to False and also is_admin to false. when i try to login to the admin panel using the user i get the error that my credentials are not correct.I have tried everything and research as much as i can but to no avail. I need help this is my code from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils.text import slugify from django.utils.crypto import get_random_string # generates a random string from django.db import IntegrityError class UserManager(BaseUserManager): def create_user(self, email, shop_name='', mall_name='', password=None, **kwargs): if not email: raise ValueError('You must enter an email address') user = self.model(email=self.normalize_email(email), shop_name=shop_name, mall_name=mall_name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email, password): user = self.create_user( email, password=password, is_admin=True, is_superuser=True, is_staff=True ) user.save(using=self._db) return user list_of_malls = [('Dubai mall', 'Dubai mall'), ('Dubai Festival City Mall','Dubai Festival City Mall'), ('Ibn Battuta Mall', 'Ibn Battuta Mall') ] class Shop(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, blank=False) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) shop_name = models.CharField(max_length=50, null=True) mall_name … -
Im trying to send password reset emails in Django but unfortunately its sending plain html which hasn't been covered to string
I have customized my Django reset password template but every time I send reset password emails they are sent as html which hasn't been converted into a string A good example is this <p>please go to the following page and choose a new password:</p> <h5> http://127.0.0.1:8000/api/accounts/reset/MQ/52b-204bbaf9b94c438dff7e/ Thanks for using our site! </h5> This is how it appears my inbox. My code is follows: urls.py urlpatterns = [ path('signup', UserCreate.as_view(), name='signup'), path('login', UserLoginAPIView.as_view(), name='login'), re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), path('password/reset', PasswordResetView.as_view(), {'template_name': 'templates/registration/password_reset_email.html', 'html_email_template_name': 'templates/registration/password_reset_email.html', 'subject_template_name': 'templates/registration/password_reset_subject.txt', 'from_email': config('EMAIL_HOST_USER'), 'extra_email_context': 'templates/registration/password_reset_email.txt', }, name='password_reset'), path('password/reset/done', PasswordResetDoneView.as_view(), {'template_name': 'templates/registration/password_reset_done.html'}, name='password_reset_done'), re_path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] password_reset.html <p>please go to the following page and choose a new password:</p> <h5> http://127.0.0.1:8000{% url 'password_reset_confirm' uidb64=uid token=token %} Thanks for using our site! </h5> I have done research on how I can convert html to a string with no success -
How to set Content-Disposition header using Django Rest Framework
I am serving an image using the Django REST framework. Unfortunately it downloads instead of displays. I guess I have to set the header Content-Disposition = 'inline'. How do I do this in the View or the Renderer? class ImageRenderer(renderers.BaseRenderer): media_type = 'image/*' format = '*' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data class ImageView(APIView): renderer_classes = (ImageRenderer, ) def get(self, request, format=None): image=MyImage.objects.get(id=1) image_file = image.thumbnail_png.file return Response(image) -
Django - filter Products in Category by Brands and other characteristics
I am trying to create an online store. Made categories, products are filtered correctly by category. Now I’m trying to filter products in categories by brand and other attributes. But it does not work. #Models class Product(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) category = TreeForeignKey('Category', related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey('Vendor', related_name='vendors', on_delete=models.CASCADE, blank=True, null=True) class Vendor(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) #urls urlpatterns = [ path('catalog/<slug:slug>/', views.category_catalog, name='category_catalog') ] #views def category_catalog(request, slug=None): category = get_object_or_404(Category, slug=slug) breadcrumbs = Category.get_ancestors(category, include_self=True) # cat = Product.objects.filter(category__in=Category.objects.get(id=category.id).get_descendants()) if category.get_level() <= 1: cat = category.get_descendants().order_by('tree_id', 'id', 'name') return render(request, 'shop/category_catalog.html', {'category': category, 'cat': cat, 'menu': menu(request), 'breadcrumbs': breadcrumbs}) if category.get_level() >= 2: list_pro = Product.objects.filter(category__in=Category.objects.get(id=category.id)\ .get_descendants(include_self=True)) \ .annotate(min_price=Min('prices__price')) vendors_ids = list_pro.values_list('vendor_id', flat=True).order_by().distinct() vendors = Vendor.objects.filter(id__in=vendors_ids) filter = BrandFilter(queryset=Vendor.objects.all()) print(filter) print(vendors) products_list = helpers.pg_records(request, list_pro, 12) category = get_object_or_404(Category, slug=slug) cat = category.get_descendants(include_self=True).order_by('tree_id', 'id', 'name') last_node = category.get_siblings(include_self=True) return render(request, 'shop/category_product_list.html', {'products_list': products_list, 'category': category, 'vendors': vendors, 'cat': cat, 'last_node': last_node, 'menu': menu(request), 'breadcrumbs': breadcrumbs, 'filter': filter, }) How can I implement this idea? -
How to run Django units test with default and unmanaged database?
I have a Django project with a default database used for storing things like user, orders etc. We also have an unmanaged database. Now when you run Django test they try to make test databases, but since we have an unmanaged db we cannot do this. I cannot create migrations of this db since that will land 300 errors about clashing reverse accessor. We use Docker and automatically spin up this unmanaged database and fill it with some mock data. This one is used for development and such. I would like the unit test to use this one for testing. I tried things like creating migrations but since the reverse accessor issue this is not possible. Is there a way to use the unmanaged database for unit testing? The test_default database which Django creates is fine, but I cannot create a test_unmanaged database. -
Problem by adding truncateworld and safe tags
I use Django 1.11 for my blog. I illustrate all acticles in my first page by a title, an image and a few words. For the few words, I'm using this method : {{post.text|safe|linebreaks|truncatewords:"50"}} I use a text editor and sometimes, I use for example italic text : <i/>Italic text</i> Let's imagine the value of truncatewords is on "1". It means it returns : <i/>Italic There is my problem. Some HTML tags are still opened. It means that the italic text never end and It will be applied for the rest of the code. Do you know if a trick or workaround exists ? Thank you. -
Django filter model by many to many filed with exact save values (query)
I need to filter query by many to many with exact same values. Can't find a way to do it. class MyParentModel(models.Model): name = models.CharField(max_length=1000) adds = models.ManyToManyField(Add, blank=True) def function(): adds = Adds.objects.filter(id__in=[1, 2, 3]) parent = MyParentModel.objects.filter(adds=adds) return parent -
How to pass parameter via JSON using ckeditor django?
I'm trying to pass a value as parameter to json function using ckeditor django plugin. But I'm getting page not found. It was working well before use this plugin. When I submit my textarea value, I got it: http://127.0.0.1:8000/leis/marcacao-nota/1/1/1/%22%3Cp%3Etest%3C%2Fp%3E%0A%22 404 (Not Found) When I do a console.log to check var urlRequest, I got it (I typed test in my textarea): /leis/marcacao-nota/1/1/1/"%3Cp%3Etest%3C%2Fp%3E%0A" My template: <div class="modal-body"> <textarea class="form-control estilo" rows="10" cols="50" id="comment" required="required"></textarea> {% wysiwyg_editor "comment" %} </div> My json: $('body').on('click', 'button.btn-salvar-comentario, .btn-del-comentario', function() { let comentario = encodeURIComponent(CKEDITOR.instances.comment.getData()); let artigo = this.getAttribute('data-artigo'); let lei = $(this).data('lei'); let usuario = $(this).data('usuario'); var urlRequest = '/leis/marcacao-nota/' + lei + '/' + artigo + '/' + usuario + '/' + comentario; $.ajax({ url : urlRequest, // the endpoint type : "POST", // http method data : { 'lei' : lei, 'artigo' : artigo, 'usuario' : usuario, 'comentario' : comentario }, // data sent with the post request dataType: 'json', success: function (data) { nota.attr('data-comentario', data.comentario); $(".btn-salvar-comentario").attr('data-comentario', data.comentario); } }); $('#modelComentario').modal('hide'); }); -
AttributeError: 'xxx' object has no attribute 'yyy_set'
I'm trying to reverse a foreign key relationship from one model to the another. In my case, that means seeing all Groups objects (many) for a given FieldFacet object (one). I've tried using field_object.groups_set method as described here, but i get the error: AttributeError: 'FieldFacet' object has no attribute 'groups_set' I have checked that (as is the accepted solution) I am importing the objects, and that i can refer to them bu name, and query their objects. My models look like this: class FieldBase(models.Model): field = models.ForeignKey('Field', on_delete=models.CASCADE) ... class Meta: abstract = True class FieldFacet(FieldBase): ... class Groups(models.Model): field = models.ForeignKey('FieldFacet', related_name='facet_field', on_delete=models.CASCADE) ... ff = FieldFacet.objects.get(pk=1) ff.__dict__ # output # {'_state': <django.db.models.base.ModelState object at 0x7fa22b9865c0>, 'id': 1, 'recipe_id': 1, 'field_id': 1, 'data_type': 'text', 'json_path': '_id', 'order': 0, 'normalization': True, 'stripping': True, 'intelligent_size_limit': 0, 'max_values': 10, 'sorting': 'count', 'groups': 'no', 'default_group': ''} gg = Groups.objects.all() for g in gg: print(g.__dict__) # output # {'_state': <django.db.models.base.ModelState object at 0x7fa22b986b38>, 'id': 4, 'field_id': 1, 'name': 'p', 'minimum': None, 'maximum': None, 'values': '7'} # {'_state': <django.db.models.base.ModelState object at 0x7fa22b986ba8>, 'id': 3, 'field_id': 1, 'name': 'second', 'minimum': 1, 'maximum': 3, 'values': None} # {'_state': <django.db.models.base.ModelState object at 0x7fa22b986c18>, 'id': 2, 'field_id': 1, 'name': … -
How to execute a scenario from a step in another scenario?
Below is the example I want to execute a scenario in another scenario. How can I do this? I've already known that I execute the other steps by using execute_steps(). My environment: macOS v10.14.1, Docker v18.06.1-ce, Django v2.1.4, behave v1.2.6, behave-django v1.1.0 Scenario: scenarioA Given ~ When ~ Then ~ Scenario: scenarioB Given scenarioA is completed # I want to exexute scenarioA here. When ~ Then ~ Is there an api to run the scenario from the name of the scenario? Is there an api that gets scenarios from scenario names and divides them into steps? -
How do I make a file load into the memory as soon as the server starts in django?
I want to load a file which is of type tar.gz into the memory as soon as the server starts so that I can perform operations with the requests that come in rather than loading the file every time a request a made. The way the file will load is through a function(load_archive) def _get_predictor() -> Predictor: check_for_gpu(-1) archive = load_archive("{}/model.tar.gz".format(HOME), cuda_device=-1) return Predictor.from_archive(archive, "sentence-tagger") Please help me out. -
django - Runpython function to turn charfield into foreignkey
I've been strugglin to relate a csv imported data model with a spatial data model based on a charfield field, I've created both models and now im trying to transfer the data from one field to a new one to be the foreignkey field, i made a Runpython funtion to apply on the migration but it goives the an error: ValueError: Cannot assign "'921-5'": "D2015ccccccc.rol_fk" must be a "D_Base_Roles" instance. here the the models: class D_Base_Roles(models.Model): predio = models.CharField(max_length=254) dest = models.CharField(max_length=254) dir = models.CharField(max_length=254) rol = models.CharField(primary_key=True, max_length=254) vlr_tot = models.FloatField() ub_x2 = models.FloatField() ub_y2 = models.FloatField() instrum = models.CharField(max_length=254) codzona = models.CharField(max_length=254) nomzona = models.CharField(max_length=254) geom = models.MultiPointField(srid=32719) def __str__(self): return str(self.rol) class Meta(): verbose_name_plural = "Roles" class D2015ccccccc(models.Model): id = models.CharField(primary_key=True, max_length=80) nombre_archivo = models.CharField(max_length=180, blank=True, null=True) derechos = models.CharField(max_length=120, blank=True, null=True) dir_calle = models.CharField(max_length=120, blank=True, null=True) dir_numero = models.CharField(max_length=120, blank=True, null=True) fecha_certificado = models.CharField(max_length=50, blank=True, null=True) numero_certificado = models.CharField(max_length=50, blank=True, null=True) numero_solicitud = models.CharField(max_length=50, blank=True, null=True) rol_sii = models.CharField(max_length=50, blank=True, null=True) zona_prc = models.CharField(max_length=120, blank=True, null=True) ##NEW EMPTY FOREIGNKEY FIELD rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.numero_certificado) class Meta: managed = True #db_table = 'domperm2015cip' verbose_name_plural = "2015 Certificados Informaciones Previas" ordering = …