Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django View, foreign key field is killing performance
MyObjects definition: class MyObjects(models.Model): field_a = models.TextField() field_b = models.TextField() ...more irrelevant text/int fields foreign_key_field = models.ForeignKey(AnotherModel, null=True, on_delete=models.SET_NULL) View definition: @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) ...irrelevant logic my_dict = defaultdict(int) for my_obj in objs: ...bunch of irrelevant logic my_dict[str(my_obj.foreign_key_field)] += 1 ...bunch of irrelevant logic return Response(my_dict, status=status.HTTP_200_OK) I do some calculations in my view that are irrelevant and my view takes around 3 seconds for 5000 objects if my_dict[str(my_obj.foreign_key_field)] += 1 is commented out. However, when that line uncommented, my view takes 20seconds. It must be because this field is a foreign key field as none of my other fields are foreign keys. That specific line is the only line referencing that field. How am I able to improve performance on this? I am surprised that just adding this line decreases my performance by that much, as objects is only around 5k and the foreign key table is around 50 objects. No other operations are touching this dictionary because that specific line, so it's not a cascading affect. If I comment out all logic besides that specific line @api_view(["GET"]) @permission_classes([IsAuthenticated]) def my_endpoint(request): objs = MyObjects.objects.filter(is_active=True) my_dict = defaultdict(int) for my_obj in objs: my_dict[str(my_obj.foreign_key_field)] += 1 return … -
Django not loading fixtures when there is post_save signal
I am testing a registration function in my Django app. When users register, a default user_type is designated to the user. I am using a post_save signal to process this. I have a Profile model to be connected with the User and under the Profile model, is a field user_type which is from another model. class UserType(models.Model): name = models.CharField(max_length=50, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.ForeignKey(UserType, on_delete=models.SET_NULL, null=True, blank=True) To automatically assign a default user_type, I have a signal: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: user_type = UserType.objects.get(pk=1) Profile.objects.create( user=instance, user_type=user_type) I made a fixture of my User, Profile, and UserType models and in my APITestCase, I placed the fixture. class TestUserManagement(APITestCase): fixtures = ['fixtures/initial'] When I run the test, the fixtures does not seem to load to the test database. File "/usr/src/app/fixtures/signals.py", line 15, in create_user_profile user_type = UserType.objects.get(pk=1) ... {model}.UserType.DoesNotExist: Problem installing fixture '/usr/src/app/fixtures/initial.json': UserType matching query does not exist. -
Django Python HTMX - Pagination is not working on multiple tables in one template
I try to build a search which shows four tables with four different models. On that multiple tables I have a problem with my infinite scroll. The output doesn't pay attention on the "paginate_by=5" variable so it just show every result. In addition to that, the pagination only use the first item of the get_template_names. So when I scroll down, it fills the tables with the order table. My views.py: **class searchView(ListView): ordering = ['-id'] template_name = 'search_items.html' paginate_by = 5 model = Rooms def get_template_names(self): if self.request.htmx: return ['single-rows/search_orders_single_row.html', 'single-rows/search_products_single_row.html', 'single-rows/search_rooms_single_row.html', 'single-rows/search_suppliers_single_row.html'] return 'search_items.html' def get_context_data(self, **kwargs): searchedItem = self.request.GET.get('searchedItem',default="") context = super(searchView, self).get_context_data(**kwargs) context['all_orders'] = Orders.objects.all() context['all_products'] = Products.objects.all() context['all_suppliers'] = Suppliers.objects.all() context['rooms'] = Rooms.objects.filter(Q(room__contains=searchedItem) | Q(cabinetNumber__contains=searchedItem) | Q(shelf__contains=searchedItem)) #filtered_rooms get the results from the search in the database context['products'] = Products.objects.filter(Q(designation__contains=searchedItem) | Q(category__contains=searchedItem)) context['orders'] = Orders.objects.filter(Q(product__contains=searchedItem) | Q(supplier__contains=searchedItem)) context['suppliers'] = Suppliers.objects.filter(Q(s_name__contains = searchedItem)) context['searchedItem'] = searchedItem return context** my search-template: <div class="col-6 col-s-6 table"> {% if searchedItem %} <h1>Suchergebnisse für: {{ searchedItem }} </h1> {% if rooms or products or orders or suppliers %} {% if rooms %} <p>Suchergebnisse in "Räume"</p> <table class="content"> <thead> <tr> <th>Raum</th> <th>Schranknummer</th> <th>Regalfach</th> <th>Aktion</th> </tr> </thead> <tbody> {% include 'single-rows/search_rooms_single_row.html' %} </tbody> … -
Managing python path and version for Django using mod_wsgi
I've joined the unhappy ranks of people who have tried to set up a Django website served by Apache (on Amazon-linux EC2). I have successfully configured Apache and compiled mod_wsgi against Python3.4 using a virtualenv (at /home/ec2-user/web-dev) largely following instructions at https://gist.github.com/tanuka72/79ae58b16be4ac3fafe0 and the mod_wsgi docs). However, I get an Internal Server Error when loading the Django test app. Looking at the logs, it seems that multiple versions of Python are somehow being called during the processing (see the change from /home/ec2-user/web-dev/lib64/python3.4 to /usr/lib64/python3.7). Also it seems that mod_wsgi cannot be imported (whilst 'import mod_wsgi' works fine from a python prompt in the ec2 terminal). [Thu Jan 19 15:19:27.329376 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Failed to exec Python script file '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.329445 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] mod_wsgi (pid=9955): Exception occurred processing WSGI script '/var/www/test/test_site/test_site/wsgi.py'. [Thu Jan 19 15:19:27.330049 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] Traceback (most recent call last): [Thu Jan 19 15:19:27.330088 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/var/www/test/test_site/test_site/wsgi.py", line 25, in <module> [Thu Jan 19 15:19:27.330093 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] application = get_wsgi_application() [Thu Jan 19 15:19:27.330108 2023] [wsgi:error] [pid 9955] [remote 81.109.251.90:61582] File "/home/ec2-user/web-dev/lib64/python3.4/site-packages/django/core/wsgi.py", line 12, … -
Django Rest API complain about swagger version
We are using DJango rest framework to make api. We added swagger page, but its complain about swagger version. Unable to render this definition The provided definition does not specify a valid version field. Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0). I was following documentation https://www.django-rest-framework.org/topics/documenting-your-api/#a-minimal-example-with-swagger-ui Below are files. urls.py from django.urls import path urlpatterns = [ ... ... path("openapi", get_schema_view( title="My api", description="API for me", version="1.0.0" ), name="openapi-schema"), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui') ] templates/swagger-ui.html <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> I think, its complaining about version: 1.0.0 mentioned in openapi schema view. But need to sure, if something else is not causing this issue. -
Is there a way to show only some model fields?
I have a model with field instances and have views. Can i make so that when you redirect to to main page you can see only ID, title, deadline, done? But when you redirect to the detail page you can see all the model fields. models.py: class Task(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.TextField() deadline = models.DateTimeField() done = models.BooleanField() views.py : lass TaskList(generics.ListCreateAPIView): # permission_classes = (IsAuthorOrReadOnly,) queryset = Task.objects.all() serializer_class = TaskSerializer class TaskDetail(generics.RetrieveUpdateDestroyAPIView): # permission_classes = (IsAuthorOrReadOnly,) queryset = Task.objects.all() serializer_class = TaskSerializer serializers.py: class TaskSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "title", "body", "author", "deadline", "done", ) model = Task urls.py: urlpatterns = [ path("<int:pk>/", TaskDetail.as_view(), name="task_detail"), path("", TaskList.as_view(), name="task_list"), ] Please add a link to useful reading materials -
'AgencyRegistration' object has no attribute 'get'
I'm trying to create an endpoint using Django REST framework, but when I'm trying to get the data from the endpoint I'm getting the following error: AttributeError: 'AgencyRegistration' object has no attribute 'get'. Here's my code models.py `class AgencyRegistration(models.Model): agency_name = models.CharField(max_length=200) tax_id_number = models.IntegerField(max_length=12) address_street = models.CharField(max_length=220) city = models.CharField(max_length=50) county = models.CharField(max_length=50) state = models.CharField(max_length=100) zip_code = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) title = models.CharField(max_length=200) email = models.CharField(max_length=200) phone = models.CharField(max_length=50) children_amount = models.CharField(max_length=100) age_range = models.CharField(max_length=100) program_benefit = models.CharField(max_length=200) organization_type = models.CharField(max_length=200) how_did_you_hear = models.CharField(max_length=200) def __str__(self): return self.agency_name` views.py `def agency_registration(request): agency_data = AgencyRegistration.objects.all() serializer = AgencyRegistrationSerializer(agency_data, many=True) return render(JsonResponse(serializer.data, safe=False))` serializers.py `class AgencyRegistrationSerializer(serializers.ModelSerializer): class Meta: model = AgencyRegistration fields = [ 'id', 'agency_name', 'tax_id_number', 'address_street', 'city', 'county', 'state', 'zip_code', 'first_name', 'last_name', 'title', 'email', 'phone', 'children_amount', 'age_range', 'program_benefit', 'organization_type', 'how_did_you_hear' ]` urls.py `urlpatterns = [ path('agency-registration/', views.AgencyRegistration), ]` -
django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple after upgrading Django
Hi I upgrade the django and after that I'm getting this error django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple. but in my setting.py file the ALLOWED_HOSTS is already in the list config.py DJANGO_CONFIG = { 'secret_key': 'fadfas-------', 'debug': False, 'admin_module': True, 'allowed_hosts': '[\'*\']', 'server_host': 'http://127.0.0.1:8000', } setting.py ALLOWED_HOSTS = DJANGO_CONFIG['allowed_hosts'] -
How to integrate third party api's in Django?
I have a project that works as a single login and I must integrate other apis so that they can log in to this api and return to their logged-in api of origin. Any help or information on the subject will be appreciated. -
How to insert data inside the html tag by fetching from django database?
is it possible in django to fetch data from database and insert it inside the html tag. I've created a below model and I want to put its data into respective html tags. class Metadata(models.Model): meta_name = models.CharField() meta_desc = models.TextField() meta_key = models.TextField() views.py def func(request): desc = Metadata.objects.get(meta_desc="some text") desc_k = Metadata.objects.get(meta_key="some text") return render(request, "results.html", {'desc':desc,'desc_k':desc_k}) I want to fetch this meta_desc and meta_key data and insert it into below HTML tags respective to its matching meta_name. I tried above function but its not working, I guess either its not possible to do that or i'm doing it wrong. results.html <meta name="description" content=" {{ desc.meta_desc }}"> <meta name="keywords" content="{{ desc_k.meta_key }}"> Please suggest me if there is any other way to do this? Thanks -
Using django form wizard with allauth
Currently my user sign up process is implemented with allauth. Does anyone have any experience of how to make this a multipage process e.g. with form wizard from formtools? forms.py (stored at users/forms.py) class UserCreationForm1(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( { "duplicate_username": _( "This username has already been taken." ) } ) username = CharField(label='User Name', widget=TextInput(attrs={'placeholder': 'User Name'}) ) class Meta(forms.UserCreationForm.Meta): model = User fields = ['username', 'email', 'title', 'first_name', 'last_name', 'country', ] field_order = ['username', 'email', 'title', 'first_name', 'last_name', 'country', ] def clean_username(self): username = self.cleaned_data["username"] if self.instance.username == username: return username try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) class UserCreationForm2(forms.UserCreationForm): class Meta(forms.UserCreationForm.Meta): model = User fields = ['occupation', 'password1', 'password2', 'terms'] field_order = ['occupation', 'password1', 'password2', 'terms'] def clean_terms(self): is_filled = self.cleaned_data['terms'] if not is_filled: raise forms.ValidationError('This field is required') return is_filled For the views.py i then have SIGNUP_FORMS = [('0', UserCreationForm), ('1', UserCreationForm2)] TEMPLATES = {'0': 'account/signup_1.html', '1': 'account/signup_2.html'} class SignupWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): for form in form_list: if isinstance(form, UserCreationForm): print('form1') user = form.save(self.request) elif isinstance(form, UserCreationForm2): userprofile = form.save(commit=False) user = self.request.user userprofile.user = user userprofile.save() print('form2') return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) What I find though is that after completing the … -
How to get class attributes in HTML
I have a few forms in my forms variable, which I took from my DB. views.py: def settings(request): new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) MY HTML: <h3>{{ error }}</h3> {% for form in forms %} <form method="POST" id="{{form.name.name}}">{% csrf_token %}</form> {% endfor %} <form method="POST" id="new-form"> {% csrf_token %}</form> {% for form in forms %} <tr> <td>{{ form.name }}</td> <td>{{ form.token }}</td> <td><button class="btn btn-lg btn-success w-100">Save</button></td> </tr> {% endfor %} <tr> <td><input class="form-control" placeholder="Name" form="new-form"></td> <td><input class="form-control" placeholder="API-token" form="new-form"></td> <td><button class="btn btn-lg btn-success w-100" form="new-form">Add</button></td> </tr> I am making a kind of editable grid and using a table for my layout ( so I cannot put a form direct to a row). So I am making the forms separately with the new HTML 5 form tag. But I cannot take out the name(HTML attr on my inputs) which == the name field in the DB. So I could make different forms for every single row in my database. Can you help me? I was thinking about setting the id of the form from my forms object but it makes the same forms for every row. -
Custom display of cell value which depends on other cell's value
Say I have a column with multiple potential value-ranges (values could range from 1-10, 1-100, etc.). Now, I want to display the upper 20% of records within this column with 5x :thumbsup: emoji's, the second 20% with 4x :thumbsup: emoji's, etc. Any idea how to achieve this with django-tables2? -
How to take the names of the Django model table (queryset) columns into a list, template or other variable?
Good day! I have a table model in Django model. With named field column names. I'm going to post this model to a table in a template. But I have 8 .. 9 columns. I would like to not specify the names of the table columns in the header manually. And so that it is filled from the list, as is most often the case in the body of the table. How it is possible to pull out to take from model or request in the list of a name of columns of fields? header from queryset ("verbose_name") or model ? template <table> <tr>{% for item in header %}<th>{{ item }}</th>{% endfor %}</tr> {% for row in rows %} <tr>{% for cell in row %}<td>{{ cell }}</td>{% endfor %}</tr> {% endfor %} </table> Model class Model_1(models.Model): name1 = models.ForeignKey(Model_2, on_delete=models.CASCADE, verbose_name="Name_0") name2 = models.ForeignKey(Model_3, on_delete=models.CASCADE, verbose_name="Name1") date3 = models.DateField(verbose_name="Name2") -
How to get url parameters as a list in Django?
I want to get url parameters as list in django. Say for example, I will add each parameters to url as; mydomain.com/param1/param2/param3/.../paramx Where each param may be existed or not. For example a link may be; mydomain.com/param1/param3/param4/... So my question is, How can I get list of params in Django? I tried handling parameters manually but since they are seperated it doesn't work as expected. -
Django-allauth | I migrate ok the github project but all the time say "You have 26 unapplied migration(s)"
I want to try django-allauth. I clone django-allauth github project (only this), but later to migrate ok, when i execute "python manage.py runserver" this says: You have 26 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): account, admin, auth, contenttypes, openid, sessions, sites, socialaccount. Run 'python manage.py migrate' to apply them. I don´t understand Example: Thank you! -
Why is my function not returning the object by its slug in the url?
'edit_holiday() got an unexpected keyword argument 'slug' I would like that when clicking on the object, its slug is returned in the url, which I set automatically in the models, to be identical to the name. Function in models.py: @receiver (post_save, sender = Holiday) def insert_slug(sender, instance, **kwargs): if not instance.slug: instance.slug = slugify(instance.HolidayReason) return instance.save() My views.py to visualize object: def edit_holiday(request, pk): if request.method == 'GET': objeto = Holiday.objects.filter(slug=pk).first() if objeto is None: return redirect(reverse('lista_holiday')) holiday_list = Holiday.objects.get(slug=pk) form = HolidayForm(instance=objeto) form_holidaycenter_factory = inlineformset_factory(Holiday, HolidayCenter, form=HolidayCenterForm) form_holidayloc_factory = inlineformset_factory(Holiday, HolidayLoc, form=HolidayLocForm) form_holidaycenter = form_holidaycenter_factory(instance=objeto, prefix='holidaycenter') form_holidayloc = form_holidayloc_factory(instance=objeto, prefix='holidayloc') context = { 'form': form, 'form_holidaycenter ': form_holidaycenter, 'form_holidayloc ': form_holidayloc , 'holiday_list ': feriado_list, } return render(request, '../templates/feriado/form_.html', context) elif request.method == 'POST': objeto = Holiday.objects.filter(slug=pk).first() if objeto is None: return redirect(reverse('lista_holiday')) holiday_list = Holiday.objects.get(slug=pk) form = HolidayForm(request.POST, instance=objeto) form_holidaycenter_factory = inlineformset_factory(Holiday, HolidayCenter, form=HolidayCenterForm) form_holidayloc_factory = inlineformset_factory(Holiday, HolidayLoc, form=HolidayLocForm) form_holidaycenter = form_holidaycenter_factory(request.POST, instance=objeto, prefix='holidaycenter') form_holidayloc = form_holidayloc_factory(instance=objeto, prefix='holidayloc') if form.is_valid() and form_holidayloc .is_valid() and form_holidaycenter.is_valid(): holiday= form.save() form_holidayloc.instance = holiday form_holidaycenter.instance = holiday form_holidayloc.save() form_holidaycenter.save() messages.success(request, "Feriado adicionado com sucesso!") return redirect(reverse('lista_holiday')) else: context = { 'form': form, 'form_holidaycenter ': form_holidaycenter, 'form_holidayloc ': form_holidayloc , 'holiday_list ': feriado_list, … -
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 18 for SQL Server]
I'm trying to convert a DataFrame columns type and I'm receiving this error when I try to insert the data into SQL SERVER: pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 22 (""): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision. (8023) (SQLExecDirectW)') These are my code and database schema: with pyodbc.connect(sql_server) as conn: cursor = conn.cursor() df_bcb = pd.DataFrame(newest_file) df_bcb['database'] = df_bcb['database'].astype(str, errors='ignore') df_bcb['codigoIdentificadorBacen'] = df_bcb['database'].astype(str, errors='ignore') df_bcb['codigoSisbacen'] = df_bcb['codigoSisbacen'].astype(int, errors='ignore') df_bcb['siglaISO3digitos'] = df_bcb['siglaISO3digitos'].astype(str, errors='ignore') df_bcb['nomeDoPais'] = df_bcb['nomeDoPais'].astype(str, errors='ignore') df_bcb['nomeDaUnidadeFederativa'] = df_bcb['nomeDaUnidadeFederativa'].astype(str, errors='ignore') df_bcb['codigoDoMunicipioNoIBGE'] = df_bcb['codigoDoMunicipioNoIBGE'].astype(int, errors='ignore') df_bcb['nomeDoMunicipio'] = df_bcb['nomeDoMunicipio'].astype(str, errors='ignore') df_bcb['nomeEntidadeInteresse'] = df_bcb['nomeEntidadeInteresse'].astype(str, errors='ignore') df_bcb['nomeEntidadeInteresseNaoFormatado'] = df_bcb['nomeEntidadeInteresseNaoFormatado'].astype(str, errors='ignore') df_bcb['codigoCNPJ14'] = df_bcb['codigoCNPJ14'].astype(str, errors='ignore') df_bcb['codigoCNPJ8'] = df_bcb['codigoCNPJ8'].astype(str, errors='ignore') df_bcb['codigoTipoSituacaoPessoaJuridica'] = df_bcb['codigoTipoSituacaoPessoaJuridica'].astype(int, errors='ignore') df_bcb['descricaoTipoSituacaoPessoaJuridica'] = df_bcb['descricaoTipoSituacaoPessoaJuridica'].astype(str, errors='ignore') df_bcb['codigoTipoEntidadeSupervisionada'] = df_bcb['codigoTipoEntidadeSupervisionada'].astype(int, errors='ignore') df_bcb['descricaoTipoEntidadeSupervisionada'] = df_bcb['descricaoTipoEntidadeSupervisionada'].astype(str, errors='ignore') df_bcb['codigoNaturezaJuridica'] = df_bcb['codigoNaturezaJuridica'].astype(int, errors='ignore') df_bcb['descricaoNaturezaJuridica'] = df_bcb['descricaoNaturezaJuridica'].astype(str, errors='ignore') df_bcb['codigoEsferaPublica'] = df_bcb['codigoEsferaPublica'].astype(int, errors='ignore') df_bcb['nomeReduzido'] = df_bcb['nomeReduzido'].astype(str, errors='ignore') df_bcb['siglaDaPessoaJuridica'] = df_bcb['siglaDaPessoaJuridica'].astype(str, errors='ignore') df_bcb['nomeFantasia'] = df_bcb['nomeFantasia'].astype(str, errors='ignore') df_bcb['indicadorEsferaPublica'] = df_bcb['indicadorEsferaPublica'].astype(int, errors='ignore') df_bcb['header_id'] = df_bcb['header_id'].astype(int, errors='ignore') print(df_bcb) … -
How to restrict so that the author of the post can only see and edit his posts
In this code only the author of the post can edit his post, but how to also make so that the author of the post can see only his posts? from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user Please add a link to useful reading materials -
AttributeError: 'Serializer' object has no attribute '_meta'
i have created this serializer to validate on the presence of a record with these column combination` class CampaignServicesValidation(serializers.Serializer): campaign_id = serializers.IntegerField(required=True) service_id = serializers.IntegerField(required=True) def validate(self, data): try: campaign_service = CampaignServices.objects.get(campaign_id=data['campaign_id'], service_id=data['service_id']) print("found"+str(campaign_service.id)) except Exception: raise serializers.ValidationError(detail='Campaign Service does not exist') return campaign_service and it is called in my viewSet like this: campaign_service = CampaignServicesValidation(data={'campaign_id': request.data['campaign_id'], 'service_id': pk}) if not campaign_service.is_valid(): return RestResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, serializer_error=campaign_service.errors) when the combination is not found it raises an exception and works well, but when it passes validation and enters the is_valid() function in the if condition it produces this error Traceback (most recent call last): File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\RightsHero\collector-management\collectors_management\views.py", line 157, in update_campaign_service_frequency serializer.save() File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 207, in save self.instance = self.update(self.instance, validated_data) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 993, in update info = … -
How to access nested fields in JSONField in the HTML template (Django)
I have a user model with a field called data containing nested data, e.g for one user that could be data = { "2020":{"payment_date":"today","amount":600}, "2021":{"payment_date":"","amount":800} } the model also has a name field. In my HTML I can access name and data but I struggle getting "deeper" into data to extract amount from 2020 and 2021. I would assume I could do {{user.data.2020}} but that does not work. Doing {{user.data}} does indeed show the "remaining data". Right now I have tried <div class="media-body"> <table> <tr> <th>Name</th> <th>2020</th> <th>2021</th> </tr> {% for user in users%} <tr> <td>{{user.name}}</td> # works <td>{{user.data.2020.amount}}</td> <td>{{user.data.2021.amount}}</td> </tr> {% endfor %} </table> </div> but that does not work -
Django Wagtail dynamically create form without new model
How would I allow my primary user to dynamically create forms they can issue to their end clients. Each of my primary users has their own unique information they would like to collect that I do not know before hand. I would like to avoid creating new models in code for their dynamic needs and then having to migrate the models. I came across this which had an interesting response but it starts with disclaimer The flexibility of Python and Django allow developers to dynamically create models to store and access data using Django’s ORM. But you need to be careful if you go down this road, especially if your models are set to change at runtime. This documentation will cover a number of things to consider when making use of runtime dynamic models. Which leads me to believe a lot can go wrong. However because I'm using wagtail I believe there is probably a way to use StructBlocks & StreamFields to accomplish it. Any guidance would be helpful. -
How to install and point to Python GDAL library on App Engine (Standard)?
Django is firing this error locally: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Here's an example of how the path should look in settings: GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300' Now this is an easy, well documented fix locally, but we're quite far along with App Engine Standard on GCP (Python 3). There's a GDAL package that seems to be installable by pip but it also seems there's also native extensions/headers required. How can I: how do I install GDAL in a specific directory in app engine? where do I know where App Engine will put it/put it somewhere myself? Note: Willing to do any kind of workaround like host it remotely (probably not allowed) or even try a different library for lat-long distance filtering. Though for the latter it must accept and return a queryset via queryset.filter() in Django so I doubt there are other Django options. Perhaps running PSQL query directly on a dataset? The only solution I found and examined were vendor packages and lib. But it looks like this is no longer an option (https://cloud.google.com/appengine/docs/legacy/standard/python/tools/using-libraries-python-27#vendoring) for … -
Groupby and count number of children where each child has more than a specific number of children itself
I have three models, Business, Employee, and Client, where each business can have many employees and each employee can have many clients: class Business(models.Model): name = models.CharField(max_length=128) menu = models.CharField(max_length=128, default="") slogan = models.CharField(max_length=128, default="") slug = models.CharField(max_length=128, default="") class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) business = models.ForeignKey( Business, related_name="employees", on_delete=models.CASCADE ) class Client(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) employee = models.ForeignKey( Employee, related_name="clients", on_delete=models.CASCADE ) A sample data: Business.objects.create(name="first company") Business.objects.create(name="second company") Business.objects.create(name="third company") Employee.objects.create(first_name="f1", last_name="l1", business_id=1) Employee.objects.create(first_name="f2", last_name="l2", business_id=1) Employee.objects.create(first_name="f3", last_name="l3", business_id=2) Employee.objects.create(first_name="f4", last_name="l4", business_id=3) Employee.objects.create(first_name="f5", last_name="l5", business_id=3) Employee.objects.create(first_name="f6", last_name="l6", business_id=3) Client.objects.create(first_name="cf1", last_name="cl1", employee_id=1) Client.objects.create(first_name="cf2", last_name="cl2", employee_id=1) Client.objects.create(first_name="cf3", last_name="cl3", employee_id=2) Client.objects.create(first_name="cf4", last_name="cl4", employee_id=2) Client.objects.create(first_name="cf5", last_name="cl5", employee_id=3) Client.objects.create(first_name="cf6", last_name="cl6", employee_id=3) Client.objects.create(first_name="cf7", last_name="cl7", employee_id=4) Client.objects.create(first_name="cf8", last_name="cl8", employee_id=5) Client.objects.create(first_name="cf9", last_name="cl9", employee_id=6) If I wanted to see how many employees each business has, I could run a query like this: Business.objects.annotate( employee_count=Count("employees") ).values( "name", "employee_count" ).order_by("-employee_count") <QuerySet [ {'name': 'third company', 'employee_count': 3}, {'name': 'first company', 'employee_count': 2}, {'name': 'second company', 'employee_count': 1} ]> Similarly, if I wanted to see how many clients each employee has, I could run a query like this: Employee.objects.annotate( client_count=Count("clients") ).values( "first_name", "client_count" ).order_by("-client_count") <QuerySet [ {'first_name': 'f1', 'client_count': 2}, {'first_name': 'f2', 'client_count': 2}, … -
autocomplete form in django
i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table views.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def get_employee(request): if is_ajax(request=request): q = request.GET.get('term', '') places = InfoTrabajadores.objects.filter(documento__icontains=q) results = [] for pl in places: place_json = {} place_json['label'] = pl.state results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) and the jquery $(document).ready(function() { async function getCities(event, ui) { let url = '{% url ' / api / get_employees / ' %}'; let url = 'http://127.0.0.1:8000/api/get_employees/'; let results = await fetch(url); let data = await results.json(); return data; }; async function AutoCompleteSelectHandler(event, ui) { let zipCode = await getCities(); $('#nombre').val(nombre[ui.item.value]); $('#num_emergencia').val(num_emergencia[ui.item.value]); $('#prov_salud').val(prov_salud[ui.item.value]); $('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]); $('#rh').val(rh[ui.item.value]); }; $("#autoSuggest").autocomplete({ source: "{% url 'invitados' %}", select: function(event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); });