Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bypass the ordering inside the Meta class
I have two models: class Member(models.Model): course_member = models.ForeignKey(CourseMember, on_delete=models.CASCADE class Meta: db_table = 'member' ordering = ['-id'] class CourseMember(models.Model): name = models.CharField(max_length=30) When I try running. Member.objects.values('course_member').aggregate(Count('id')) I keep getting the wrong order_by. instead of grouping by course_member, it keeps grouping by member_id. The Django docs warn about this issue, see link. I'm trying to see if there is a solution to bypass this issue instead of just waiting for Django 3.1 -
How do I tell POpen to use/set certain environment variables?
I'm using Python 3.7 and Django. I use the below to run a command I would normally run in the shell ... out = Popen([settings.SELENIUM_RUNNER_CMD, file_path], stderr=STDOUT, stdout=PIPE) t = out.communicate()[0], out.returncode his dies with the error b'env: node: No such file or directory\n' What I'm trying to figure out is how to give my Python environment access to the normal environment variables I have access to, or figure out a way to set them before I run my Python command. Normally "node" is easily found when I check as myself davea$ which node /usr/local/bin/node But I don't know how to tell Python to use the same PATH that I have access to. -
Django model form field: use disabled but still pase (calculated) values to form.is_valid()
Assume I have a model class A with a mandatory text field b (and other fields). I want to create a model form where under certain circumstances (determined in the form's __init__) the value for b is calculated and not shown in the form. It seems that setting disabled is the way to go, which, according to this docs entry, will ignore any value passed but instead use "the form’s initial data". However, the following does not do what I hoped it would do: class A(models.Model): b = models.TextField() c = ... class MyForm(forms.ModelForm): class Meta: model = A fields = ('b', 'c', 'd') def __init__(self, *args, **kwargs): if complicated_test(*args, **kwargs): field = self.fields['b'] field.disabled = True field.initial = 'Bla' This does disable the field, but seems to ignore the manually given value Bla, which in my case will make form.is_valid() fail (as my model really expects Bla to be in there). Questions: Is field.initial = 'Bla' really supposed to fail in this situation, or it this a weird bug in my setup? If no bug: Can I set "the form’s initial data" in some other way? What alternatives are recommended? In my case, I do not see a natural … -
django-heroku installation giving an error
I'm trying to deploy my app to heroku but after executing pip install django-heroku it gives me an error. I'm running Python 3 with Django 2.2 on a mac. The error message recommended to install psycopg2-binary, which I did but after the installation I still see the same error. Thank you for help. The error message: ERROR: Complete output from command python setup.py egg_info: ERROR: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/6z/cqmvjcds4_s2pz_8zb28s_v40000gn/T/pip-install-28adny1a/psycopg2/ -
Elasticsearch create index error on Heroku
I have a django application that uses elasticsearch with the django-elasticsearch-dsl package as an integration. Locally I'm using docker compose to host my django and elasticsearch services and after some setup everything is working fine. I'm hosting the app on heroku with the bonsai add-on and am getting the following error when running ./manage.py search_index --rebuild to create the index on the heroku bonsai elasticsearch instance. elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [receiver : {type=text}] [sender : {type=text}] [created_at : {type=date}] [id : {type=integer}] [text : {type=text}] [source : {type=text}] [title : {type=text}]' ) I've played around with my local elasticsearch version and flavor to get it to be as similar as possible to the deployed instancem, but can't get the error to reproduce to debug it. The only fields that are different are name and cluster_name, all other fields are the exact same. { name: "7OgSp1I", cluster_name: "docker-cluster", cluster_uuid: "ZOXfnHeJTrK-nF7GEKON3A", version: { number: "6.5.4", build_flavor: "oss", build_type: "tar", build_hash: "d2ef93d", build_date: "2018-12-17T21:17:40.758843Z", build_snapshot: false, lucene_version: "7.5.0", minimum_wire_compatibility_version: "5.6.0", minimum_index_compatibility_version: "5.0.0" }, tagline: "You Know, for Search" } Both local and deployed have the same version of django-elasticsearch-dsl installed through the Pipfile. Not sure what else to … -
Django passing a parameter from a site to another
I have two different django project hosted on two different domains. I would from a view of a project1 redirect traffic to a page with a form of a project 2 passing a value for fill a field of the form. In my project1 view i do: @login_required def go_ccredit(request, lic_num=None, **kwargs): return HttpResponseRedirect('https://www.project2.ai/goform') i would to pass lic_num variable in my HttpResponseRedirect, and in my project2 goform page check if there is in request a variable named lic_num and in case fill the field with id=license with it's value. I hope to be clear enough So many thanks in advance -
Grabbing the data from the post request for create model view set override django rest framework
I have a django rest framework project with a model view set. I want to override the create method of the viewset. With the override, I want to grab data from the post request and data from the url arguments. Now i can grab the url arguments as I am expecting. I am having trouble trying to get the post request data informaiton in order to set all the correct data before submitting the create request. This is what I have..: I am having an issue with the request.data['version'] & request.POST['version'] & request.data.version @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): # print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.data['version'], 'namespace':namespace, 'path':request.data['path'], 'value':request.data['value'], 'user_id':request.user.id, } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.data['version'], 'namespace':namespace, 'path':path, 'value':request.data['value'], 'user_id':request.user.id, } return super().create(data) -
Django join different tables
This is what i got in the models class SFE(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) # Field name made lowercase. elementid = models.ForeignKey(Functionalelement, models.DO_NOTHING, db_column='ElementID') # Field name made lowercase. celllineid = models.ForeignKey(Celllines, models.DO_NOTHING, db_column='CELLLINEID') # Field name made lowercase. countexperiments = models.PositiveIntegerField(db_column='countExperiments') # Field name made lowercase. filetype = models.CharField(db_column='fileType', max_length=10) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs_FunctionalElement' unique_together = (('snpid', 'elementid', 'celllineid', 'filetype'),) def __str__(self): return str(str(self.snpid) + str(self.elementid) + str(self.celllineid) + str(self.filetype)) class Functionalelement(models.Model): elementid = models.AutoField(db_column='ElementID', primary_key=True) # Field name made lowercase. name = models.CharField(unique=True, max_length=55) class Meta: managed = False db_table = 'FunctionalElement' def __str__(self): return str(self.elementid) class Snps(models.Model): snpid = models.AutoField(db_column='SNPID', primary_key=True) # Field name made lowercase. rsid = models.CharField(unique=True, max_length=20) chrom = models.CharField(max_length=5) pos = models.PositiveIntegerField() ref = models.CharField(max_length=1) alt = models.CharField(max_length=1) maf1000genomes = models.FloatField(blank=True, null=True) maftopmed = models.FloatField(db_column='mafTOPMed', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs' def __str__(self): return str(self.snpid) Now i want to join FunctionalElement with SFE in order to retrieve the field FunctionalElement.name given a specific SFE.snpid. I tried with SFE.objects.select_related('elementid__name') but i know it's wrong and i can't understand how to work with django ORM -
Custom ordering on a many to many relationship
I'm trying to implement a model that represents sorted lists of items, without having to specify the sort order every time I'm unable to find a way to customize the get_queryset() method of the forward many-to-many relationship manager from django.db import models class Item(models.Model): name = models.CharField(max_length=50) class Meta: ordering = ['name'] class List(models.Model): name = models.CharField(max_length=50) items = models.ManyToManyField(Item, through='Listing')) class Listing(models.Model): list = models.ForeignKey(List, on_delete=models.CASCADE) items = models.ForeignKey(Item, on_delete=models.CASCADE) index = models.SmallIntegerField() class Meta: ordering = ['index'] I would like Item.objects.all() to be sorted by name (working), and List.objects.get(pk=1).items to be sorted by listing.index (not working; also sorted by name) -
Django - How to retrieve columns in template automatically from a query in views.py?
There is a module with 30 columns. I query this table in the views.py to get the last record (last row). To get the data in template (index.html), I have to write each column and in front of it, its value. I have to do it 30 times! is there anything like {{form}} to get all the columns and their value automatically or at least by using {% for ... %}? in views.py def articlesindex(request): data = Articles.objects.all().last() return render(request, 'Articles\index.html', {'articles':data}) in index.html {{ articles }} (does not work) {{ articles.a_table }} (does not work) {% for k,v in articles %} (does not work) <tr> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endfor %} -
Can Email Validators overwrite clean() method?
Problem: I am attempting to write a clean() method on my Django forms class and for the most part, it is working (Password validation is working but not email?). My goal is to compare two email fields and two password fields to each other and raise a validation issue if they do not match. I have tried using the raise forms.ValidationError() as detailed in the Django docs here, however I would prefer to display the validation error on both fields so I am trying to use the self.add_error('field', msg) method instead as detailed on the same page. My attempt: forms.py class userRegistrationForm(forms.Form): # field definitions here def clean(self): cleaned_data = super(userRegistrationForm, self).clean() email1 = cleaned_data.get('email') email2 = cleaned_data.get('emailConfirm') password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 != password2: msg = 'Your Passwords do not match...' self.add_error('password1', msg) self.add_error('password2', msg) elif email1 != email2: msg = 'Your emails do not match...' self.add_error('email', msg) self.add_error('emailConfirm', msg) Exact error: What ends up happening, is the first email field validates with no errors no matter what and if there is a mismatch, the error only shows up on the second field, unless I type out the full correct email address, then that field also … -
Django-allauth, how do I change the url in my email confirmation email?
friends. Used Django-allauth package for authorization in django project. The project is located in the Docker container (with parameter -p 8002:8001) on the server with the domain(testsite.com). When I run the container on the command line, I run the python command manage.py runserver 0.0.0.0:8001. In the admin panel specify the domain of the site. The problem is that django-allauth sends an email to confirm the email type - http://127.0.0.1:8002/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg/. In the package code found that the url is used to build the site.domain - but when the variable is output to the console - get the correct domain of the form - testsite.com ahhh! I can not understand what variable to override or how to make to get the desired url of the form - http://testsite.com/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg ahhh! Can who knows as solve this question? -
Django-Rest: Need to get all data in batch wise from oracle
I need to create Django rest API- fetching data from Oracle DB, apply pagination, send back to response. For that, I am taking no_of_rows_per_page and page_no, and fetching all data. I am using fetchall() method. By this method we are getting all data from DB first, then pagination apply and send back as response. By this process, we need to call next page data, we are getting the same process again(Loading all data again from DB). For that our application is taking too much time (Database connected through VPN and Table having millions of records) For this, I need to fetch data in batch, for that, I used fetchmany(no_of_rows_per_page) method and returning back as response. Since Oracle return each time random rows, getting duplicate/same rows in next page call. Help needed on this. Thank you. -
multitenant django db not migrate
i'm using django-db-multitenant this works ok but the problem is when i try run migrate get this error: [roo@rgmanagement_2 facturacion]$ TENANT_DATABASE_NAME=rg python manage.py migrate Operations to perform: Apply all migrations: correo, empresa, sessions, personal, admin, proveedores, ordenescompra, seguridad, auth, cartera, bodegas, movimientos, contenttypes, custodias, clientes, contabilidad, productos, secuencias, ordenespedido, ventas Running migrations: Rendering model states... DONE Applying seguridad.0004_auto_20190709_1300...Traceback (most recent call last): File "manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/lib64/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib64/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib64/python2.7/site-packages/django/db/migrations/operations/models.py", line 202, in database_forwards new_model._meta.db_table, File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 359, in alter_db_table "new_table": self.quote_name(new_db_table), File "/usr/lib64/python2.7/site-packages/django/db/backends/base/schema.py", line 110, in execute cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib64/python2.7/site-packages/django/db/utils.py", line 95, in … -
Replacing Basic Auth in Django Rest Framework
I currently have Django basic auth setup with Knox token authentication. Basic Auth doesn't seem sufficient for production work, so I want to replace that. Does Django have another password-based authentication_class that I can easily replace BasicAuthentication with, or is this a more involved process? If so, where do I start? my login api view: class UserLoginView(GenericAPIView): serializer_class = UserOrganizationSerializer authentication_classes = (BasicAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request): """User login with username and password.""" token = AuthToken.objects.create(request.user) return Response({ 'user': self.get_serializer(request.user).data, 'token': token }) my default authentication classes: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ], -
GIF Erroring on Network
I'm not quite sure if this is a Django issue, an HTML issue, or something else so apologies if this isn't properly tagged. I have an application where a user submits an Elasticsearch query and a report is then generated. Depending on the number of results the query returns, the report can take quite a while to generate. As a result, I'd like to put a gif of a spinner so the user understands that it's still processing (instead of me just explicitly saying it's still going). I have ajax-loader.gif in my project/static/ folder but it doesn't seem to recognize that it exists because it's giving me a 404 error. Additionally, it's classifying the type as "text/html" instead of "gif". How can I get the gif to load in? html <!-- templates/django_audit/check.html --> {% extends 'base_login.html' %} {% block title %}Please wait{% endblock %} {% load static %} {% block content %} <script type='text/javascript' src="{% static "bootstrap/js/jquery/1.7.1/jquery.min.js" %}"></script> <script type="text/javascript"> $(document).ready( function() { var fn = $('#fn').val() var checkInterval = setInterval(isFileComplete, 3000); //1000 is 1 second function isFileComplete() { $.ajax({ url: '/check_progress/', type: 'POST', data: { 'filename': fn, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, dataType: 'json', success: function (data) { if … -
What's behind the mechanism of Django models and fields?
What is the Django/Python mechanism behind the Django model/field part of framework? To be exact, I am looking for a hint on how Django parses (?) class definition and then knows which fields are required? from django.db import models class Car(models.Model): name = models.CharField(max_length=255, null=True, blank=True) year_of_production = models.DateField(null=True) # the rest of fields... I think the same mechanism is behind Django Forms framework or DRF serializers. I checked repos of these projects but I still can't find any reasonable starting point. There's a architectural problem under my question. I think I need to implement something similar to this mechanism: class Field: def __init__(self, label: str, required: bool = True, **kwargs): self.label, self.required = label, required class CharField(Field): def __init__(self, max_length: int, **kwargs): self.max_length = max_length super().__init__(**kwargs) class DateField(Field): ... class BooleanField(Field): ... class Model: # the mechanisms I do not understand class MyModelInstance(Model): name = CharField(...) # etc. What I need is really simple solution that knows that field is required. But as I stated before I am not that advanced and I would really appreciate any hints. -
How can I know the space left in a pdf page?
I have a pdf with 3 sections and I had to add a page break for each section but now I have to know if the section 3 is smaller and can go into in the same page with section 2, but the tricky part is if section 3 is more than the space left in the page after section 2 I have to add the page-break. What I mean is if I can know where section 2 ends in a page and if I can know the space left in that page, and in the space left can section 3 be. The actual is that section 3 goes after section 2 and when section 3 is longer than the space left for section 2, it does in that way. I expected if section 3 is longer than the space left in the page after section 2 should be a page break, if not so section 3 should go after section 2 on the same page. -
Grabbing data from post request and creating new object model error: 'dict' object has no attribute 'data'
I have a django rest framework project. I want to take the standard create method for Model View Sets in django rest framework. I want to create a new model object based on the data passed in but I also wanted to override some of the fields if they are passed in through url arguments. So if there are no url arguments => just create a default object based soley on the post request. if there is a namespace arguments => create default object based on post request but use the namespace url argument. if there is a namespace and path arguments => create default object based on post request but use the namespace and path url arguments.: I am getting the following error: AttributeError at /api/v2/preferences/namespace1/ 'dict' object has no attribute 'data' Here is the model view set: @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':request.POST['path'], 'value':request.POST['value'], 'user_id':request.user.id, } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':path, 'value':request.POST['value'], 'user_id':request.user.id, } return super().create(data) -
images not loading from HTML template using Django
Images on my Django website are not loading This is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT= os.path.join(BASE_DIR,'assets') This is my index.html file code for images: I have used {% load staticfiles %} in the index.html file also have ran "python manage.py collectstatic" -
How to completely reset Postgres DB on Heroku?
I have a learning project deployed on Heroku. It had a Postgres database provisioned. I introduced some major changes in the models of my Django project and destroyed the old DB and provisioned a new one, which is totally empty, but it is not working like an empty database. When I run the command heroku run python manage.py makemigrations, I get the error message, You are trying to add a non-nullable field.... Why am I getting this message when I have destroyed the old database? -
Virtual Environment won't create
I am just getting into Django and I'm trying to create a virtual environment, I am using windows 10. I have Pip and Python installed. However, when I try to create a virtual environment, I keep getting this in the cmd prompt over and over again. The message is: Running virtualenv with interpreter c:\users\kenny james\appdata\local\programs\python\python37\python.exe How can I resolve this? -
How to Update Object in Django
I two functions which I am using to update an object when various user input is detected. I have two other functions which operate in a nearly identical manner, however, for some reason the object is not being updated upon submission like the other functions. views.py(working) def new_opportunity_engineer(request): id = request.GET.get('id') try: obj = Opportunity.objects.get(id=id) account_manager_obj = cwObj.get_member_by_id(obj.accountManger) account_manager = account_manager_obj[0]['firstName'] + ' ' + account_manager_obj[0]['lastName'] inside_solutions_obj = cwObj.get_member_by_id(obj.insideSolutions) inside_solutions = inside_solutions_obj[0]['firstName'] + ' ' + inside_solutions_obj[0]['lastName'] selected_company_obj = cwObj.get_company_by_id(obj.company) selected_company = selected_company_obj[0]['name'] selected_location = obj.location selected_contact_obj = cwObj.get_contact_by_id(obj.contact) selected_contact = selected_contact_obj[0]['firstName'] + ' ' + selected_contact_obj[0]['lastName'] company_id = obj.companyId selected_practice = obj.practice project_name = obj.projectName ware_type = obj.wareType estimate_id = obj.estimateId qualify = obj.qualify professional_services = obj.professionalServices total = obj.total maintenance = obj.maintenance sub_labor = obj.subLabor ga_contract = obj.gaContract cisco = obj.cisco cisco_question_1 = obj.ciscoQuestion1 cisco_question_2 = obj.ciscoQuestion2 cisco_question_3 = obj.ciscoQuestion3 close_date = obj.closeDate priority = obj.priority notes = obj.notes except Opportunity.DoesNotExist: obj = None context = { 'account_manager': account_manager, 'inside_solutions': inside_solutions, 'selected_company': selected_company, 'selected_location': selected_location, 'selected_contact': selected_contact, 'company_id': company_id, 'selected_practice': selected_practice, 'project_name': project_name, 'ware_type': ware_type, 'estimate_id': estimate_id, 'qualify': qualify, 'professional_services': professional_services, 'total': total, 'maintenance': maintenance, 'sub_labor': sub_labor, 'ga_contract': ga_contract, 'cisco': cisco, 'cisco_question_1': cisco_question_1, 'cisco_question_2': cisco_question_2, 'cisco_question_3': cisco_question_3, 'close_date': … -
Unable to get Django HttpResponse
A little description of what i m trying to do. I want to make a User Interface (web/HTML) through which i can send the commands to router and display the result on the Webpage/HTML. Here's the code i m using:- Views.py from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse def index(request): my_dict = {'insert_me': ""} return render(request,'first_app/index.html',context=my_dict) def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler devices = { 'device_type':'cisco_ios', 'ip':'192.168.50.145', 'username':'kartik', 'password':'12345', 'secret':'12345', 'port':'22' } cmd = request.POST.get('command', '') netconnect = ConnectHandler(**devices) #print("connection established with", devices['ip']) output = netconnect.send_command(cmd) return render(request,'first_app/forms.html', {'form': form, 'output':output}) else: form = CmdForm() return render(request,'first_app/forms.html', {'form': form}) forms.py from django import forms class CmdForm(forms.Form): command = forms.CharField(label='Command to execute') urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from first_app import views urlpatterns = [ path('Automation_page/', views.form_name_view,name='IP form'), path('admin/', admin.site.urls), path('', views.index,name='first'), path('first_app/',include('first_app.urls')), ] forms.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>FORMS</title> </head> <body> <h1> IP address form </h1> <p>Run command:</p> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Run command!" /> </form><br> {% if request.POST %} <p>Command output:</p> <pre>{{ output }}</pre> … -
Can't create new model object within django rest framework model view set: 'User' object is not subscriptable
I have a django rest framework project. I am trying to override the create method so that if there are certain parameters or arguments passed into the url, it will ovverride some of the default informaiton passed in with the form. I am doing that by creating the data object that will be used to create the new object. Right now, I am grabbing the user by using request.user but it is giving me the following error: TypeError at /api/v2/preferences/namespace1/ 'User' object is not subscriptable and I am not sure how to fix it. Here is my code for the mode view set create method override: @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':request.POST['path'], 'value':request.POST['value'], 'user_id':request.user['id'], } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.POST['version'], 'namespace':namespace, 'path':path, 'value':request.POST['value'], 'user_id':request.user['id'], } return super().create(data)