Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing Django user information to Dash app
I am curious whether it is possible to pass the currently logged in user full name into a Dash app created in Django? Assume you have a simple Dash table integrated into Django: import dash from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd from django_plotly_dash import DjangoDash df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) Are there any way to access the -Django- user information of the person who is logged in? This is just a simple example, but I want to create an SQL folder conditional on user name and user ID located in Django Admin. I solely need to know how to grab the name e.g. "name = request.user.get_full_name" or some type of similar function (in the latter case 'request' is not defined so it does not work). Thanks! -
Django PUT/PATCH request body is empty in RetrieveUpdateAPIView
I'm trying to update user by passing Jwt token in header. But body of my request is empty. View passes empty data to serializer. views.py class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): serializer_data = request.data.get('user', {}) print(f'request data: {request.data}') # prints empty dic {} serializer = self.serializer_class( request.user, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) When I run PUT or PATCH request on Postman, I get unchanged user which is related to a token. postman: Postman django terminal says: Error Can someone explain what am I doing wrong? -
__str__ returned non-string (type bytes)
I'm trying to open the view for my posts but I keep getting the error 'str returned non-string (type bytes)'. I read thhat I should use force_bytes and then unicode but it doesn't seem to be working. How can I fix it? This is the model: class Post(models.Model): """ Post """ category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField('Title', max_length=200) body = models.TextField('Body') reply_to = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='child') created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL'), on_delete=models.CASCADE, related_name='posts') def __str__(self): return force_bytes('%s' % self.title) def __unicode__(self): return u'%s' % self.title -
ordering modelchoicefield in django loses formatting
I wanted to order a list in my form view, and found this post here: How do I specify an order of values in drop-down list in a Django ModelForm? So I edited my code and added the line specialty = forms.ModelChoiceField(queryset ='...') So then I reload the form and the widget is all smoshed and funky looking. I checked the html code and the specialties are indeed in the right order! But it misses the widget definition lower adding the form-control class. I am not sure why. if I remove the line specialty = form.ModelChoiceField then everything looks great aside from the dropdown not being in the right order (alphabetical by name field) Not sure why it is missing that widget definition and attaching the class form-control or the tabindex even. Guessing the specialty = forms.ModelChoiceField is overriding it somehow? class ProviderForm(forms.ModelForm): specialty = forms.ModelChoiceField(queryset = Specialty.objects.order_by('name')) #added this def __init__(self, *args, **kwargs): super(ProviderForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-6' self.helper.field_class = 'col-md-6' self.fields['ptan'].required = False self.helper.layout = Layout( Field('...'), Field('specialty'), FormActions( Submit('save', 'Save'), Button('cancel', 'Cancel'), Button('terminate', 'Terminate', css_class="btn-danger"), ), ) class Meta: model=Provider fields = ( '...', 'specialty' ) widgets = { 'specialty':Select(attrs={ … -
Maintain a subset of Django app along with full app
I'm working on a Django project for a large organization, and the full app will be for internal, private use, while a subset of the view functions and templates will also need to be available publicly. Due to IT constraints, the public portion will be on a different server, and won't be able to use the same files (but it will be able to query the database on the private server). Is there a way to maintain a subset of the app's files on a separate server? For example, if the private version has view functions a, b, and c, the public version will only use c. And the public version will only need the relevant template files, etc. Does Django have some way of accomplishing this? Or Git, somehow (maybe gitignore)? I'm just trying to save myself from having to manually copy all updates from the full version to the partial version. -
How to return the maximum value for a given day in python django
I have two apis that return doctor list and nurses list. Each doctor/nurse has a field amount for the amount of money in their account.My aim is to return the nurse/doctor with the highest amount of money on a given day, since these values will change when money is earned/withdrawn.Basically I need to return the max value from doctors and nurses, and then return the maximum of those two as well.I have tried Max in django and order_by but there seems to be more that I need to do to achieve the desired result.I will appreciate if anyone can spare sometime to take me through how to achieve this.The apis that return this data look smt like: "doctors": [ {"name": kev "amount": 100.00}, {"name": dave "amount": 200.00} ] "nurses": [ {"name": brian "amount": 150.00}, {"name": mary "amount": 90.00} ] -
Django:How to update field value from another model?
I want to update the value of field Availability value from "available" to "issued" in the CylinderEntry model when the user Issued that particular cylinder but I was unable to make the change. here what logic I m executing: class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(pk=self.pk).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName+" issued "+self.cylinder.cylinderId here is cylinderentry model: class CylinderEntry(models.Model): stachoice=[ ('fill','Fill'), ('empty','empty') ] substachoice=[ ('available','Availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId here is issuecylinder model: class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE,unique=True) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(pk=self.pk).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName+" issued "+self.cylinder.cylinderId help me out make changes in values :) -
I tried running code for my SLAMTECH RPlidar but the lidar doesnt get imported in my python window but it show it has been imported on my terminal
Here is the error File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/cbook/__init__.py", line 224, in process func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 959, in _start self._init_draw() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1703, in _init_draw self._draw_frame(next(self.new_frame_seq())) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/animation.py", line 1726, in _draw_frame self._drawn_artists = self._func(framedata, *self._args) File "/Users/lkhagvabyambajav/Desktop/rplidar/examples/animate.py", line 14, in update_line scan = next(iterator) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 357, in iter_scans for new_scan, quality, angle, distance in iterator: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 323, in iter_measurments raw = self._read_response(dsize) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rplidar.py", line 199, in _read_response raise RPLidarException('Wrong body size') rplidar.RPLidarException: Wrong body size and code is from rplidar import RPLidar import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation PORT_NAME = '/dev/tty.usbserial-0001' DMAX = 4000 IMIN = 0 IMAX = 50 def update_line(num, iterator, line): scan = next(iterator) offsets = np.array([(np.radians(meas[1]), meas[2]) for meas in scan]) line.set_offsets(offsets) intens = np.array([meas[0] for meas in scan]) line.set_array(intens) return line, def run(): lidar = RPLidar(PORT_NAME) fig = plt.figure() ax = plt.subplot(111, projection='polar') line = ax.scatter([0, 0], [0, 0], s=5, c=[IMIN, IMAX], cmap=plt.cm.Greys_r, lw=0) ax.set_rmax(DMAX) ax.grid(True) iterator = lidar.iter_scans() ani = animation.FuncAnimation(fig, update_line, fargs=(iterator, line), interval=50) plt.show() lidar.stop() lidar.disconnect() if __name__ == '__main__': run() I didnt write this code it is from https://github.com/SkoltechRobotics/rplidar Im trying to test my lidar to see if it … -
Unable to install dependencies for django_heroku because of lack of pg_config
(Disclaimer: I'm a frontender and don't know much about python; I'm trying to deploy the backend that my partner made to Heroku along with my React build. Apologies in advance if I'm hard to understand/using JS terminology) I'm trying to host a django app on Heroku. If I include import django_heroku django_heroku.settings(locals()) and then try to run the server, I get this error: ModuleNotFoundError: No module named 'django_heroku' This thread reports that it's because of a missing dependency. However, when I try to run pip3 install psycopg2 I get this cascade of errors -- it's like pip is trying to install older and older versions of psycopg2 until it find a match, but each time it errors out. And the error states: 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'. I don't have a pg_config file/package, nor a steup.cfg or a setup.py package. There is a setuptools_build.py. This thread suggests it's because I don't have postgres installed, but we're not using postgres (we're … -
error with sekizai for adsense when debug = false in my django web app
i'm trying to add google adsense to my django web app and i can't activate my account because of no content on my website. (ah this moment i had only put the script tag that google gave me when i created my account). so i tried to add django ads and sekizai to my app to make adsense work on it. and my problem is that when my debug settings is true and i try to runserver, everything works well, but when i change it to False and try runserver, i've got an 500 error and i don't understand why... there was one thing i've maybe bad understand in the sekizai settings is the last step : "For Django versions after 1.10, add sekizai.context_processors.sekizai to your TEMPLATES['OPTIONS']['context_processors'] setting and use django.template.RequestContext when rendering your templates." where should i put "django.template.RequestContext" ? it the only way i have to solve my problem. i leave you few parts of my settings.py, thank's for help and answer Settings.py : """ Django settings for yufindRe project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from … -
Django: Saving database with manipulated .csv file | Error: “” value has an invalid date format
I have csv file and It is updating by another platform periodically. I am trying to import this csv file to my database. But csv file style (like date field, blank fields or choice fields) are not matching with django. So I need to manipulate this file and then I am going to import to my database. Even I edit this csv file in my script and looks good as a csv file, still I got following errors. Error django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] Aslo I have another error ValueError: Field 'socialNumber' expected a number but got ''. My Models class Personnel(models.Model): personnnelNumber = models.IntegerField(primary_key=True) name = models.CharField(max_length=50, null=True, blank=True) dateEmployment = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) dateTermination = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) cardCode = models.IntegerField(null=True, blank=True) SapCode = models.IntegerField(null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) idNo = models.IntegerField(null=True, blank=True) gender = models.CharField(max_length=50, null=True, blank=True) birthdate = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) socialNumber = models.IntegerField(null=True, blank=True) dateEmploymentRD = models.DateField( auto_now=False, auto_now_add=False, null=True, blank=True) dateTerminationRD = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) task = models.CharField( max_length=50, null=True, blank=True) workTime = models.IntegerField(choices=((1,'Full Time'),(2,'Part Time')), null=True, blank=True) graduateLevel = models.CharField( max_length=50, null=True, blank=True) highSchoolname = models.CharField( max_length=50, null=True, … -
Django Maximum Recursion Depth Exceeded. View loops infinitely
I am writing an application that will decode make, model, and year information for provided VIN numbers from cars. The script works standalone but when integrated into my django app and called through a button click on my web app, the view begins to loop infinitely and raises a RecursionError. I will provide relevant code below base html template <!DOCTYPE html> {%load static%} <Html> <title>What the F*cking F*ck</title> <head> </head> <h1>Here I will attempt to recreate the Working Title File in a somewhat nice looking format. </h1> <h4>We'll see what happens</h4> <div> {% block header %} <p>Upload an IPDF with the Browse Button below</p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} <p><a href="{% url 'wtf' %}">Return to upload</a></p> <p> </div> <div id="address"> {% block address %} <p>This is where stuff would render if you had uploaded something. But you didn't. Or it broke. So shame on both of us.</p> {% endblock %} </div> </Html> address_render.html (inherits from base, also called wtf). This one works as intended. When I click the button here to call the view vin_decode it breaks. {% extends "wtf2/wtf.html" %} <script scr='../../jquery-3.6.0.js'> </script> {% block header %} <p>Successful Address … -
Question: 'tuple' object has no attribute 'get' [closed]
def search_jobs(request): if request.method == "POST": searched = request.POST['searched'] jobs = Job.objects.filter(job_title__contains=searched) return render(request, 'jobs/jobs_searched.html', {'searched':searched, 'jobs':jobs}), else: return render(request, 'jobs/jobs_searched.html') Traceback Switch to copy-and-paste view C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\deprecation.py, line 119, in call response = self.process_response(request, response) … ▶ Local vars C:\Users\Jams\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response if response.get('X-Frame-Options') is not None: … ▼ Local vars -
How to clear Django-imagekit cache?
on my ubuntu VPS, I process thousands of images through django-imagekit. My code class Thumbnail(ImageSpec): processors = [ResizeToFit(1200)] format = 'WEBP' options = {'quality': 90} Main_image = open('path/to/image.jpg','rb') Preview_gen = Thumbnail(source=Main_image) Preview = Preview_gen.generate() but after few hundred processes it stops at: Preview = Preview_gen.generate() but after restarting the server it works fine for the next few hundreds maybe it's related to caching so, how to clear the cache or any other solution -
Issue joining data in graphene-django with a ManyToMany field
I've been trying to find a good example for returning a query set with joined data across a ManyToMany field, but I've not found one. Given the following model: class Task(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) detail = models.ManyToManyField("Detail", through="TaskDetails") class Detail(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) detail_name = models.CharField(max_length=250) class TaskDetails(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) task = models.ForeignKey("Task", related_name="detail_tasks") detail = models.ForeignKey("Detail", related_name="task_details") detail_value = models.CharField(max_length=250) I'd like to return the data for Task with it's related details. Based on the answer on this question, I tweaked my schema to the following: class TaskDetailsType(DjangoObjectType): class Meta: model = TaskDetails fields = ("id", "detail_name", "detail_value") detail_name = graphene.String() def resolve_detail_name(value_obj, info): return value_obj.detail.detail_name class TaskType(DjangoObjectType): class Meta: model = Task fields = ("id", "task_details") task_details = graphene.List(TaskDetailsType) def resolve_task_details(value_obj, info): return value_obj.detail_tasks When I run this though, I get an error: {'errors': [{'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}], 'data': {'getInboxTasks': [{'id': 'a430e49d-c9c3-4839-8f2c-aaebbfe9ef3a', 'taskDetails': None}, {'id': '74c8dacc-1bfd-437a-ae34-7e111075ac5e', 'taskDetails': None}, {'id': '10956caa-d74f-4a01-a5cf-9cac6a15c5a3', 'taskDetails': None}]}} -
Complex query, getting the sum of a group of brands django
So here is the following issue, i am basically trying to bring up a query that display a top 10 brands table. And i am currently stuck at trying to 'join up' the brands. As you can clearly see, i am uncapable of putting the brands at the same group and count the number of sales, of that specific brand group. I tried the following query, but it didnt work out query2= DataDB.objects.annotate(marcas=Count('marca')).order_by('marcas')[:10] And here is my tables code <table class="table table-striped table-dark" width="100%"> <thead> <th>Marca</th> <th>N* de vendas</th> </thead> {%for q in query2 %} <tr> <td>{{q.marca}}</td> <td>{{q.marcas}}</td> </tr> {% endfor%} </table> Would really appreciate a little help here, dont actually know if the issue is on display or query. -
How to use temporary files in AWS - moving from BytesIO
I have a Django app hosted on Heroku, with the static files in an AWS bucket. On my localhost I had been using xhtml2pdf to render some pdfs. I have been using the code below. Does anyone know how I could achieve something similar with AWS bucket (possibly using Boto3)? def render_to_pdf(template_src, context_dict={}): template=get_template(template_src) html=template.render(context_dict) result = BytesIO() pdf=pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
'tuple' object has no attribute 'filter'
I'm trying to return two tables in two querysets, using objects attributes filter and get. I tested on print function these two querysets and they are returning right. But the error continues. I believe that mistakes happen only in views.py. def cliente_detail_view(request, slug): template_name = 'reconhecimento_facial/cliente_detail.html' obj = Cliente.objects.filter(Q(slug__icontains=slug) | Q(slug__iexact=slug)) cliente = Cliente.objects.get(slug__icontains=slug).id_cliente print(cliente) queryset2 = Exame.objects.filter(cliente_fk=cliente) print('cliente_detail_view') print(obj) context = { "object": obj, "object2": queryset2 } return render(request, template_name, context) class ClienteDetailView(DetailView): def get_queryset(self): slug = self.kwargs.get("slug") print('--------') print(slug) print('--------') if slug: queryset = Cliente.objects.filter(slug__icontains=slug) cliente = Cliente.objects.get(slug__icontains=slug).id_cliente print(cliente) queryset2 = Exame.objects.filter(cliente_fk=cliente) #queryset3 = Dependencia.objects.get(id_cliente1=cliente) #queryset4 = Dependencia.objects.get(id_cliente2=cliente) else: queryset = Cliente.objects.all() queryset2 = Exame.objects.all() print('ClienteListView') print(queryset) print(queryset2) return queryset, queryset2 -
Django object search
I am trying to make a search bar for some QuerySet objects. How can I make this code cleaner? filtered = test.filter( Q(user__icontains=query) | Q(notes__icontains=query) | Q(fees__icontains=query) | Q(date__icontains=query) ) This code looks through all the fields of the model for the search query. I am thinking a way to make this cleaner is somehow pass in a list like ['user', 'notes', 'fees', 'date'] and then running __icontains for all the items in the list. -
How to use a nested serializer dynamically for two serializers?
I am working on an API, with Django, Django Rest Framework, and trying to achieve these(ad described) First Serializer class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField(initial={}) context = serializers.JSONField(initial={}) templates = FilterTemplatesByOrganization(many=True) class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] extra_kwargs = {'status': {'read_only': True}} Now I have two nested serializer containing the above serializer for the LIST and DETAIL endpoints:- Second Serializer class DeviceListSerializer(FilterSerializerByOrgManaged, serializers.ModelSerializer): config = DeviceConfigSerializer(write_only=True, required=False) class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip','management_ip', 'model', 'os', 'system', 'notes', 'config', 'created', 'modified',] Third Serializer class DeviceDetailSerializer(BaseSerializer): config = DeviceConfigSerializer(allow_null=True) class Meta(BaseMeta): model = Device fields = ['id','name','organization','mac_address','key','last_ip','management_ip', 'model','os','system','notes','config','created','modified',] Now, I am using the same serializer for List, and Detail endpoint, but for the list endpoint I have set the nested serializer as write_only=True, But What I am trying to do with the list endpoint that is DeviceListSerializer serilaizer is that out of all the fields from the DeviceConfigSerializer, I want the status, and backend fields to be readonly and others fields as write_only. Presently with this configuration I am getting the response from the DeviceListSerializer as this:- { "id": "12", "name": "tests", "organization": "-------", "mac_address": "-------", "key": "------", "last_ip": null, "management_ip": null, "model": "", "os": … -
Is there is compulsory to stop a thread in python?
I have started a thread for sending email, Does my code need to stop a thread. I started a thread from view.py file Please inform me if I need to change my code view.py ForgotPassword(user, full_name).start() task.py import threading from django.contrib.auth.tokens import default_token_generator from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from Settings.models import Global class ForgotPassword(threading.Thread): def __init__(self, user, full_name): self.user = user self.full_name = full_name threading.Thread.__init__(self) def run(self): site = Global.objects.get(pk=1) subject = "Password Reset Requested" c = { "email": self.user.email, 'domain': '127.0.0.1:8000', 'site_name': site.visible, 'site_full_name': site.hospital, 'site_email': site.email, 'user_name': self.full_name, 'site_address': site.address, 'uid': urlsafe_base64_encode(force_bytes(self.user.pk)), 'user': self.user, 'token': default_token_generator.make_token(self.user), 'protocol': 'http', 'facebook': site.facebook, 'contact': site.contact, } html_template = render_to_string('Email_templates/password_email_template.html', c) from_email = site.hospital + " " + "<" + site.email + ">" try: send_mail(subject, None, from_email, [self.user.email], html_message=html_template) except BadHeaderError: return HttpResponse("Invalid Header") -
Update Bootstrap modal body with pk/id for Django form
I have table with data provided by Django. Each row has naturally different data and different 'pk'. I'd like to use Bootstrap Modals to render form and send it back to Django, to edit the fields. I spent hours to find and try different solutions from SO, but it still don't work for my case. Please help as I'm out of options now. Here is pure code I manage to produce: HTML: <a data-bs-toggle="modal" data-bs-target="#updatemodal" title="Update" class="btn btn-icon btn-light btn-hover-primary btn-sm mx-3" data-url="{% url 'event:event-update' event.pk %}">link </a> <div class="modal fade" tabindex="-1" id="updatemodal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Update Event</h5> <!--begin::Close--> <div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close"> <span class="svg-icon svg-icon-2x"></span> </div> <!--end::Close--> </div> <div class="modal-body"> <form id="update-form" method="POST" action="#"> <button type="submit" class="btn btn btn-danger font-weight-bold ml-2"> Update Event </button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close </button> </div> </div> </div> </div> Javascript: <script> $('#updatemodal').on('show.bs.modal', function (e) { var trigger = $(e.relatedTarget).data('url'); console.log(trigger); document.getElementById("update-form").setAttribute("action", trigger); }); </script> Note: I use BS 5.0.0-beta3 + JQ 3.6 As for now I get it from here: <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> -
type object 'ContactCenter' has no attribute 'objects'
I'm getting a weird error for the first time, can some one help please from .models import ContactCenter from django_tenants.utils import schema_context from apps.contacts.models import Contact # Create your views here. class ContactCenter: def test(self, logged_user_id = None): obj = [] contacts = ContactCenter.objects.filter(name = "john") error : type object 'ContactCenter' has no attribute 'objects' -
What is a CBV mixin in Django?
I was reading about the Django UserPassesTestMixinmixin, and I came across the term CBV Mixin. What is this, and how is it useful? Is a CBV Mixin a general type of mixins, and are there CBV mixins in any other framework apart from Django? -
How to increase SSL timeout on Amazon EC2 instance?
The ADFS server I have to leverage is hosted on Azure in a different country. Occasionally I get an error HTTPSConnectionPool(host='<sts server name>', port=443): Max retries exceeded with url: /adfs/oauth2/token/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)'))) Just need to increase the SSL timeout between my Amazon EC2 instance hosted Django site, and the Azure hosted ADFS server. How would I do that?