Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form.is_valid() always returns False as the form is losing the data fbefore validations
When I added required=False in the form.It was validated yet the form.cleaned_data is empty I also tried the get option of the form and used request.GET.get("tag_query") but in vain. Also tried defining clean method inside the form class . no fruitful results. MODELS.PY: class Tag(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=100) author_pic=models.ImageField(upload_to='author_pics',blank=False) Class Problem(models.Model): title = models.CharField(max_length=200) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) author = models.ManyToManyField(Author) description=models.CharField(max_length=10000) rating=models.PositiveIntegerField() link=models.URLField(max_length=100) def __str__(self): return self.title; FORMS.PY class SearchForm(forms.Form): tag = forms.CharField(required=False,widget=forms.TextInput(attrs={'autocomplete': 'off'}) ) VIEWS.PY @login_required def index(request): form = SearchForm() q2 = Tag.objects.all() q1 = Problem.objects.none() if request.method == "POST": form = SearchForm(data=request.POST ) if form.is_valid(): print("BYE") tag_query=form.cleaned_data['tag'] print(tag_query) q1 = Problem.objects.filter(tag__name__iexact=tag_query) if q1: return render(request,'index.html',{'form':form, 'problems':q1, "tags":q2}) else: print("fuck") else: q1 = Problem.objects.all() print('hi') return render(request,'index.html',{'form':form, 'problems':q1,'tags':q2}) INDEX.HTML <!DOCTYPE html> {% extends 'base.html' %} {% load static %} {% block title %}Search Flights{% endblock %} {% block index %}{% endblock %} {% block links_n_scripts %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ form.media }} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="{% static 'js/ajax.js' %}"></script> {% endblock %} {% block body_block %} <div class="jumbotron jumbotron-translucent" style="margin: 65px 0px 45px 0px; border-radius: 0rem!important;"> <form … -
Django Admin permissions applied on REST API views
In the django admin interface, it is possible to specify permissions on each individual Model. The permission options for an example model Customer are: Can add customer Can change customer Can delete customer Can view customer However, these permissions do not seem to apply to REST Framework API Views (rest_framework.viewsets.ModelViewSet), implemented for Customer as follows: class CustomerViewSet(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' I thought that by setting the DEFAULT_PERMISSION_CLASSES to DjangoModelPermissions these permissions would be reflected, but it does not: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissions', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } Should the permissions defined in admin work in Views as well with these settings, should they not, and/or is there any way to make this happen? The benefit is that system administrators can easily define groups in the admin interface and tailor their permissions to their problem areas, so being able to define permissions in this way is very desireable. I have seen many other ways of implementing permissions, but they require from what I have seen a lot of customization on the View definitions in python. Versions: Django 2.2.9 djangorestframework 3.11.0 djangorestframework-simplejwt 4.4.0 -
Time taken for each task in celery
Doubt 1:- I am currently using celery for asynchronous tasks. In my computer currently, the function is passed to 8 workers. I wanted to know how much time is taken for processing each worker's result. Also, I have heard that in celery, for loops and print statements are not going to work, is this true? Doubt 2:- I initially tried celery outside of my Django project and now I want to integrate into my Django project. I have seen that there is a separate process for setting up celery especially in Django. Will it work if I use my previous normal celery stuff in my Django project or do I have to do it in Django way like creating __int__.py file etc,..? I maintained a task.py and in views.py I will am importing the function from the task and wrote a separate function in views.py which uses delay() function for passing the data to task.py to run it asynchronously. -
Djnago Login level
I have three types of user and each use have different dashboard means three level admin manager and operation team but i want if user is of type admin enter the admin dasbhboard and if the user is manager then enter manager dashboard and if the user is of employee enter in to respective dashboard in django want to create -
How to add all language compilers in my django project on cloud platforms like heroku
I have built an online compiler web application using django which has to compile&run languages like. - C - C++ - Java - Python - C# The command I use in my project are. subprocess.Popen("gcc filename.c",stdin = PIPE , stdout =PIPE, shell=true) subprocess.Popen("g++ filename.cpp",stdin = PIPE , stdout =PIPE, shell=true) subprocess.Popen("python filename.py",stdin = PIPE , stdout =PIPE, shell=true)``` On my local I have installed compilers for above languages and ran python subprocess commands to compile and run the code file. It worked fine on my local. But in production when I deployed m app on heroku platform It did not work well, because those compilers are missing on heroku. I have used some heroku official buildpacks provided like JVM. Only java and python languages are working. But C and C++ are not working as there is no official buildpacks for GCC on heroku. - I did't find solution anywhere can you help me with adding all the dependencies of the project. - Trying to do with docker but have no idea on how to add compilers in docker image. - Is there any possibility to add my compilers is project root directory and running Subprocess in project local environment. **Please … -
Django - render custom form fields in custom HTML template
I'm kinda new into Django and I'm facing some troubles using some custom forms. I'm using a purchased Bootstrap theme which apart from the standard classes that comes with Bootstrap has its own classes and of course, some custom CSS. I find it very difficult how Django deals with custom forms and all the sources/information/examples found online makes no sense to me. So, my elements from my HTML template use the following classes: <form action="#" method="post" class="card shadow-soft border p-4 mb-4"> <div class="form-group"> <label for="video">Video url</label> <input type="text" value="https://video.com/" class="form-control shadow-soft" id="video" placeholder="Video url" required> </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> </div> </div> </form> In forms.py I have added the following: class UpdateURLForm(forms.Form): VideoURL = forms.CharField( widget=forms.TextInput( attrs={ 'class': 'form-group' } ) ) class Meta: model = Listing fields = ('VideoURL') In views.py I have imported the form and added to the view: from .forms import UpdateURLForm def updateInfo(request): if request.method == 'POST': form = UpdateURLForm(request.POST) if form.is_valid(): pass else: form = UpdateURLForm() return render(request, 'myapp/editinfo.html', {'form': form}) Now, in my HTML template, I want to render the form field which has to inherit the custom CSS styles but somehow, I'm missing something … -
Django Rest (DRF) - using BulkListSerializer getting 400 with a blank body
Im wondering how I can troubleshoot the following... Im seeing a 400 error when using a PUT with the BulkListSerializer, however the body is just a blank list with no details as to what the error is... Does anyone know how to figure out the cause of the 400 or can see any obvious issues? Thanks data = [{"site_id": 7, "active_link_id": 371}] response: 400 response body: [""] models: class Site(models.Model): location = models.CharField(max_length=50) ref = models.CharField(max_length=255, blank=True, null=True) site_type = models.ForeignKey(SiteType, verbose_name="Site Type", on_delete=models.CASCADE) tel = models.CharField(max_length=20, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) town = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) region = models.ForeignKey(Region, verbose_name="Region", on_delete=models.CASCADE) postcode = models.CharField(max_length=10, blank=True, null=True) active_link = models.OneToOneField('circuits.Circuit', related_name='active_link', verbose_name="Active Circuit", blank=True, null=True, on_delete=models.CASCADE) views.py class MonitoringSiteConnectivity(ListBulkCreateUpdateDestroyAPIView): queryset = Site.objects.all() serializer_class = SerializerMonitoringConnectivity permission_classes = (IsAdminUser,) serialisers.py: class SerializerMonitoringConnectivity(BulkSerializerMixin, serializers.ModelSerializer): class Meta(object): model = Site fields = ('id','active_link_id',) list_serializer_class = BulkListSerializer -
How to optimice query with a lot of AND's conditions?
I have the following design problem: An entity call "Object" that has several "Metadata" (a relation many to many) and the "Product" entity allows a given user access to a set of objets depending of the metadata. For example: Product A: Metadata 1 ("Red") & Metadata 2("Blue") Product B: Metadata 3 ("Yellow") Product C: Metadata 1 ("Red") & Metadata 2("Blue") & Metadata 3("Yellow") and Object 1: Metadata 3 ("Yellow") Object 2: Metadata 3 ("Yellow") + Metadata 2("Blue") Object 3: Metadata 1 ("Red") + Metadata 2("Blue") & Metadata 3("Yellow") Object 4: Metadata 1 ("Red") & Metadata 2("Blue") So for example User 1, has access to Product B and C and cause of that should access only to Objects 1 and 3. We have a problem of scalability when we search (we have around a million of Objects, each object can contain around 6 metadatas of average, and we have around 400 pairs of them for each client, and we have more than 100k products), cause the pseudo code that we trying to run right now is like the following: for product in client_products: objects += Object.get(metadatas = product.list_metadatas) Here we think we will have a problem, cause in order to get … -
How can I get the extra-datas using class based view?
Well... I tried to calculate a score. I would like to get the 4 results of score stored (I supposed) in the liste. I get results in the terminal but I go in circle and I am unable to export them in the template... Any helps will be nice. class ShowDashboard(generic.TemplateView): template_name = "dashboard/dashboard.html" http_method_names = ['get'] def get_context_data(self, *args, **kwargs): context = super(ShowDashboard, self).get_context_data(*args, **kwargs) ... return context def get(self, request, *args, **kwargs): liste = [] i = 1 while i <= 4: questions_by_type = Question.objects.filter(typo_id=i) num_questions = Question.objects.filter(typo_id=i).count() num_answers = Answer.objects.filter(question_id__in=questions_by_type).count() sum_of_votes = Choice.objects.filter(typo_id=i).aggregate(Sum('choice_result')).get('choice_result__sum', 0.00) # total_votes try: total = (sum_of_votes / (num_answers / num_questions )) / 16 * 100 print(total) liste.append(total[i]) except: total = 0 i = i + 1 return super().get(request, *args, **kwargs) -
Table with Horizontal Scroll as Default
I got this table on my project : https://examples.bootstrap-table.com/index.html#options/large-columns.html, but I want to the default mouse scroll being the horizontal one, not vertical. How can I do that? <div id="divtest" class="container mt-2 mb-2"> <table id="tableteste" class="tabletest" data-toggle="table" data-search="true" data-virtual-scroll="true" data-detail-view="true" data-show-export="true" data-click-to-select="true" data-detail-formatter="detailFormatter"> <thead> <tr> <th data-field="tipo" data-sortable="true">Tipo </th> <th data-field="codigo" data-sortable="true">Código </th> <th data-field="descricao" data-sortable="false">Descrição </th> <th data-field="quantidade" data-sortable="true">Quantidade (Und) </th> {% for i in lista_estoque %} <th data-field="{{i.fantasia}}" data-sortable="true">{{i.fantasia}}</th> {% endfor %} <th data-field="valorun" data-sortable="true">Valor Unitário (R$) </th> <th data-field="valortot" data-sortable="true">Valor Total (R$) </th> </tr> </thead> <tbody> {% for i in lista_produto %} <tr> <td>{{i.tipo}}</td> <td class="id{{i.id}}">{{i.codigo}}- <span style="color: red;">{{i.id}}</span></td> <td class="id{{i.id}}">{{i.produto_desc}}</td> <td></td> {%if i.tipo == 'PI'%} <td class="id{{i.id}}"> {{i.valoruni}}</td> {%else%} <td class="id{{i.id}}"> {{i.compvalortot}}</td> {%endif%} {%if i.tipo == 'PI'%} <td class="id{{i.id}}"> {{i.valoruniDol}}</td> {%else%} <td class="id{{i.id}}"> {{i.compvalortotDol}}</td> {%endif%} </tr> {% endfor %} </tbody> </table> </div> -
django.db.utils.ProgrammingError: syntax error at or near "FUNCTION"
I am following Optimizing Full Text Search in Django article and at some point the article says: In order to add a trigger we need to craft a manual Django migration. This will add the trigger function and update all of our Pages rows to ensure the trigger is fired and content_search is populated at migration time for our existing records. from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('web', '0002_auto_20200115_1401') ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [migrations.RunSQL(migration, reverse_migration)] when I run the migration I get this error: django.db.utils.ProgrammingError: syntax error at or near "FUNCTION" One difference of my settings.py from the tutorial article is that it uses django.db.backends.postgresql as database engine and I use django.db.backends.postgresql_psycopg2 What can be the problem here and more importantly how can I solve this? Thanks in advance. -
Handling multiples forms in django in single views
as shown in above screenshot. I want to handle all the form independently. Here I'm using generic base view. I didn't know how to handle this situation. so any suggestion would be appreciated. In my case, all forms are static. and there are almost 60 forms. -
Profile form update is not saved to DB, even with commit = True?
I create a Profile when a user is created. The profile is empty at the time of it's creation. I also have a cuentas/perfil/ section where I want to let the users update their profiles. In this section my form is shown, the user can submit but the data is not saved. The idea is to show the form empty the first time, and the next times with all the fields the user has previously filled. views.py: It redirects to home, so the form is valid. @login_required @csrf_exempt def update_client_profile(request): user = request.user provincias_list = ["Azuay", "Bolívar", "Cañar", "Carchi", "Chimborazo"] cantones_list = ["Aguarico", "Baba", "Daule", "Echeandía", "Flavio Alfaro"] parroquias_list = ["Parroquia1", "Parroquia2", "Parroqui3", "Parroquia4", "Parroquia5"] if request.method == 'POST': profile_form = ProfileForm(provincias_list, cantones_list, parroquias_list, request.POST, request.FILES, instance=user) #import pdb; pdb.set_trace() if profile_form.is_valid(): profile_form.save(commit=True) return redirect('core:home') else: return HttpResponse("No se grabó el perfil") else: #profile_form = ProfileForm(initial={'birthdate': datetime.date(2020, 1, 15), 'cedula_ruc': '26545'}) profile_form = ProfileForm(provincias_list, cantones_list, parroquias_list, instance=user.profile) return render(request, 'scolarte/profile/perfil.html', {'client_profile_form': profile_form}) forms.py: class ProfileForm(ModelForm): MONTHS = { 1:'ene', 2:'feb', 3:'mar', 4:'abr', 5:'may', 6:'jun', 7:'jul', 8:'ago', 9:'set', 10:'oct', 11:'nov', 12:'dic' } def __init__(self, provincias_list, cantones_list, parroquias_list, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['shipping_provincia'] = forms.ChoiceField(label='Provincia', choices=tuple([(name, name) for name in provincias_list])) … -
Django Form is executing hundreds of queries
In my view, django is loading a Form (with Crispy in Template). In this modelForm i have 2 Models with Select form (account and order). I can't understand why Django makes hundreds of querys. Can someone explain? Model: This is the Model with two ForeignKey from accounts.models import Account from orders.models import Order class Costs(models.Model): account = models.ForeignKey(Account, on_delete=models.PROTECT) order = models.ForeignKey(Order, blank=True, null=True, on_delete=models.PROTECT) ... Form: from . models import Costs class CostsForm(ModelForm): class Meta: model = Costs fields = '__all__' exclude = ['created_by', 'updated_by'] widgets = { 'account': forms.Select(attrs={'class':"form-control select2"}), 'order': forms.Select(attrs={'class':"form-control select2"}), 'date': forms.DateInput(attrs={'class':"form-control datepicker"}, format='%d.%m.%Y'), 'description': forms.TextInput(attrs={'class':"form-control"}), 'invoice_number': forms.TextInput(attrs={'class':"form-control"}), 'total': forms.TextInput(attrs={'class':"form-control form-line"}), } def __init__(self, *args, **kwargs): super(CostsForm, self).__init__(*args, **kwargs) self.fields['account'].label = "Lieferant" self.fields['order'].label = "Zuordnung zum Auftrag" self.fields['invoice_number'].label = "Referenz oder Rechnungsnummer" View from .models import Costs from .forms import CostsForm def Costs_Index(request): cost_form = CostsForm(auto_id='costs.%s') return render(request, 'costs/index.html', { 'page_title_tag':'Einbuchungsübersicht', 'cost_form':cost_form, }) Template {% crispy cost_form %} Queries: Screenshot django-debug-toolbar Python: 3.7 Django: 2.2.6 Database: MySQL -
cant migrate columns in django
this is the error while i am trying to migrate some columns down below. ValueError: Field 'Contact_Number' expected a number but got ' '. class Voter_Form(models.Model): Voter_Name = models.CharField(max_length=30) Emirates_ID = models.IntegerField() Date_Of_Birth = models.DateField(auto_now=False,auto_now_add=False) Contact_Number = models.IntegerField() Email_ID = models.CharField(max_length=254) File_Upload = models.FileField(upload_to=None) Property_Registration = models.BooleanField(help_text='Enter Yes or No') -
How can I do to delete some entries which are duplicate using Django?
Hello I am using Django and I realized in the following table : id age name 1 12 John 2 12 John 3 12 John 4 15 Eve 5 16 Meghan I have some duplicates. I precise that I am using Django. How can I do to delete the following duplicates ? Thank you a lot ! -
Custom tags work every other time django?
I'm in total misunderstanding, I created custom tags for my project. I had a hard time to get them accepted by django (I had to reboot my local server several times) finally it worked here I save a new custom tag, but I can't load it in django, it tells me that the tag doesn't exist. I restarted several times. I even made a copy of my previous code by simply changing the name of the function but I can't get django to take it, it tells me that it doesn't exist... Thank you in advance :) in application > templatetags with init file etc... Work tag loaded in django :(base.html) register = template.Library() @register.simple_tag() def news_archive_date_blog(): list_all_year = New.all_year_post() if len(list_all_year) > 1: list_all_year.remove(timezone.now().year) return list_all_year @register.simple_tag() def rallies_archive_date_blog(): list_all_year = Rally.all_year_post() if len(list_all_year) > 1: list_all_year.remove(timezone.now().year) return list_all_year no work (TemplateSyntaxError at /'background_image' is not a registered tag library.)(base.html) @register.simple_tag() def background_image(): list_all_year = Rally.all_year_post() if len(list_all_year) > 1: list_all_year.remove(timezone.now().year) return list_all_year -
How can to rewrite logic from view to serializer?
At the input, I get parameters from get request (http://127.0.0.1:8000/api/v1/landing?template=1&referrer=/example/assistant/): referrer - required (CharField) template - optional (IntegerField) I wrote the following logic to handle a get request. On output, I should get json with fields: palette_type = IntegerField template_id = IntegerField profession_name = CharField profession_id = IntegerField All fields are optional But I do not like how it looks. I want to somehow do it all with a serializer.Serializer. But while I am not familiar with DRF - I do not understand how to do this ( class LandingPageRetrieveApiView(RetrieveAPIView): serializer_class = ??? queryset = ??? def _get_template(self, params, templates): if params['template'] == '1': template = templates.last().template else: template = templates.first().template return template def get(self, request, *args, **kwargs): params = request.query_params referrer = params['referrer'] slug = referrer.split('/')[-2] profession = profession_id = template = palette_type = template_id = None if '/blog/' in referrer: entry = Entry.objects.get(slug=slug) if 'template' in params: templates = entry.template_components.all() template = self._get_template(params, templates) elif '/example/' in referrer: if not referrer.endswith('/example/'): landing = LandingProfessionPage.objects.get(slug=slug) profession = landing.professions.first() if 'template' in params: template_components = landing.components.all().filter(component__contains='TemplateLineComponent') if template_components.exists(): template_component = template_components.first() template_instance = template_component.get_component_instance() templates = template_instance.template_popular_components.reverse() template = self._get_template(params, templates) if template: palette_type = template.palette_type template_id = template.component_id if … -
Exception Value: login() missing 1 required positional argument: 'user'
TypeError at /login/ login() missing 1 required positional argument: 'user' Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 3.0.2 Exception Type: TypeError Exception Value: login() missing 1 required positional argument: 'user' -
create regex for a specific string
I want to create a regex for a string like this "tst_pbl" in javascript or/and python I try /^(\w){3}_(\w){3}$ but it doesn't work Thanks -
How can I implement a custom mapping of a django model to a graphene-django type?
In Django 3.0.2 I've defined a model like the following one in <django-app>/model.py: from django.db import models from django.utils.translation import gettext_lazy as _ class Something(models.Model): class UnitPrefix(models.TextChoices): MILLI = 'MILLI', _('Milli') MICRO = 'MICRO', _('Micro') NANO = 'NANO', _('Nano') class UnitSi(models.TextChoices): VOLUME = 'CM', _('Cubicmetre') METRE = 'M', _('Metre') unit_prefix = models.CharField( max_length=5, choices=UnitPrefix.choices, default=UnitPrefix.MICRO, ) unit_si = models.CharField( max_length=1, choices=UnitSi.choices, default=UnitSi.M, ) I'm using graphene-django to implement a GraphQL API. The API provides the model via <django-app>/schema.py: from graphene_django import DjangoObjectType from .models import Something class SomethingType(DjangoObjectType): class Meta: model = Something class Query(object): """This object is combined with other app specific schemas in the Django project schema.py""" somethings = graphene.List(SomethingType) ... The result is that I can successfully query via GraphQL: { somethings { unitPrefix unitSi } } However I'd like to define a GraphQL type type Something { unit: Unit } type Unit { prefix: Unit si: Si } enum UnitPrefix { MILLI MICRO NANO } enum UnitSi { CUBICMETRE LITRE } that I can query via { somethings { unitPrefix unitSi } } How can I implement this custom model to type mapping? -
403 Forbidden error when registering custom domain for my django website
I am new to Django,I was following a tutorial on how to deploy a site using ngnix ubuntu and gunicorn,I bought a domain at namecheap and the site is hosted by LinodeBut whenever.Every step was succesful,no errors when I checked for gunicorn status,he server also restarts succesfully ,but I when I visit the domain I get a 403forbiden error. I have checked out for similar problems but none of them are of help settings.py ALLOWED_HOSTS = ['www.devbrian.com',] sudo nano /etc/nginx/sites-available/blog server { listen 80; server_name wwww.devbrian.com; location = /favicon.ico {access_log off;log_not_found off;} client_max_body_size 100M; location /static/ { root /home/brian/blog; } location /media/ { root /home/brian/blog; } location / { include proxy_params; proxy_pass http://unix:/home/brian/blog.sock; } } sudo nano /etc/nginx/sites-available/default # server { listen 80 default_server; listen [::]:80 default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you … -
How to get the name of item search display in url
How do i get the name of the search item display in url. As shown in the image. For example i search for bag, i want the word 'bag' to be displayed in url. def search_result(request): query = request.GET.get('q', '') if query is None: return redirect("shop:homepage") else: item = Item.objects.all().order_by("timestamp") if item: item = item.filter( Q(title__icontains=query) ).distinct() if item.count() == 0: messages.error(request, "No search results found") paginator = Paginator(item, 1) page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { 'search': queryset, 'query': query, } return render(request, 'search_result.html', context) -
Django Import-Export: 'tablib.formats._xls' has no attribute 'title'
Im using django import-export module and I had an issue with UNIQUE CONSTRAINT FAILED: Django Import Export - UNIQUE constraint failed In the end I had to rebuild the database and I encountered this error: Django - No such table: main.auth_user__old So I changed the django version to 2.1.5 as per a solution in the thread. Now I get this error: 'tablib.formats._xls' has no attribute 'title' Please find below the full traceback: Traceback (most recent call last): File "D:\Users\...\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Users\...\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Users\...\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\...\env\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Users\...\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Users\...\env\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner return view(request, *args, **kwargs) File "D:\Users\...\env\lib\site-packages\import_export\admin.py", line 278, in import_action **form_kwargs) File "D:\Users\...\env\lib\site-packages\import_export\forms.py", line 21, in __init__ choices.append((str(i), f().get_title(),)) File "D:\Users\...\env\lib\site-packages\import_export\formats\base_formats.py", line 92, in get_title return self.get_format().title AttributeError: module 'tablib.formats._xls' has no attribute 'title' Thank you for any help -
insertion in nested serializer in DRF
Currently i am using django rest_framework.I have two different class name as Customer and Customerinfo . My code is working properely . Now I want to insert value in the customer serializer. In CustomerSerializer it has Customerinfo field. These are the serializer: class CustomerinfoSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ['id','phone'] class CustomerSerializer(serializers.ModelSerializer): info = CustomerinfoSerializer(many=True, source='customerinfo_set') class Meta: model = Question fields = ["id","name","info"] How can i use post method to insert value ? sample values are: { "name": "user10", "info": [ { "phone":12345 }, { "phone":54321 } ] }