Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, }); }); -
How to define and render Django formset for registeting hours spent on a project each day during a month?
I building a Django site where users can register their time spent working on a particular project (Time Report). In the future Time reports will be subject to approval process and possibly sources for calculating invoices to clients, but right now I struggle in setting it up in Django. I want Time Reports to hold multiple project lines and each project line should have as many input fields as many days is in a particular month . This will allow user to register number of hours spent each day on all projects they work on. In addition each project can be presented in more than line (so user can register different tasks within the project separately, e.g. hours spent on project planning vs time spent on development). Projects are defined separately (separate model). I believe that I need following models to support the requirements: from django.db import models class TimeReport(models.Model): employee = models.ForeignKey('employees.Employee', on_delete=models.CASCADE) start_date = models.DateField() #to calculate Time Report month status = models.CharField(max_length=20, default='draft') class ProjectLine(models.Model): time_report = models.ForeignKey('TimeReport', on_delete=models.CASCADE) project = models.ForeignKey('projects.Project', on_delete=models.CASCADE) comment = models.TextField(blank=True, null=True) class ProjectLineDay(models.Model): project_line = models.ForeignKey(ProjectLine, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField(max_digits=2, decimal_places=0) I want to achieve something like this … -
NOT NULL constraint failed: store_customer.first_name
NOT NULL constraint failed: store_customer.first_name Request Method: GET Request URL: http://127.0.0.1:8000/signup/ Django Version: 4.1.4 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: store_customer.first_name models.py class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=50) email = models.EmailField(max_length=100) password = models.CharField(max_length=500) def register(self): self.save() def __str__(self): return self.first_name views.py def signup(request): if request == 'GET': return render(request, 'signup.html') else: first_name = request.POST.get('firstname') last_name = request.POST.get('lastname') phone = request.POST.get('phone') email = request.POST.get('email') password = request.POST.get('password') customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password) customer.register() # return HttpResponse( 'signup successful' ) return render(request, 'signup.html') -
How to query model list from one app to another django?
I am facing an issue in django. I have two apps in my project booking and Home, in the booking I have a model called Clinics that has data related to clinics in the home app I am creating a template that shows clinics list I used {% if clinics_list%} to query the data into the model but nothing shows up notes: 1.clinics list has data 2.I imported the clinics model into home app in models.py 3.no issues were detected when running check Tried to create new model(test) in home app that inherit the data from clinics and used {% if test_list %} -
SessionId inside the cookie header slows down request (Django)
I'm learning how to use django sessions and caching. I noticed that once I login, a sessionId is included in the cookie header. I'm using the "@authentication_classes" and "@permission_classes" decorators to validate the session. I'm also using Redis to cache the session, since I dont want to hit the DB everytime. I followed the docs for the django and redis server setup. Once the user log in, the session is written in the cache. The problem is that, even tho the session is inside the cache, the database is hit with each request and it slows down the response time to around 300ms. This is the api I'm using for testing. It does nothing, but it takes 300 ms and it does hit the DB each time I call it. I'm using "never_cache" because I dont want the entire response to be cached. @api_view(["GET"]) @authentication_classes ([SessionAuthentication]) @permission_classes([IsAuthenticated]) @never_cache def test(request, username): return JsonResponse("", safe=False) this is the request I'm making: request If I remove the session autentication decorators, a SessionId is not required anymore to access the api, but the DB is still hit and the response still takes 300ms (there is still the sessionID token inside the cookie header). …