Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model max_length from another Django model
I have two models. The model Copy should get the max_length from the model AdSpot without inheriting from it. And after trying multiple times, I failed to make this work: class AdSpot(models.Model): title_max_chars = models.IntegerField(default=0) @property def title_max_chars_from_adspot(self): return self.title_max_chars class Copy(models.Model): adspot = models.ForeignKey(AdSpot, on_delete=models.PROTECT) def title_max_chars_from_adspot(self, *args, **kwargs): return self.adspot.title_max_chars_from_adspot title = models.CharField('Name', max_length=title_max_chars_from_adspot, default="") The error is polls.Copy.title: (fields.E121) 'max_length' must be a positive integer. What am I missing ? -
Django FE + BackEnd integration
I started up a project in django. It is still not very big but it has some 5 apps already active . The project was done in django backend and in the html. the FE is plain JS and CSS - the FE code is in every app. I heard\read that react\angular are far more popular for FE and have many benefits and I know django can work with them (But needs some adjustments made to it). my question is, is project like mine - that keeps all the login in django without using a JS framework - scalable\preferable? should I make the effort to refactor my code to django+react (so I wont have to do it later)? best practices \ references to articles will be appreciated (looked for it but didnt find anything that really meets my needs) -
How can I test whether get_absolute_url redirects me to desired url after CreateView or not
There are 3 model and I have 3 CreateView for each. and I want to test redirection after filling the form. I have tried writing 3 tests but 2 of them face with failure. However the app is working as I want in my browser. all models have this get_absolute_url method def get_absolute_url(self): return reverse('foo', kwargs = {'pk':self.pk}) Three create view for above models is exactly like this class foo(CreateView): form_class = bar template_name = 'xxx.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) And this test works class Test_get_absolute_url(TestCase): def test_electronical_GAU(self): client = Client() create_electronical_ad_path = reverse_lazy('create_electronical_ad') User.objects.create(username = 'user1', password = 'TESTuSER1234') user = User.objects.get(username = 'user1') client.force_login(user) form = {'title':'title', 'price':123, 'location':20, 'tag':1,'description':'description'} response = client.post(create_electronical_ad_path, form) expected_url = reverse_lazy('electronical_detail', kwargs = {'pk':1}) self.assertRedirects(response, expected_url) While this does not def test_viechle_GAU(self): client = Client() create_viechle_ad_path = reverse_lazy('create_viechle_ad') User.objects.create(username = 'user1', password = 'TESTuSER1234') user = User.objects.get(username = 'user1') client.force_login(user) form = {'title':'title', 'price':123, 'location':20, 'produced':2019, 'color':'color', 'color': 'red' ,'description':'description'} response = client.post(create_viechle_ad_path, form) expected_url = reverse_lazy('viechle_detail', kwargs = {'pk':1}) self.assertRedirects(response, expected_url) -
Retrieving Values from ModelMultipleChoiceField Checkboxes
Big Picture: Ultimately I have no idea of if I approached this correctly but this is as far as I have got. I am building a platform for lawn care industry service providers. Each company is capable of offering different services so I setup a model that allows each service provider to create their own services. When the service provider sets up an appointment for their customer, I want them to be able to select from a list of checkboxes. I large in part referenced this thread to get the logged in users entries to display. Customizing django form based on currently logged in user I have gotten as far as displaying the list of services correctly based on the logged in user but I am having trouble with the POST processing/validation. The form saves correctly everywhere EXCEPT where the checkboxes are selected. I ultimately want those saved into a Charfield in a different model "form_a" in a comma delimited format. Corresponding portion of the View: def new_booking(request): page_title = "New Booking" template = 'jobs/new-booking.html' customer_id = request.GET.get('customer') customer = '' form_a = AddJob(request.POST or None) form_b = AddJobDatePicker(request.POST or None) form_c = PersonForm2(request.POST or None) form_d = AddJobServices(**{'user': request.user}) … -
Shared database with isolated schema and centralized Admin panel
I have a project configured in this way. Is there any possibility to have a centralized admin panel instead of visiting each domain separately? thor.polls.local:8000/admin/ potter.polls.local:8000/admnin/ -
Is there a way to add up model values in django?
I want to get the total of all days combined. I can't really figure out how to add them and store the total value. Does anyone know how I could fix this? Here is my model: class Weekstaat(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',) jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE) week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE) werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE) #contract = models.ForeignKey(Contract, null=False, blank=False, default=1,on_delete=models.CASCADE) maandag = models.FloatField(null=True, blank=True, default=0) dinsdag = models.FloatField(null=True, blank=True, default=0) woensdag = models.FloatField(null=True, blank=True, default=0) donderdag = models.FloatField(null=True, blank=True, default=0) vrijdag = models.FloatField(null=True, blank=True, default=0) zaterdag = models.FloatField(null=True, blank=True, default=0) zondag = models.FloatField(null=True, blank=True, default=0) def __str__(self): return str(self.jaar) + ' week ' + str(self.week) + str(self.werknemer) + str(self.status) and here is the html: <td class="text-center"> {{ Weekstaat.maandag }} </td> <td class="text-center"> {{ Weekstaat.dinsdag }} </td> <td class="text-center"> {{ Weekstaat.woensdag }} </td> <td class="text-center"> {{ Weekstaat.donderdag }} </td> <td class="text-center"> {{ Weekstaat.vrijdag }} </td> <td class="text-center"> {{ Weekstaat.zaterdag }} </td> <td class="text-center"> {{ Weekstaat.zondag }} </td> <td class="text-center"> ................... </td> -
Why can a superclass in django-oscar call a method that it does not implement?
Big picture: I am currently trying to work with django-oscar (specifically, attempting to integrate custom ways to pay as well as modify the checkout flow). Problem: I encountered code that I'm quite certain should not be able to run, but is running. The code calls the method of a superclass, but the superclass does not have this method implemented. Specifically, we call super(ShippingMethodView, self).get(request, *args, **kwargs) and my assumption is that we call the superclass of ShippingMethodView which is CheckoutSessionMixin. However, CheckoutSessionMixin does not accept any arguments, nor does it have a get method. Question: Why is the code running without problems when it should throw an error since an extra argument is passed to the superclass and the called method is not defined? Here is the code in question: # file location: /path_to_python_3_install/python3.7/site-packages/oscar/apps/checkout/views.py # source can be seen here: https://django-oscar.readthedocs.io/en/releases-1.6/_modules/oscar/apps/checkout/views.html # imports from django.views import generic ... # The next import is unconventional, but I believe this points to the # CheckoutSessionMixin class which is found at # /path_to_python_3_install/python3.7/site-packages/oscar/apps/checkout/session.py # source: https://django-oscar.readthedocs.io/en/releases-1.6/_modules/oscar/apps/checkout/session.html?highlight=CheckoutSessionMixin CheckoutSessionMixin = get_class('checkout.session', 'CheckoutSessionMixin') ... class ShippingMethodView(CheckoutSessionMixin, generic.FormView): ... def get(self, request, *args, **kwargs): ... # Here, the 'get' method of superclass is called, and self is … -
How to schedule a celery task without blocking django
I have a Django service that register lot of clients and render a payload containing a timer (lets say 800s) after wich the client should be suspended by the service (Change status REGISTERED to SUSPENDED in MongoDB) I'm running celery with rabbitmq as broker as follow : celery/tasks.py ` @app.task(bind=True, name='suspend_nf') def suspend_nf(pk): collection.update_one({'instanceId': str(pk)}, {'$set': {'nfStatus': 'SUSPENDED'}}) ` and calling the task inside django view like : api/views.py ` def put(self, request, pk): now = datetime.datetime.now(tz=pytz.timezone(TIME_ZONE)) timer = now + datetime.timedelta(seconds=response_data["heartBeatTimer"]) suspend_nf.apply_async(eta=timer) response = Response(data=response_data, status=status.HTTP_202_ACCEPTED) response['Location'] = str(request.build_absolute_uri()) ` What am I missing here ? -
Django: how to allow null value
I have the following Django model: from django.db import models class AlertCalendar(models.Model): alert_calendar_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) I want to create an instance of this model where all of the fields except the id are set to null, but when I try to do so I get the following error: { "start_time": [ "This field may not be null." ], "end_time": [ "This field may not be null." ], "start_date": [ "This field may not be null." ], "end_date": [ "This field may not be null." ] } it is also the case when only one of these values is set to null, yet I defined the fields using both null=True and blank=True, so why can't I create this instance? -
How to make a 404 page for a single view?
I have a function-based view that I want if I set the URL to show me a 404 page. I know it can be set in the settings.py with DEBUG = True, but I have serious problems doing so. Now I can make only this page be with Http404? Try this example, but nothing. But I'm missing something, but I do not know what it is. from django.shortcuts import render from polls.models import Poll def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404("Poll does not exist") return render(request, 'polls/detail.html', {'poll': p})``` ```url(r'^reporte_servicio_externo/(?P<pk>[\w{}.-]{20})/$', 'apps.servicios.views.reporte_servicio_externo', name='reporte_servicio_externo'),``` ```def reporte_servicio_externo(request, pk): anuncio = Anuncio.objects.get(pk=get_unhash(pk)) anuncioproyectos = AnuncioProyectos.objects.filter(anuncio=anuncio) cadena_tipo_carga = [] cadena_actividad = [] cadena_trafico = [] cadena_escala = [] cadena_ambito = [] cadena_articulo = [] cadena_tipo_producto = [] cadena_muelles = [] title_meta = 'Reporte Anuncio' title = 'Reporte Anuncio' if anuncio.tipo_carga: tipo_carga = anuncio.tipo_carga.all() for i in tipo_carga: cadena_tipo_carga.append(i.nombre) if anuncio.amarraderos: amarraderos = anuncio.amarraderos.all().values('nombre') for item in amarraderos: cadena_muelles.append(item['nombre']) for item in anuncioproyectos: if item.escala: cadena_escala.append(item.escala) if item.ambito: cadena_ambito.append(item.ambito.nombre) if item.articulo: cadena_articulo.append(item.articulo.nombre) if item.tipo_producto: cadena_tipo_producto.append(item.tipo_producto.nombre) for i in item.actividad.all(): cadena_actividad.append(i.nombre) for i in item.tipo_trafico.all(): cadena_trafico.append(i.nombre) cadena_tipo_carga = ", ".join(list(set(cadena_tipo_carga))) cadena_actividad = ", ".join(list(set(cadena_actividad))) cadena_trafico = ", ".join(list(set(cadena_trafico))) cadena_escala = ", ".join(list(set(cadena_escala))) cadena_ambito … -
Django: authorization rules per row (not per table)
Django has the ability to give access permissions based on users / and / or / groups per table. Here's a sample: I would like to have a more detailed granularity: I would like this principle but for rows of tables. The idea behind is: a user can create something (whatever the table is), and would like to share it (read only / or / read-write) with other users. I thought of a model like this but it doesn't work because it will get rapidly too big. How can I implement this? class AccessRight(models.Model): A_R = 1 A_W = 2 A_RW = A_R | A_W ACCESS_RIGHTS = {A_R: {'long': 'Read', 'short': 'R'}, A_W: {'long': 'Write', 'short': 'W'}, A_RW: {'long': 'Read/Write', 'short': 'RW'}, } table_name = models.CharField(max_length=50, default=None, blank=True, db_index=True) row_id = models.PositiveIntegerField(default=None, blank=True, ) user = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) right = models.IntegerField( choices=[(idx, '{} ({})'.format(desc['long'], desc['short'])) for idx, desc in ACCESS_RIGHTS.items()], default=A_R) -
Integrating a cms with flask on the same server
I am developing a web application using flask, and was looking for a cms with a robust WYSIWYG editor to help non technical users submit content to a custom template on the front end. Is it possible to have a server running flask and a cms like "wagtail" or "django cms" side-by-side? Generally, how is this done on a linux server? I have been using wagtail to add WYSIWYG fields to my templates but do not know how to get it running on the same localhost instance as my flask project. -
How to create all django apps inside a folder?
Here is my project folder structure: - .venv [virtual environment] - apps - budgetApp - >> __init__.py - >> settings.py - >> urls.py - >> wsgi.py - manage.py When I run the following command python manage.py startapp budget it creates a new folder named budget beside the folder budgetApp. But I want to create all my apps folder inside the "apps" folder. -
Why Django 2.2.1 does not call get_absolute_url()
Documentation states that if get_absolute_url() method is defined on model then is used in Django Admin for "VIEW ON SITE" button: One place Django uses get_absolute_url() is in the admin app. If an object defines this method, the object-editing page will have a “View on site” link that will jump you directly to the object’s public view, as given by get_absolute_url(). After some time of debugging I wonder why it is not called. And then I found that it is not even called in the source of Django. https://github.com/django/django/blob/8b3f1c35dd848678225e8634d6880efeeab5e796/django/contrib/admin/options.py#L290 elif self.view_on_site and hasattr(obj, 'get_absolute_url'): # use the ContentType lookup if view_on_site is True return reverse('admin:view_on_site', kwargs={ 'content_type_id': get_content_type_for_model(obj).pk, 'object_id': obj.pk }) Is it bug? -
The django-geoposition map widget is not showing up in the django admin on my production server, but it is working perfectly fine on my test server
The django geoposition widget shows up in admin when I am testing everything on my laptop with the django test server. However, when I put everything onto my production server, there is no map showing up and no labels showing up for the latitude and longitude. Both setups are using django == 2.1.7 and geoposition == 0.3.0. The production server is being served with nginx and gunicorn. I opened the browser inspection window and it turned out that the geoposition.js is being served by django before jQuery is being called. So I tried calling jQuery directly in the geoposition.js file, but there is still no widget. I then revert everything back to it's original stage and I am now including js = (setting.STATIC_URL + 'geoposition/geoposition.js") in a media class in admin.py. This is causing two maps to appear in my test server, but still no map in my production server. I added an if statement so that it doesn't run if jQuery is not loaded, so no jQuery errors on the first geoposition.js being served. I added some console.log() statements to the file so I can see where it is at and it is getting into the main function fine, … -
__init__() missing 1 required positional argument: 'get_response'
I use Django 1.11 and got this error class TenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): set_tenant_schema_for_request(request) response = self.get_response(request) return response I tried to fix that: class TenantMiddleware: def process_response(self, request, response): set_tenant_schema_for_request(request) return response is this a correct equivalent using "new" middleware style? -
django disabled Booleanfield not submitted on POST method
I have a BooleanField that given certain conditions, needs to be disabled. How can I submitting the input even if it's disabled first time form submit second time form submit that ignore disabled booleanfield views.py def test(request): form = InformationForm() test_table = TestTable.objects.get(id=1) result = '' if test_table.status == True: result = True form.fields['agree'].initial = True form.fields['agree'].widget.attrs['disabled'] = True # form.fields['agree'].widget.attrs={'onclick': 'return false','style':'opacity: 0.4 !important'} if request.method == "POST": post_form = InformationForm(request.POST) result = post_form['agree'].value() text = post_form['text'].value() if post_form['agree'].value() == True: t = TestTable.objects.filter(id=1).first() t.status = 1 t.save() post_form.fields['agree'].initial = True post_form.fields['agree'].widget.attrs['disabled'] = True #post_form.fields['agree'].widget.attrs={'onclick': 'return false','style':'opacity: 0.4 !important'} return render(request,'test.html',context={'form':post_form,'result':result,'text':text}) text = form['text'].value() return render(request,'test.html',context={'form':form,'result':result}) every time disabled BooleanField returns false, even it selected i am also referred this link forms.py class InformationForm(forms.Form): text = forms.CharField(max_length=50) agree = forms.BooleanField(required=False) def clean(self): agree = self.cleaned_data.get('agree') text = self.cleaned_data.get('text') #def clean_agree(self): # if self.instance and self.instance.pk: # return self.instance.agree # else: # return self.cleaned_data.get('agree') -
OperationalError at /weekstaat/
I want to use 'organisatie' from the contract model in weekstaat index.html. When I import contract in weekstaat I get this error: OperationalError at /weekstaat/ no such column: weekstaat_weekstaat.contract_id. How do i fix this error? here is some code: weekstaat/model.py this is the model of weekstaat from django.db import models from django.contrib.auth.models import User from datetime import datetime, date from contract.models import Contract STATUS_CHOICES = ( ('actief', 'actief'), ('concept', 'concept'), ('non-actief', 'non-actief'), ) class Jaar(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) jaar = models.CharField(null=False, blank=False, default=str(datetime.now().year), max_length=4) def __str__(self): return str(self.jaar) class Week(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) def __str__(self): return str(self.id) class status(models.Model): id = models.AutoField(primary_key=True) status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',) def __str__(self): return self.status class Weekstaat(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='Niet ingediend',) jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE) week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE) contract = models.ForeignKey(Contract, null=True, blank=False, default=1,on_delete=models.CASCADE) werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE) maandag = models.FloatField(null=True, blank=True, default=0) dinsdag = models.FloatField(null=True, blank=True, default=0) woensdag = models.FloatField(null=True, blank=True, default=0) donderdag = models.FloatField(null=True, blank=True, default=0) vrijdag = models.FloatField(null=True, blank=True, default=0) zaterdag = models.FloatField(null=True, blank=True, default=0) zondag = models.FloatField(null=True, blank=True, default=0) def __str__(self): return str(self.jaar) + ' week ' + str(self.week) + … -
Perform query in django against another table, but its not finding the table
I am trying to perform a query via a join. My models.py looks like: class TSFH(models.Model): sB = models.DateTimeField(null=True) sE = models.DateTimeField(null=True) FKToUser = models.ForeignKey(User,default=None, on_delete=models.PROTECT) class Tld(models.Model): dNm = models.CharField(verbose_name="",max_length=40,unique=True) FKToUser = models.ForeignKey('auth.user', default=None, on_delete=models.PROTECT) class TSF(models.Model): FKToT = models.ForeignKey('T', on_delete=models.PROTECT) FKToTSFH = models.ForeignKey('TSFH', on_delete=models.PROTECT, null=True, blank=True) views.py enteredd = request.GET.get('d', '') query=TSFH.objects.filter(FKToT__dNm=enteredd,FKToUser=request.user,sE__isnull=False) return render(request, 'view.html', {'q':q}) templates/file.html {% if q %} {% for res in q %} <li><span>{{ res.sE }}</span></li> {% endfor %} {% else %} {% endif %} When I view this all it complains about: Cannot resolve keyword 'FKToT' into field In plain sql I'm looking to perform the following just with dNm search directly from the enteredd instead of a hardcoded value of 123.145.23.1 as shown below: SELECT sE FROM tsfh, tsf, t where tsfh.id=tsf.FKTotsfh_id and t.id=tsf.FKToT_id and tsfh.sE is not null and t.dNm='123.145.23.1'; How can I keep these existing checks in the query but include this FKToT__dNm=enteredd somehow? Thank you very much. -
Django signals: conflicts with models inheritining from the same class
I encountered a strange behavior while applying a signal to a new model, I'm not sure to understand what is wrong but it seems related with the fact that I used abstract classes. The models (simplified) Basically, I have Article, Photo (inheriting from Post) class Post(models.Model): class Meta: abstract = True some_field = models.Something() class Article(Post): category = models.ForeignKey(Article_category, null=True, on_delete=models.SET_NULL) some_field = models.Something() class Photo(Post): category = models.ForeignKey(Photo_category, null=True, on_delete=models.SET_NULL) some_field = models.Something() and their respective Categories class Category(models.Model): class Meta: abstract = True parent = models.ForeignKey('self', null=True, blank=True, related_name='nested_category', on_delete=models.SET_NULL) name = models.CharField(max_length=50) count = models.PositiveSmallIntegerField(default=0, editable=False) class Article_category(Category): @classmethod def load(cls): cache.set('{}'.format(cls.__name__), cls.objects.all()) class Photo_category(Category): @classmethod def load(cls): cache.set('{}'.format(cls.__name__), cls.objects.all()) The signal A straighforward incremental counter. Every time an article/photo is created, it's corresponding category count is updated and the entire model is saved in the cache (for templating purposes) from django.db.models import F @receiver(post_save, sender=Article) ----> here comes trouble @receiver(post_save, sender=Photo) def add_one_to_count(sender, instance, **kwargs): cat = type(instance.category).objects.get(name=instance.category) cat.count = F('count')+1 cat.save() cache.set('{}_category'.format(sender.__name__), type(instance.category).objects.all()) The problem What you saw above works like a charm for @receiver(post_save, sender=Photo) but when I add @receiver(post_save, sender=Article), DB initialization with fixture fails and I only get emptyset tables (mariaDB). This … -
MultiValueDictKeyError when i use select form-control in python django with bootstrap
When I try to use a select form-control in my template for input some selected value to the views, returns the MultiValueDictKeyError, but when I try use the same input without the select fields works withou a error. code with select and returns MultiValueDictKeyError: {% extends 'base.html' %} {% block main %} Edit <form method="POST"> {% csrf_token %} <label for="descricao">Data Inicial:</label> <input id="descricao" type="text" name="descricao" value="{{ descricao }}" class="form_datetime" /><br> <script type="text/javascript"> $(".form_datetime").datetimepicker({ format: '03/01/19 08:00' }); </script> <label for="descricao2">Data Final:</label> <input id="descricao2" type="text" name="descricao2" value="{{ descricao2 }}" class="form_datetime" /><br> <script type="text/javascript"> $(".form_datetime").datetimepicker({ format: '03/01/19 09:00' }); </script> <label for="inputUnidades">Selecione unidade</label> <select class="form-control" id="inputUnidades"> {% for item_unidade in unidade2 %} <option>{{ item_unidade }}</option> {% endfor %} </select> <input type="submit"> {% if descricao != None %} <br><br> <p> Data Inicial: {{ descricao }}<br> Data Final: {{ descricao2 }}<br> Unidade:{{ item_unidade }} Tabela:{{ passar|safe }} </p> {% endif %} <a href="{% url 'graficos' %}" class="btn btn-primary">Grafico2</a> <a href="{% url 'tela_graficos' %}" class="btn btn-primary">Grafico</a> </form> {% endblock %} Code that does not return error, I just change this part: <label for="inputUnidades">Selecione unidade</label> <select class="form-control" id="inputUnidades"> {% for item_unidade in unidade2 %} <option>{{ item_unidade }}</option> {% endfor %} </select> For this and work, I … -
query string, changes required in urls.py and view
A basic django question, but stumping me. I have an existing view for an endpoint. http://localhost:8001/v1/subject - which returns all subjects from the subject model. I want to serve a new endpoint... http://localhost:8001/v1/subject?owner_ids=60,61,62 What would be the changes required in the "urls.py" definition and ''' def query_set ''' method in views/subject.py, I have added the method but it's not working as intended. Here's the urls.py definition, any changes required to accommodate a query string? router.register(r'subjects', views.SubjectsViewSet) Should I do something like this? url(r'^v1/subjects/', views.SubjectViewSet.as_view({'get': 'list'})) If its the above, what changes maybe needed to make it work? Also, here's my views/subjects.py file...the logic in def get_queryset may work, but how do I wire the urls.py entry so that the querystring localhost:8001/v1/subject?owner_ids=60,61,62 is served? class SubjectViewSet(Subject.get_viewset()): pagination_class = SubjectPagination def get_queryset(self, *args, **kwargs): owner_id_list = self.request.GET['owner_ids'].split(',') owner_id_list_integer = [] for i in owner_id_list: owner_id_list_integer.append(int(i)) queryset = Subject.objects.all() if owner_id_list is None: return None else: return queryset.filter(organization__in=owner_id_list) SubjectUserRoleViewSet = Subject.get_by_user_role_viewset( SubjectViewSet, GroupRoleMap, Role) -
Access create method of nested serializer
I have a parent serializer that contains two child serializers. The child serializers are re-used and they have logic to update and create. My request data looks like this, { 'key1': [ {'keyA': value}, {'keyA': value} ] 'key2': [ {'keyB': value}, {'keyB': value} ] } These are the serializers that I have written, class ParentSerializer(serializers.Serializer): key1 = Key1Serializer(many=True) key2 = Key2Serializer(many=True) class Meta: ... Child serializers, class Key1Serializer(serializers.ModelSerializer): keyA = serializers.CharField(required=True) class Meta: model = Key1 fields = ('keyA') list_serializer_class = MultipleKey1Serializer class Key1Serializer(serializers.ModelSerializer): keyB = serializers.CharField(required=True) class Meta: model = Key2 fields = ('keyB') list_serializer_class = MultipleKey2Serializer List serializers, class MultipleKey1Serializer(serializers.ListSerializer): def update(self, extra_params): for el in self.validated_data: ... #update logic class MultipleKey2Serializer(serializers.ListSerializer): def create(self, extra_params): for el in self.validated_data: ... #create logic This is how I initialize the parent serializer serializer = ParentSerializer(data=request_data) serializer.is_valid() # <- works perfectly, validates all the fields So the nested serializers validate the data perfectly. Now all I want to do is call the update method inside the Key1Serializer and create method inside the Key2Serializer. I tried calling it the lazy way, serializer.data['key2'].create(params) But that's not the right way to do it. Can anyone help me out? -
openpyxl : I can't open excel file with password
I am a student. I want to read protected excel file with openpyxl, but I can't. This is my code. wb = load_workbook(file_path) # Error returned in this line. wb.security.workbook_password = 'password' ws = wb.active This is my error message Traceback (most recent call last): File "D:\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "D:\env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\env\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "D:\env\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "D:\manager\views_payment.py", line 32, in post self.read_excel(tmp.payment_excel) File "D:\manager\views_payment.py", line 20, in read_excel wb = load_workbook(file_path) File "D:\env\lib\site-packages\openpyxl\reader\excel.py", line 171, in load_workbook archive = _validate_archive(filename) File "D:\env\lib\site-packages\openpyxl\reader\excel.py", line 121, in _validate_archive archive = ZipFile(f, 'r', ZIP_DEFLATED) File "c:\python36\Lib\zipfile.py", line 1100, in __init__ self._RealGetContents() File "c:\python36\Lib\zipfile.py", line 1168, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file What is the problem? -
How solve the problem with clean function in django
I'm building a booking website, where customer can book an appointment on a day of his/her choice and the time of appointment is selected from the available slots with the help of drop-down menu. The problem is if a time slot has already been booked by someone it should not be available and an error message should be shown to the customer. I have written a clean function to perform the check. It gives and error as follows :- No booking on 2019-06-08 Internal Server Error: / Traceback (most recent call last): File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/views/generic/edit.py", line 172, in post return super().post(request, *args, **kwargs) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/forms/forms.py", line 383, in full_clean self._post_clean() File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/forms/models.py", line 403, in _post_clean self.instance.full_clean(exclude=exclude, validate_unique=False) File "/home/gireesh/PycharmProjects/astrobookinenv/lib/python3.6/site-packages/django/db/models/base.py", line 1181, in full_clean self.clean_fields(exclude=exclude) …