Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms.Form reflecting property field constraints
I'm implementing a Django Form witch should contain the field 'fieldA' from modelA: class ModelA(models.Model): fieldA = models.CharField(max_length=8) ... My question is: Is there a way to have Django form, which will automatically handle validation of fieldA (check the max_length)? I know I Could use form.ModelFormclass referring to ModelA, but then the form would reflect all the fields of the ModelA. I would like to use simple forms.Form. I'm looking for a solution like: class formX(forms.Form): fieldA = forms.CharField(**modelA.fieldA.constraints) fieldB = ... some other fields not related to ModelA ... .... even more fields -
Django Rest Framework for Calculations
I'm starting to develop in django/django rest framework and I needed to make a kind of calculator, send a and b, python would take these values, process, for example, do the sum and return in a json, but I only find examples with database data, would it be possible to do this? -
Django Middleware Login check
I want to restrict all pages for unauthenticated users. I wrote the following middleware: from django.shortcuts import redirect def require_login(get_response): def middleware(request): if request.user.is_authenticated: response = get_response(request) return response return redirect('/login/') return middleware The issue is that it also redirects to my Login page when it redirects to Login page (hope you got it). So it continuously redirects to my login page. What do I need to do about it? Is it okay to check if the requested page is Login page then don't check the if statement above. Thanks! -
django-tailwind problem on python manage.py tailwind start
I have an issue with tailwind that did not happen before and I can't really think of any change I would have done. Anyone encountered that? Can't really find a fix to it. Thanks for your help Traceback (most recent call last): File "manage.py", line 9, in execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 55, in handle return self.handle_labels(*labels, **options) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 63, in handle_labels getattr(self, "handle_" + labels[0].replace("-", "_") + "_command")( File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 103, in handle_start_command self.npm_command("run", "start") File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\management\commands\tailwind.py", line 113, in npm_command self.npm.command(*args) File "C:\Users\user\Desktop\Projets\afufmedia1\venv\lib\site-packages\tailwind\npm.py", line 23, in command subprocess.run([self.npm_bin_path] + list(args), cwd=self.cwd) File "c:\program files\miniconda\lib\subprocess.py", line 489, in run with Popen(*popenargs, **kwargs) as process: File "c:\program files\miniconda\lib\subprocess.py", line 854, in init self._execute_child(args, executable, preexec_fn, close_fds, File "c:\program files\miniconda\lib\subprocess.py", line 1247, in _execute_child args = list2cmdline(args) File "c:\program files\miniconda\lib\subprocess.py", line 549, in list2cmdline for arg in map(os.fsdecode, seq): File "c:\program files\miniconda\lib\os.py", line 818, in fsdecode filename = fspath(filename) # Does type-checking of filename. TypeError: expected str, bytes or os.PathLike object, not NoneType -
How to Reassign value to variable in Django template through filters
I have an xml object that I am looping to print in template. It is detailing of items with their tax rate. so after printing all items I need sum of those tax rate values. I am trying to sum up that value in template. I have created filter named updatevariable, it is working and doing sum up but issue is due to loose of old sum it just returns latest value rather than whole sum up. SO I need a way to reassign TotalTax with sum up value from filter. this is example of output needed: Tax-1 16 Tax-2 18 Tax-3 2 TotalTax = 36 {% with TotalTax=0 %} {% if taxRateDetailing %} {% for item in taxRateDetailing%} <tr> <td> {{item.1.text}} </td> <td> {{item.4.text}} {{TotalTax|updatevariable:item.4.text}} </td> </tr> {% endfor %} <tr> <td> Total Tax </td> <td> {{TotalTax}} </td> </tr> {% else %} <tr> <td> Tax </td> <td> {{defaultSalesTaxRate}} </td> </tr> {% endif %} {% endwith %} Filter function def updatevariable(value, arg): TotalTax = value + float(arg) return TotalTax -
why my URL's path work when I delete name?
hi guys my second app path works when I delete 'notes' in the path why? urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('notes/', include('notes.urls')) ] urlpatterns= [ path('',views.list, name="notes"), ] def list(request): all_notes = Note.objects.all() return render(request, "notes/notes.html" , {'notes' : all_notes} ) -
How do I display a Django form correctly using ListView
I am writing a simple app to track sales leads based on the Django tutorial "Writing your first Django app" (https://docs.djangoproject.com/en/4.0/intro/tutorial01/). Everything works well except for displaying a ListView of the existing leads. Here are the relevant python snippets: # leads/models.py class Leads(models.Model): id = models.IntegerField(primary_key=True) last = models.CharField(max_length=32) first = models.CharField(max_length=32) # config/urls.py urlpatterns = [ # Django admin path('admin/', admin.site.urls), # User management path('accounts/', include('allauth.urls')), # Local apps path('leads/', include('leads.urls')) # leads/urls.py app_name = 'leads' urlpatterns = [ path('', LeadsListView.as_view(), name='list'), path('<int:pk>/', LeadsDetailView.as_view(), name='detail'), ] # leads/views.py class LeadsListView(ListView): model = Leads template_name = 'leads/list.html' context_object_name = 'leads_list' def get_queryset(self): return Leads.objects.order_by('id') class LeadsDetailView(DetailView): model = Leads template_name = 'leads/detail.html' The link in the 'home.html' template, which displays a menu option correctly: <a href="{% url 'leads:list' %}">Leads</a> And finally, the 'list.html' template that does not display at all. Instead of showing the list of leads, it remains on the home page. {% block content %} {% for lead in lead_list %} <div class="lead-entry"> <h2><a href="{% url 'leads:detail' lead.pk %}">{{ lead.fname }} {{ lead.lname }}</a></h2> </div> {% endfor %} {% endblock content %} I'm missing something fundamental here.... -
Convert the Image to base64 and upload the base64 file in S3 and get the same file using django
I need to get a image from django imagefield and convert it to base64 file and upload that converted file in private s3 bucket. And while I getting the image from the s3 bucket I need to get that base64 file and send it to the forntend(reactjs). Basically I need to convert the image to base64 file, I checked on the internet and Iam not sure where to use that code correctly. Can anyone please suggest me to do that or is any clear documentation available to use as step by step. Here is my model, views and seriailizers class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def remove_on_image_update(self): try: # is the object in the database yet? obj = Organisation.objects.get(org_id=self.org_id) except Organisation.DoesNotExist: # object is not in db, nothing to worry about return # is the save due to an update of the actual image file? if obj.org_logo and self.org_logo and obj.org_logo != self.org_logo: # delete the old image file from the storage in favor of … -
Django, runserver exits with -1073741819 (0xC0000005) code
I have downloaded Django project in my Windows PC, that has a large amounts of libs and modules. When I try to run runserver command, it returns to me this: Process finished with exit code -1073741819 (0xC0000005) Every other manage.py commands just crashes silently without any warnings and messages. I know that this code means buffer overload. How it is possible to increase buffer or fix this? -
What should I return at post function in DetailView Class
I have Message model and Post model. I can successfully save message on data base, however I got an error at PostDetailView,views.py 'super' object has no attribute 'post' How can I fix this? All my code views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message.objects.create( user=request.user, post_id=self.kwargs.get('pk'), body=request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
Is there any way to run python manage.py runworkers & python manage.py runserver simultaneously in apache server?
While deploying django project in Apache server facing an error : I need to run python manage.py runworkers and python manage.py runserver simultaneously. It is working fine while running local/django server. But have complications in production time. -
Django 2.1: takes 1 positional argument but 4 were given
Note: I have python version 3.9 on my laptop and I know Django 2.1 is only compatible with python's version 3.7. is python's 3.7 version will solve the issue that I am facing right now? I have 2 year old django 2.1 project and when I type: python manage.py runserver it throws an error of _XMLParser.__init__(self, html, target, encoding) TypeError: __init__() takes 1 positional argument but 4 were given my requirements.txt file packages: amqp==2.5.0 asn1crypto==0.24.0 billiard==3.6.0.0 boto3==1.9.223 botocore==1.12.223 cairocffi==0.9.0 CairoSVG==2.4.2 captcha==0.3 celery==4.3.0 certifi==2018.11.29 cffi==1.15.0 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 cryptography==36.0.2 cssselect2==0.2.2 defusedxml==0.5.0 diff-match-patch==20181111 Django==2.1.5 django-admin-honeypot==1.1.0 django-admin-numeric-filter==0.1.2 django-admin-rangefilter==0.3.10 django-admin-shortcuts==2.0.0 django-admin-toolbox==1.0.0.dev15 django-admin-tools==0.8.1 django-advanced-filters==1.4.0 django-ajax-selects==1.7.1 django-allauth==0.39.1 django-bower==5.2.0 django-braces==1.13.0 django-captcha-admin==0.2 django-celery-beat==1.5.0 django-chart-tools==1.0 django-ckeditor==5.6.1 django-cors-headers==2.0.2 django-extensions==2.1.4 django-filter==2.1.0 django-froala-editor==2.9.2 django-import-export==2.8.0 django-jet==1.0.8 django-js-asset==1.1.0 django-jsonfield==1.0.1 django-material==1.4.1 django-modeladmin-reorder==0.3.1 django-nvd3==0.9.7 django-oauth-toolkit==1.2.0 django-qsstats-magic==1.0.0 django-recaptcha==1.3.0 django-rest-auth==0.9.5 django-rest-framework-social-oauth2==1.1.0 django-rest-swagger==2.2.0 django-storages==1.7.1 django-suit-redactor==0.0.4 django-timezone-field==3.0 django-tinymce==2.8.0 django-wordpress-api==0.2.0 djangorestframework==3.9.0 djangorestframework-jwt==1.8.0 djcacheutils==3.0.0 docutils==0.15.2 drf-yasg==1.12.1 drfdocs==0.0.11 enum34==1.1.6 et-xmlfile==1.0.1 gunicorn==19.9.0 html5lib==1.0.1 idna==2.8 inflection==0.3.1 ipaddress==1.0.22 iso8601==0.1.12 itypes==1.1.0 jdcal==1.4 jet-django==0.4.4 Jinja2==2.10 jmespath==0.9.4 kombu==4.6.3 logger==1.4 Markdown==3.1.1 MarkupSafe==1.1.0 numpy==1.22.3 oauth2-provider==0.0 oauthlib==3.0.0 odfpy==1.4.0 openapi-codec==1.3.2 openpyxl==2.5.12 pandas==1.4.2 Pillow==9.1.0 psycopg2-binary==2.9.3 pycparser==2.19 pyfcm==1.4.5 PyJWT==1.7.1 PyMySQL==0.9.3 pyOpenSSL==18.0.0 Pyphen==0.9.5 PySocks==1.6.8 python-crontab==2.3.8 python-dateutil==2.8.0 python-http-client==3.1.0 python-memcached==1.59 python-nvd3==0.14.2 python-openid==2.2.5 python-slugify==1.1.4 python3-openid==3.1.0 pytz==2018.7 PyYAML==3.13 raven==6.10.0 reportlab==3.6.9 requests==2.21.0 requests-oauthlib==1.2.0 requests-toolbelt==0.9.1 ruamel.yaml==0.15.83 s3transfer==0.2.1 sendgrid==5.6.0 sentry-sdk==0.12.2 simplejson==3.16.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.0.0 stripe==2.22.0 tablib==0.12.1 tinycss2==1.0.2 toml==0.9.6 twilio==6.21.0 unicodecsv==0.14.1 Unidecode==1.0.23 uritemplate==3.0.0 urllib3==1.24.1 … -
want to check my logout function in django is working or not
i have 2 api 1--login 2-- logout i have to make a "SAMPLE_API" which which will be be accessed by only loggedin user can able to access if loggedout user/new user is tring to access that "SAMPLE_API"--- than it should return "UNAUTHORISED" -
Return total value from Subquery - Dja
I have a django query that returns values but I also need to calculate the total quantity in a subquery. When I have only one value in the subquery table it works fine although if more than one i get an error "More than one row returned by a subquery used as an expression". Any help would be appreciated. here is sample of code def get_machine_components(self): return PlantMachineryComponents.objects.filter(machine=self.get_object()).annotate(stock_qty=Sum(Subquery(Stock_DET.objects.filter(stock_hdr__commodity=1275).values('qty')))) -
Annotate Total Created, Modified, and Deleted for each week
Given a Model Item how would I find the total number of items created, modified, and deleted every week? And can this be done in a single database query? from django.db import models class Item(models.Model): created_at = models.DateTimeField(null=True, blank=True) modified_at = models.DateTimeField(null=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) My current query returns the same counts for total_created, total_modified, and total_deleted. from django.db.models.functions import TruncWeek Item.objects.annotate( created_at_week=TruncWeek("created_at"), modified_at_week=TruncWeek("modified_at"), deleted_at_week=TruncWeek("deleted_at"), ).values("created_at_week", "modified_at_week", "deleted_at_week").annotate( total_created=models.Count("id"), total_modified=models.Count("id"), total_deleted=models.Count("id"), ) I know it's possible to add filter parameter to Count but I do not know if I can use that here. -
Two HTML Forms in one DJango views
I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2. There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission. HTML Form <form action="" method=post name="form1" id="form1"> <input type="text" id="input_form1" name="input_form1"> <button type="submit">Submit</button> </form> <form action="" method=post name="form2" id="form2"> <input type="text" id="form2" name="form2"> <button type="submit">Submit</button> </form> Views.py def index(request): if request.method == 'POST': input_form1 = request.POST.get('input_form1') return render(request, 'index.html', params) Please elaborate how to integrate form2 in Views.py -
cannot update into database using this formset
def updateID(request): EmployeeFormSet = modelformset_factory(Employee, form=EmployeeForm,extra=0) queryset = Employee.objects.filter(EmpID=None) if request.method == "POST": Empform = EmployeeFormSet(request.POST, request.FILES, queryset=queryset) Empform=EmployeeFormSet() if Empform.is_valid(): Empform.save() # Do something. else: Empform=EmployeeFormSet(queryset=queryset) return render(request,'updatingid.html',locals()) I was trying to update the id of a existing employee through formset but it isn't updating -
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00'
I have a Django app, where I use raw SQL query to get some item with date before some date. In view.py file I have to query the CourseInfo table to get the courses before a specific date. View.py: query_results = CourseInfo.objects.raw('SELECT * FROM TABLE_course WHERE first_semester <= %s' % (datetime(2021, 1, 1))) But I got this error: 1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00' at line 1 How could I fix this error? -
How to pass list of urls from view to tempalte and use them in url reverse
How can I pass a list of URLs to template that corresponds to a specific view? I would like that url {{view}} reverses to theme:view1 views.py def preview(self): context = { "views": ["view1", "view2"] } urls.py app_name="theme" urlpatterns = [ path('view1', view.some_view1, name="view1"), path("view2" view.some_view2, name="view2") ] index.html {% for views in view %} <a href="{{ url {{view}} }}" {% endfor %} Putting {{view}} in quotes makes it a string instead of url -
FileNotFoundError: [Errno 2] using Pipenv
I'm trying to install dependencies in django using pipenv install. Then it responded error message like this in Ubuntu. Does file path in wrong or installation incomplete? Python version - 3.10.4, pip version - pip 22.0.4 from /usr/local/lib/python3.10/dist-packages/pip (python 3.10) /home/username/.local/lib/python3.10/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release warnings.warn( /home/username/.local/lib/python3.10/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( Creating a virtualenv for this project... Pipfile: /home/username/Documents/codes/storefront2/Pipfile Using /usr/bin/python3 (3.10.4) to create virtualenv... ⠏ Creating virtual environment...created virtual environment CPython3.10.4.final.0-64 in 184ms creator CPython3Posix(dest=/home/username/.local/share/virtualenvs/storefront2-Kl67gUFU, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/username/.local/share/virtualenv) added seed packages: pip==22.0.4, setuptools==62.1.0, wheel==0.37.1 activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator ✔ Successfully created virtual environment! Traceback (most recent call last): File "/usr/local/bin/pipenv", line 8, in <module> sys.exit(cli()) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/pipenv/cli/options.py", line 56, in main return super().main(*args, **kwargs, windows_expand_args=False) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File … -
__init__() missing 1 required keyword-only argument: 'creator'
I am getting type error while setting current user to created_by field in my model forms.py class MyModelForm(forms.ModelForm): class Meta: model = Model fields = ('name',) def __init__(self, *args, creator, **kwargs): super().__init__(*args, **kwargs) self.creator = creator def save(self, *args, **kwargs): self.instance.created_by = self.creator return super().save(*args, **kwargs) views.py class CreatEEView(LoginRequiredMixin, CreateView,): form_class = '' template_name = '' success_url = '' Models.py class MYmodel(models.Model): name = models.CharField() created_by = models.ForeignKey() -
Bootstrap datatable queryParams & pagination
I'm using bootstrap datatable to render my tables. It's almost working like I expected it to work but not quite and I don't know why. <table class="datatable-font-size" data-toggle="table" data-search="true" data-search-align="left" data-pagination="true" data-query-params="queryParams" data-pagination-parts="[pageList]" data-classes="table table-borderless table-striped"> <thead> <tr> <th>Name</th> <th class="ColHideMobile text-center">Intern name</th> <th class="text-end">Last modification</th> </tr> </thead> <tbody> {% for champ in champs %} <tr class="trLink" data-identifiant="{{field.identifiant}}"> <td>{{field.name}}</td> <td class="ColHideMobile text-center">{{field.intern_name}}</td> <td class="text-end">{{field.modif_date|date:"d/m/Y à H:i"}}</td> </tr> {% endfor %} </tbody> </table> I call my function in js, parameter = 15: queryParams("limit") function queryParams(params) { console.log("{{parameter}}") // params.limit = parseInt("{{parameter}}") params = {"limit":parseInt("{{parameter}}"),"offset":0,"order":"asc"} // console.log(params) // console.log(params["limit"]) console.log(JSON.stringify(params)); return params } It goes inside the function queryParams but my datatable never render the number of row limit I want. I don't understand why. I also have a little problem with my pagination: The pagination goes outside the card and my tags are correctly closed so I don't get why it goes sideway. Thank for your help. -
AttributeError: 'str' object has no attribute '_meta' upon migrating
I moved my Inventory model to its own app and reset all migrations. python manage.py makemigrations has no issues, but I get an error upon migrating. Hope someone could point me to a direction since the traceback doesn't seem very helpful to me for resolving the issue. traceback Operations to perform: Apply all migrations: admin, auth, contenttypes, inventory, item, project_site, requisition, sessions, transfer, users Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK ... Applying item.0001_initial... OK Applying project_site.0001_initial...Traceback (most recent call last): File "C:\Users\Bernard\pelicans\imrs-capstone\imrs\manage.py", line 22, in <module> main() File "C:\Users\Bernard\pelicans\imrs-capstone\imrs\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() ... File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards schema_editor.create_model(model) File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\db\backends\base\schema.py", line 364, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' project_site/0001_initial.py from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('item', '0001_initial'), ] operations = [ migrations.CreateModel( name='Cart', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cartItemCount', models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name='Site', fields=[ ... ('inventory_items', models.ManyToManyField(blank=True, related_name='inventory_items', through='inventory.Inventory', to='item.Item')), ('siteCart', models.ManyToManyField(blank=True, related_name='siteCart', through='project_site.Cart', to='item.Item')), ], ), ] -
How to implement JWT access mechanism for a Django application (not django rest_framework)
I'm actually looking for a way to implement. I have a django project folder (only django, not django rest framework). All the views across all the apps in the project will be returning a JsonResponse parsed response. (Instead of rendering to a template) A basic view looks like this, with necessary imports from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.http import JsonResponse @csrf_exempt @require_http_methods(['POST']) def sample_route(request): # validate request object, use them to query / process data # .. some more statements result = {"a": 1, "b": 2} return JsonResponse(result, status=200) I understand that this isn't a conventional practice like in a DRF project, but I would like to make such routes accessible by tokens (supposedly JWT). Can I get suggestions about how this would be possible - like with or without depending on djangorestframework library or any extensions or any other JWT associated libraries. Thanks -
Join with OneToOneField relathionship django
I have two models with OneToOneField relationship and I want to somehow join them and be able to access the attribute of the one model from the other. My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My views.py is as follows: @api_view(['GET']) def result(request): results_list = Result.objects.all() num_results_list = Result.objects.all().count() if num_results_list < RES_LIMIT: serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) else: results_list = Result.objects.order_by('-created_at')[:RES_LIMIT] serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) Right now the query is as follows: [OrderedDict([('id', 1), ('HVAC_flex', [49.0, 27.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), ('DHW_flex', [4.0, 0.0, 45.0, 4.0, 20.0, 33.0, 42.0, 13.0]), ('lights_flex', [6.0, 8.0, 0.0, 0.0, 0.0, 18.0, 28.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', 2), ('HVAC_flex', [0.0, 0.0, 15.0, 0.0, 23.0, 6.0, 0.0, 0.0]), ('DHW_flex', [1.0, 2.0, 7.0, 47.0, 1.0, 19.0, 37.0, 9.0]), ('lights_flex', [40.0, 28.0, 34.0, 6.0, 8.0, 43.0, 6.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', …