Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Store form data with changing fields
I am trying to make a platform to handle various custom forms whose fields are are not known beforehand (similar to google forms). How can I manage the data entries from the form to my backend/ database. (django -> sql postgress)? I thought of using the standard Django models, but they need the fields to be pre-specified in code. -
Heroku Redis Error while reading from socket: (104, 'Connection reset by peer')
I'm running a Heroku Redis instance that always worked fine, but after the upgrade when I try to run celery workers I get the following error [2021-07-23 11:06:08,135: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-54-***-***-*.eu-west-1.compute.amazonaws.com:*****//: Error while reading from socket: (104, 'Connection reset by peer'). Trying again in 12.00 seconds... (6/100) Everything seems to be up to date and I can't seem to figure out how to run it again. I tried to drop the redis instance and create it from scratch but nothing. -
Check constraint on django
I have two models class Order(models.Model): ord_number:str ord_date: date ord_ref: str Null=True ord_qty: Decimal ord_desc: str timestamp: datetime created: datetime Class OrderLines(models.Model): order: FK(Order) driver: FK(Driver) truck: FK(Truck) ord_qty: Decimal loaded_quantity: Decimal loading_date: date My schemas on posting will be like this OrderCreateBase = create_schema(Order, exclude=("id", "timestmap", "created")) OrderLineCreateBase = create_schema(OrderLines, exclude=("id)) class OrderCreateSchema(OrderCreateBase): order_lines = List[OrderLineCreateBase] Json data to be used on creating like this "ord_number: "AB123", "order_date: Date(01/01/2021), "ord_ref" Null, "ord_qty": Decimal("10_000"), "ord_desc" "Sample Order", "order_lines"[ {"order_id": 1, "driver_id: 23, "truck_id": 12, "ord_qty": Decimal("10_000"), "loaded_quantity": Decimal("8_000") <----#, "loading_date": Date(01/01/2021)}, {"order_id": 1, "driver_id: 13, "truck_id": 17, "ord_qty": Decimal("10_000"), "loaded_quantity": Decimal("9_000") <----#, "loading_date": Date(01/01/2021)}] } I want check constraint that will ensure total loaded quantity(loaded_quantity) per order will be <= to ordered_quantity (ord_qty) currently my create endpoint is like this @router.post( "/ilr/{ilr_id}/instrunctions", response={HTTPStatus.CREATED: Message, HTTPStatus.BAD_REQUEST: Message}, tags=["ilrs instructions"], summary=_("create loading request instructions"), description=_("API to create ilr instructions lines"), url_name="create_ilr_instructions", ) @transaction.atomic() def create_ilr_instrunctions(request, ilr_id: int, payload: ILRLineCreateSchema): data = payload.dict() ilr = get_object_or_404(ILR, id=ilr_id, status=0) data["request"] = ilr data["order_date"] = ilr.ilr_date # get existing lines total volume total_volume = ILRLine.objects.filter(request=ilr).aggregate(total_volume=Sum("quantity")) if ilr.quantity < total_volume.get("total_volume") + data.get("quantity"): <-----# return HTTPStatus.BAD_REQUEST, { "detail": [{"msg": f"Total loading quantities will be higher than ordered … -
How to assign string value instead of id in a foreign key column in Django view?
I'm working on a Django project where I have to assign a string into a foreign key column. But i'm getting error like this Field 'id' expected a number but got 'Rituparna Das' for this line js.update(Developers=rule[1]) Here's my model.py class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True, primary_key=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developers = models.ForeignKey(developer, on_delete=models.CASCADE,blank=True, null=True) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) Epic = models.CharField(max_length=500, blank=True) class assignmentRule(models.Model): id = models.AutoField(primary_key=True) assignmentRuleName = models.CharField(max_length=300) assignmentObject = models.CharField(max_length=300) assignmentValue = models.CharField(max_length=300) def __str__(self): return self.assignmentRuleName class assignmentRuleItem(models.Model): Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) # LogicalOperator = models.CharField(max_length=30, blank=True) Rule_No = models.ForeignKey(assignmentRule, on_delete=models.CASCADE, blank=True, null=True) And that is my view.py def rule_assignment_developer(request): rules = list(assignmentRule.objects.values_list('id','assignmentValue','assignmentRuleName','assignmentObject').filter(assignmentObject = 'Developer')) for rule in rules: # print(rule[1]) assignmentRuleItems = list(assignmentRuleItem.objects.values_list('Jira_Column', 'RelationalOperators', 'Jira_Value').filter(Rule_No = rule[0])) AR = len(assignmentRuleItems) print(AR) myString = '' for i in range(AR): kwargs = {} if myString == "": myString = myString + assignmentRuleItems[i][0] + assignmentRuleItems[i][1]+assignmentRuleItems[i][2] else: myString = myString+","+assignmentRuleItems[i][0]+assignmentRuleItems[i][1]+assignmentRuleItems[i][2] for e in myString.split(','): k, v … -
Please tell me which code needs to be modified
I want to edit the main page of ctfd, but I don't know which part to edit no matter how much I search.I can't use the django web server, so please tell me what part I need to edit to edit the main page text.enter image description here The material I want to fix and edit is at the link below. https://github.com/CTFd/CTFd -
nginx stops working if no requests on server_name
I set up django app with gunicorn and nginx with my laptop dedicated to be a server (works on Xubuntu). All works fine on this laptop, but trouble starts on another devices. I use real ip from my ISP, which is 195.214.223.143 so it's easy to reach site from server laptop and sometimes it's easy to reach the site by this ip from another devices. The thing is that I can't access my site if there are no activity from server laptop. So to run site (http://195.214.223.143:5001) I need to refresh the page of it on my server laptop or just to ping the port from my server laptop (like telnet 195.214.223.143 5001). After this I can reach the site from another device. But if there is no requests from my server laptop, after 1-2 minutes I lose access to site (ERR_CONNECTION_REFUSED). I've already thought about making script which will ping to port every minute, but that looks dumb of course. Below are my gunicorn and nginx configs. /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=holyskills Group=www-data WorkingDirectory=/home/holyskills/Desktop/SimpleBill/ivan-education/main_projec> ExecStart=/home/holyskills/Desktop/SimpleBill/ivan-education/main_project/main_> --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ main_server.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/main_server … -
Django-autocomplete-light filtering and displaying results based on two fields filtering the results based on two fields
I am facing some problem about using Django-autocomplete-light with one filter that able to filtering two different feild.It take about 2 weeek still cannot fix. model.py class Material(models.Model): model_name = "Material" material_code = models.CharField(max_length=50, null=False, blank=False, unique=True) name = models.CharField(max_length=100, null=False, blank=False, unique=True) def __str__(self): return "{} {}".format(self.material_code, self.name) form.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'material': autocomplete.ModelSelect2(url='autocomplete_material'), 'material': autocomplete.ModelSelect2(url='autocomplete_material_name'), } url.py path('autocomplete/material/', autocomplete.Select2QuerySetView.as_view(model=models.Material, **model_field_name="material_code"**), name="autocomplete_material"), path('autocomplete/material_name/', autocomplete.Select2QuerySetView.as_view(model=models.Material, **model_field_name="material_code"**), name="autocomplete_material_name"), For the filter that i want to able filter with two field name,which is material_code and name , that you can be showing in the model.py,right now if i put two autocomplete just can be run the bottom one cannot be filter two field name, that may be got solution that can be combie two model_field_name into one ? Thank !! -
how to create django template tag for custom model
I'm new for django template tag. I am trying to display logged user payment_status and remaining_days on django html template. For this I wrote model and I don't know how to write template tag for this. Request your help on this. models.py class User_subscription(models.Model): user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) subscription_id = models.ForeignKey(Subscription, on_delete=models.CASCADE) subscripted_date = models.DateTimeField() expired_date = models.DateTimeField() payment_status = models.CharField(max_length=50) payment_details = jsonfield.JSONField() I want to display payment_status above in model and remaining_days = expired_date-subscripted_date -
access one to one related relations inside django template
Applied candidate skill sets class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) Candidate job profile class SeekerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) current_salary = models.IntegerField() # when users appies for a job class JobPostActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) apply_date = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=25, default='onhold') def __str__(self): return self.user.username+''+self.job_post.title class Job_Skillset(models.Model): job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) skill = models.ForeignKey( Skillset, on_delete=models.CASCADE) skill_level = models.CharField(max_length=20) my view def manage_applic(request): if request.method == 'GET': # getting onhold candidates applied_candi = JobPostActivity.objects.filter( job_post__creater=request.user).exclude(Q(status__iexact='rejected') | Q(status__iexact='selected')) context = { 'applicants': applied_candi, } return render(request, 'jobmanagment/applicants_manage.html', context) Here is what I am trying, I want to get the skills of applied candidates which I am looping through, i having trouble getting those, there is one to one relation of user and seeker profile but how do we access that inside django template my view {% for val in applicants %} <tr> <td>({{val.user.id}}){{val.user.username | capfirst }}</td> <td>{{val.apply_date}}</td> <td> <select class="status_select" name="{{val.job_post.title}}" id="{{val.user.id}}" > <option selected="{{val.status}}" style="font-weight: bolder"> {{val.status}} </option> <option value="onhold">Onhold</option> <option value="selected">Selected</option> <option value="rejected">Rejected</option> </select> </td> <td> <b>{{val.job_post.job_type}}</b> </td> <td>{{val.job_post.title}}</td> <td> {% for cand_skills in val.user.seeker_profile.seeker_skill_set_set.all %} <<-- here is my issue … -
Django allauth:email comfirmation link can be accessed even after confirmation?
I'm using django-allauth to manage signin and signup in my Django app. When a user sign up, an email contains a confirmation link sent to the registered email. In allauth settings, I set ACCOUNT_CONFIRM_EMAIL_ON_GET=False so a user have to click a button to confirm the email address. But the link is still accessible even after user clicked the button. (by click the link in the email or press go back) Can I redirect the user to a specific url (e.g. home) if the user go to the confirmation link after confirmation? -
Sending bulk email from User email account
I have a web-app in Django, an user should be able to send marketing emails to a selected list of recipients but the emails should be sent from the user's personal email. This of course requires communication between my web-app and the user's email provider (for auth and managing emails). Leaving opinions aside, could anyone point to me libraries or tools used to achieve this functionality? Thanks -
Find all occurences of maximum value from a list of tuple?
I have a list of tuple such as: list1=[(1,1),(2,1),(3,1),(4,0),(5,0)] I have found the maximun element using: max_value = max(list1, key=itemgetter(1)) this outputs (1, 1) I want some thing like [(1,1),(2,1),(3,1)] -
Django python sehll from app.models import Modelclass not working
redcube/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) level = models.IntegerField(blank=True) def __str__(self): return self.user.username class Images(models.Model): redcube = models.ForeignKey(Redcube, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.redcube.name from the python shell >>> from redcube.models import Profile Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name 'Profile' from 'redcube.models' (/Users/macos/basic/btp/btp/redcube/models.py) >>> from redcube.models import Images >>> Images.objects.all() <QuerySet [<Images: Hawaii>, <Images: City view hotel>, <Images: Cottage>, <Images: Redcube>, <Images: Phone>, <Images: Flower>, <Images: Miho>]> When I try to import and test the models in the python shell Other model class is working right. but the Profile class is not working! I've tried the from .models import Profile, but not working. Thanks for the help :) -
TypeError at /book/2 string indices must be integers
I'm new to Django, I have encountered this error TypeError at /book/1 string indices must be integers I have a JSON file called book.json (seen below) { "books":[ { "id": 1, "title": "Unlocking Android", "isbn": "1933988673", "status": "PUBLISH", }, ..... I'm trying to get single book using id in the view def show(request, id): with open('bookstore/books.json') as file: books = json.load(file) book = [book for book in books if book['id'] == id] return render(request, 'books/show.html', book) The show.html template has this code <a href="/book/{{book.id}}"> for book links -
Finding the middleware that interrupted a Django request
I was debugging yesterday a Django view that returned a 403 without entering the view code. It turns out it was because I provided a Content-Type: multipart/form-data header without specifying the delimiter. This was "silently" rejected by some Django request parsing logic or middleware, which returned a 403. This makes sense, but the debugging experience wasn't great. Is there a way to make these middlewares (request parsing, auth, CSRF...) print some logs when they interrupt a request? -
Multiple Serializer within the same view.list call
I have a simple model that can contain some sensitive information class Organization(Model): name = CharField() is_private = BooleanField() # the following information is sensitive code = CharField() employee_count = IntegerField() # other confidential fields... I am using regular ModelViewSet and ModelSerializer for this model. when calling the list action of the viewset (GET organizations/) I would like to have my organizations serialized differently depending on whether they are private: show all the fields if the organization is not private only name if it is What I already tried: overriding get_serializer() of viewset => this doesn't fit as the same serializer applies for all objects of the list using serializers.MethodField() => not efficient because I have many fields that I'd need to handle -
I want to make location based app in django
Basically when user will put location name then a map showing that location should get displayed and I want to make it by google api like geocoding So can anyone help me? -
post django form data via iframe
I have a django form that I want to display on another website via iframe. The form displays ok but whenever I try to submit the form that is displayed in the iframe, I get a "server refused to connect" error message. Is it possible to make a django form work with iframe or is there a better way to do it? The views code for the form: from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def booking_create_view(request): form=BookingForm submitted = False if request.method=='POST': form = BookingForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/?submitted=True') else: form = BookingForm if 'submitted' in request.GET: submitted = True return render(request, "booking_form.html",{'form':form, 'submitted': submitted}) HTML for the form: <form class="" action="" method= POST> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <input type="Submit" value="Submit" class = "btn btn-secondary"> </form> {% endif %} The iframe: <h1>The iframe element</h1> <iframe src="http://127.0.0.1:8000/" title="test"> </iframe> Note: I have also tried using a live server (pythonanywhere) that had the same result -
extract data from sting by keys and values in python
i have a text field in which i have the following data how can i retrieve values from these keys can anyone help me out '{'wsgi.errors': '<gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f00a70eb668>', 'wsgi.version': '(1, 0)', 'wsgi.multithread': 'False', 'wsgi.multipr ocess': 'True', 'wsgi.run_once': 'False', 'wsgi.file_wrapper': "<class 'gunicorn.http.wsgi.FileWrapper'>", 'wsgi.input_terminated': 'True', 'SERVER_S OFTWARE': 'gunicorn/20.0.4', 'wsgi.input': '<gunicorn.http.body.Body object at 0x7f00a70ebe10>', 'gunicorn.socket': '<socket.socket fd=4, family=AddressFam ily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0, laddr=/home/ubuntu/oto_directory/oto_project/otocore.sock>', 'REQUEST_METHOD': 'POST', 'QUERY_STRING': '' , 'RAW_URI': '/api/v1/otp/create/', 'SERVER_PROTOCOL': 'HTTP/1.0', 'HTTP_X_FORWARDED_FOR': '157.37.221.189, 172.31.27.255', 'HTTP_HOST': 'abc.in', 'HTTP_CONNECTION': 'close', 'CONTENT_LENGTH': '31', 'HTTP_X_FORWARDED_PROTO': 'https', 'HTTP_X_FORWARDED_PORT': '443', 'HTTP_X_AMZN_TRAC E_ID': 'Root=1-60c98a8f-6308e3da7d3e4eef7c86e0c2', 'HTTP_SEC_CH_UA': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"', 'HTTP_ACCEPT': 'ap plication/json, text/plain, /', 'HTTP_X_ID_KEY': 'f48abf167aa67669e592933b9114e07f', 'HTTP_SEC_CH_UA_MOBILE': '?1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Li nux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Mobile Safari/537.36', 'CONTENT_TYPE': 'application/json', 'HTTP_ORIGIN': 'https://abcl.in', 'HTTP_SEC_FETCH_SITE': 'same-site', 'HTTP_SEC_FETCH_MODE': 'cors', 'HTTP_SEC_FETCH_DEST': 'e mpty', 'HTTP_REFERER': 'https://abc.in/', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9 ', 'HTTP_COOKIE': '_gcl_au=1.1.1633381306.1622530786; _ga=GA1.2.638419829.1622530787; _fbp=fb.1.1622530787694.1900095648; _hjid=cfa0329f-ffdd-439e-95a9-4f396ed001 ed; WZRK_G=5dc2f416c2394d4ba88bb7dd0bb9259d; session_id=bad4f39e-5b56-42f3-817d-9e14ac16d83e; csrftoken=2yVyosyb8eAewJ9bR7I9SX8bQPfsFcv5; _gid=GA1.2.607509864.162382 0852; _hjTLDTest=1; _hjAbsoluteSessionInProgress=0; WZRK_S_TEST-RKW-65Z-6Z6Z=%7B%22p%22%3A1%2C%22s%22%3A1623820853%2C%22t%22%3A1623820917%7D', 'wsgi.url_scheme': 'https', 'REMOTE_ADDR': '', 'SERVER_NAME': 'abc.in', 'SERVER_PORT': '443', 'PATH_INFO': '/api/v1/otp/create/', 'SCRIPT_NAME': ''} ' -
How to make clearable fileinput in django in an updateview
In my django app I have a person model with a filefield 'identification_image_front'. I also defined a ModelForm using the Fileinput widget for that field. For the template I am using the jasny-bootstrap plugin for representing the fileinput with 'Select file', 'Remove' and 'change' options Using the following code is is posible to save the file when creating a new working in the CreateView. But when updating an existing worker using the UpdateView the fileinput is allways empty. Is not posible to see if the worker has a file atached to it, nor remove the file from and existing Worker. Is there any way to load the file inside the fileinput and enabling the 'remove' option, so I can remove or change the file of an existing worker? Maybe there is another way to do that using other plugins or HTML code. I am open to suggestions This is my code class WorkerModel(BaseModel): name = models.CharField(verbose_name=_("Nombre "), max_length=50, blank=False, null=False) surname1 = models.CharField(verbose_name=_("Primer apellido"), max_length=50, blank=False, null=False) surname2 = models.CharField(verbose_name=_("Segundo apellido"), max_length=50, blank=False, null=False) identification_image_front = models.FileField(verbose_name=_("Foto carnet frontal"), upload_to="app_person_identification_image_front", null=True, blank=True) class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'surname1' : forms.TextInput(attrs={'class': … -
Upload and manipulate xml and image file in django
This code return a TypeError as expected str, bytes or os.PathLike object, not InMemoryUploadedFile I don't know how to pass user data in the form of file and image to my code.py file for making changes to the original. views.py def home(request): new_image = None file = None form = ScanForm() if request.method == 'POST': form = ScanForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] xml_file = request.FILES['xml_file'] new_image = code.create(image, code.search( xml_file)[0], code.search(xml_file)[1]) form.save() return render(request, 'app/home.html', {'form': form, 'new_image': new_image}) else: form = ScanForm() return render(request, 'app/home.html', {'form': form, 'new_image': new_image}) printing image and xml_file successfully prints out their names forms.py class ScanForm(forms.ModelForm): class Meta: model = Scan fields = '__all__' models.py class Scan(models.Model): image = models.ImageField(upload_to='images') xml_file = models.FileField(upload_to='files') processed_at = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=500, null=True) class Meta: ordering = ['-processed_at'] def __str__(self): return self.description Here is the code for manipulation of image according to the data in the xml code.py def search(path): new = [] object_names = [] object_values = [] txt = Path(path).read_text() txt.strip() names = et.fromstring(txt).findall('object') for i in names: object_names.append(i[0].text) values = et.fromstring(txt).findall('object/bndbox') for i in values: for j in i: object_values.append(int(j.text)) return object_names, object_values def create(image, object_names, object_values): img = cv.imread(image) on = … -
How to display latest 5 orders by using for loop in jinja (django)
The code below will display all the orders but now I want to display only 5 latest orders in my template. Can anyone explain to me how can I iterate only 5 latest orders through jinja? code <div class="card card-body"> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for i in orders %} <tr> <td>{{i.product}}</td> <td>{{i.date_created}}</td> <td>{{i.status}}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' i.id %}">Update</a></td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' i.id %}">Delete</a></td> </tr> {% endfor %} </table> </div> -
problems with authentication on the client
I am starting with a project with graphql I use django graphene for the backend and apollo with react but I have problems with authentication I am using django-graphene-auth for this but I don't know how to implement it on the client if I have to save it in a local storage or in a cookie in addition to how do I retrieve the necessary data, for example the profile if the only thing that returns the token is the username, I do not know if you can help me with some books, videos or any type of information where they explain this -
django csrf token not setting in cookie in production
I am using django and react js for my application and when i am passing csrf token in loclhost it ia working fine but in production csrftoken is missing.`axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; class LoginService extends Component { loginUser(formData) { const config = { headers: { 'content-type': 'application/json'}, "X-CSRFToken": Cookies.get('csrftoken'), withCredentials: true } return axios.post(${API_BASE_URL}api/user/v1/account/login_session/,formData,config); }` -
Get Django object attributes from url to use as context
I filtered a list and sent a link from the chosen record to my view. I want to use the attributes of that object as context to filter some models. I tried this code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entity = self.entity context["entity"] = entity This raises the error: 'EffectivenessProcessOwner' object has no attribute 'entity' The local variables reflected are: Variable Value __class__ <class 'internalcontrol.views.EffectivenessProcessOwner'> context {'pk': 1, 'view': <internalcontrol.views.EffectivenessProcessOwner object at 0x00000284A5672040>} kwargs {'pk': 1} self <internalcontrol.views.EffectivenessProcessOwner object at 0x00000284A5672040> How do I get the entity attribute (and others) from the object?