Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make non-model field disabled or readonly in djnago admin based on condition
i have model, admin and form for it. But there is a field in my form that is not in the model and i'm doing some custom action with that field. I want this field to be readonly or hidden or disabled for users without some permissions, but django doesn't allow me to dynamically set any of these attributes. My model: class PromocodePool(TimeStampedModel): start = models.DateTimeField() end = models.DateTimeField(null=True, blank=True) Form: class PromocodePoolForm(forms.ModelForm): promocodes = forms.FileField(widget=AdminFileWidget, required=False) # this field is non-model class Meta: model = PromocodePool fields = '__all__' Admin: @admin.register(PromocodePool) class PromocodePoolAdmin(admin.ModelAdmin): form = PromocodePoolForm list_display = ("get_start", "get_end") readonly_fields = (<some fields, tuple>) @admin.display(description="Start date") def get_start(self, obj): return _date(obj.start, formats.DATE_FORMAT) @admin.display(description="Start date") def get_end(self, obj): return _date(obj.end, formats.DATE_FORMAT) def get_readonly_fields(self, request, obj=None): if not request.user.has_perm("promocode.custom_permission"): self.readonly_fields += ("promocodes",) # this doesn't work return self.readonly_fields Im getting this error: Unable to lookup 'promocodes' on PromocodePool or PromocodePoolAdmin or PromocodePoolForm Btw if i rename my form, error text stays the same because the real "finish" form generates via django's ModelFormMetaclass and is called PromocodePoolForm and this form is not my form described above. Is there any way to dynamically disable this field? If it's matters, im using python … -
How to implement Two Factor Authentication in Django rest framework in social authentication?
In my Django project, I use DRF Social OAuth2 to do social authentication. Now my question is how to implement Two Factor Authentication when a user login by social authentication. -
Django display attribute of intermediary entity through parent entity
I am trying to reference an attribute from the Material_Requisition_Items intermediary entity through the Material_Requisition.reqItems ManytoManyField and have it displayed on HTML; however, it references the Item parent entity instead. Is there a way to reference attributes from the intermediary entity through the parent in Django HTML? models.py [Intermediary Entity] class Material_Requisition_Items(models.Model): reqID = models.ForeignKey("Material_Requisition", on_delete=models.CASCADE) itemID = models.ForeignKey('item.Item', on_delete=models.CASCADE) ... itemQuantity = models.PositiveIntegerField(default=0, null=True) [Parent Entity] class Material_Requisition(models.Model): ... reqItems = models.ManyToManyField( Item, through="Material_Requisition_Items", through_fields=('reqID', 'itemID'), related_name="mat_req_items" ) requisition_detail.html {% for item in object.reqItems.all %} <td>{{ item.itemID.itemName }}</td> <td>{{ item.itemQuantity}}</td> {% endfor %} views.py class RequisitionDetailView(LoginRequiredMixin, generic.DetailView): model = Material_Requisition template_name = "requisition/requisition_detail.html" context_object_name = "requisition" -
Request updating the state with an invalid payload in Django unit tests
a small question about Django unit tests. I'm only just starting out with Django so apologies if this might sound like a beginner question. But how can I test a scenario where I'm updating a state with an invalid payload in Django, with different fields missing each time? And then the request is rejected with a message this the request was invalid? My test code: def test_invalid_state_payload(self): # Given user = self.admin_user self.client.force_login(user) integration = AccountFactory(name="account", enabled=True, provider=str_to_kebab_case("account")) # When payload = { "enable_personal_payment_profile": True, "payment_profile_settings": [ { "payment_profile_id": "Some random ID", "send_to": "booker", }, { "payment_profile_id": "Another random ID", "send_to": "payment_profile_contact", }, ], } response = self.client.post( f"{self.url}/account/update_state", data=json.dumps(payload), content_type="application/json" ) # Then assert response.status_code == status.HTTP_200_OK # This is how far I have gotten with this. I'd like to assert that one of the # fields is missing and it raises an error but not entirely sure how to do this Help would be much appreciated. Thank you :) -
Django using mongodb _id
I want to use mongodb's self generated objectID, removing the django generated ID. How do I do this and will it cause an error that I don't know in the future? My ID line in models.I deleted this ID.: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) I will using mongo ID: _id:ObjectId("4864gh937m3oy3xa412w16a8") -
Django/Python - radio button value: check depending on model value & submitting value to view
I have an issue: I have a model that says whether autoreply (to send email automatically) is on or off. The model (that contains only 1 row) looks like this: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) the model contains only 1 row, with the default as above with auto = False and manual = True Now, what I want is that in the frontend: 2 radio buttons with "auto" and "manual" when either auto or manual is True, the radiobutton is checked The user can change this setting: they can choose to go to auto setting, click the submit button > this new value for auto is True will be send to views.py where it is used to change the first row in the AutoSendMail model. What I have so far is: mailindex.html <form action="" method="post" class="card"> {% csrf_token %} <div class="card-body"> <div class="form-group text-right"> <label class="form-label">Send E-mail Automatically</label> <input type="radio" name="autoapprove" value="On"> Manual <input type="radio" name="autoapprove" value="Off"> Auto </div> <div class="card-footer text-right"> <a href="{% url 'core:auto_send' %}" class="btn btn-secondary btn-sm">Submit</a> </div> </div> </form> views.py class AutoSendView(generic.TemplateView): model = AutoSendMail extra_context = {"mailbox_page": "active"} context_object_name = 'auto_send' template_name = 'core/mailbox/mailindex.html' def get(self, queryset=None, **kwargs): new_setting = AutoSendMail.objects.get(id=1) if … -
how can i implement admin login and logout using django rest framework?
i have been given a task to authenticate admin login programmatically and logout as well. I am able to to do login but on logged out when i check which user i am logging out it says AnonymousUser. How can i make sure i log out current user which is logged it. I am using django rest framework and testing it on postman @api_view(["POST"]) def adminLogin(request): if(request.method=="POST"): username = request.data["username"] password = request.data["password"] authenticated_user = authenticate(request,username=username, password=password) if authenticated_user != None: if(authenticated_user.is_authenticated and authenticated_user.is_superuser): login(request,authenticated_user) return JsonResponse({"Message":"User is Authenticated. "}) else: return JsonResponse({"message":"User is not authenticated. "}) else: return JsonResponse({"Message":"Either User is not registered or password does not match"}) @api_view(["POST"]) def adminLogout(request): print(request.user) logout(request) return JsonResponse({"message":"LoggedOut"}) -
django model structure (database structure)
I have one model many to one current state of this as follows: class A(models.Model): a_field = models.CharField() class B(models.Model): c_field = models.CharField() class C(models.Model): c_field = models.CharField() and they are related to D model class D(models.Model): a_field = models.ForeignKey(A) b_field = models.ForeignKey(B) c_field = models.ForeignKey(C) here there may be more related fields to the D model my questions are that is it a good database structure? or should I just do this class D(models.Model) object_id = models.IntegerField() in here there will be no related fields I will just save the ID can anybody answer to this question please? -
Understanding Django coming from R Shiny?
First of all, my apologies if this isn't the best place to ask this. My question isn't looking for an opinion of which one is better, but rather understanding what is going on as I am completely lost. I am familiar with R Shiny and its concept of reactivity, just writing a whole HTML page with the objects linked to functions all in one go. I am now trying to understand Django, but it has proven quite difficult for me throughout the tutorials. Background: Deployed basic apps internally at company using Shiny - the apps use authentication, collect data, push/pull to AWS S3, one linked to SQL database as well. Use HTML, SCSS and Javascript with Shiny. Know python to do Machine learning with it, now I am wanting to translate one of my apps to Django. In Shiny, I can literally use functions that will generate HTML and CSS once the app is running. I can describe "make a div here, with a button inside it, when the user presses it, change the background color of the div, wait 5 seconds and go back to original color". Shiny will then generate the HTML and use reactivity to check if … -
Django - How do to subtract two annotations with different models
a = Category.objects.annotate(total_products=Count('product')) b=Order.objects.values('category__name').annotate(total_approve=Sum('approve_quantity')).order_by('-total_approve') so I want to subtract a - b -
drf-spectacular post method not working with form field
I am using Django Rest Framework. And for documentation I am using drf-spectacular. But the problem I am facing is that when I am trying to submit using form, I can not submit. But I can submit using JSON type normally. This Does not Work: This Works: How can I make the form to work? It does not even let me submit the form. Also, How can I make the profile_pic as filefield? Below is my code: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Your project description', 'VERSION': '1.0.0', } serializers.py from rest_framework import serializers from app_restaurant import models class RestaurantSerializer(serializers.ModelSerializer): """ Restaurant Create Serializer """ class Meta: model = models.Restaurant fields = '__all__' extra_kwargs = { 'slug': {'read_only': True}, } views.py from rest_framework import generics from app_restaurant import serializers, models from app_user import apipermissions # Create your views here. class RestaurantCreateView(generics.CreateAPIView): """ Restaurant Creation View """ permission_classes = [apipermissions.IsOwner] serializer_class = serializers.RestaurantSerializer queryset = models.Restaurant.objects.all() -
Django with Nginx and Gunicorn prompt null warning
I am running Django project in server using Nginx and Gunicorn. When user visit the website, I can find the NULL warning message in server. Anyone know how to solve it? -
parse array of objects sent from frontend in python Django backend
I have a web app, backend using Django, frontend using normal HTML5. I the frontend, I use axios to send an array of objects via POST request. axios ({ method: 'POST', url: test_url, data: { [{title:1, isbn:1234},{title:2, isbn:5678}] } }) However, in the backend, I could not succeed in parsing the data send from frontend. def test_url(request): body = request.body.decode("utf-8") json_acceptable_string = body.replace("'", "\"") d = json.loads(json_acceptable_string) title = d.get('title') ... I got json decode error in the backend. How could I easily parse the array of objects sent from frontend in python? -
Django: Get all inline objects in Admin's save_model
I have two related (via foreignKey relation) models and created admin model for parent with inlines. In a certain use-case, I need to fetch all related models and use those to update 1 particular field for parent model. What is the efficient way to do it? My Models: class ParentModel(BaseModel): text = models.CharField() // This is generated from inline children's data ... class ChildModel(BaseModel): parent = models.ForeignKey(ParentModel, on_delete=models.RESTRICT) ... class ChildModelInline(TabularInline): model = ChildModel class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelInline] ... What I want is something similar to this: class ParentModelAdmin(admin.ModelAdmin): inlines = [ChildModelInline] ... def save_model(self, request, obj, form, change): inline_objects = <get_all_inline_objects> obj.text = <generate_text(inline_objects)> super(ParentModelAdmin, self).save_model(request, obj, form, change) -
CKEditor not rendering on Deploy
I installed CKEditor in my Django blog app and all worked fine in development. Once I deployed through Heroku the text editor window has disappeared from both the admin panel and the client front end, showing these errors in the console: Console Error Messages I have it in installed apps in settings.py My configs are CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', }, } Static Files are set as: STATIC_URL = "/static/" STATICFILES_STORAGE = ( "cloudinary_storage.storage.StaticHashedCloudinaryStorage" ) STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = "cloudinary_storage.storage.MediaCloudinaryStorage" CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "/media/" And I have path("ckeditor/", include('ckeditor_uploader.urls')), set up in my urls.py It has also been imported into my models.py, I have it in my requirements.txt and I have ran the collectstatic command. Any suggestions please? -
Race condition when two different users inserting new records to database in Django
There is a race condition situation, when I want to create a new instance of model Order. There is a daily_id field that everyday for any category starts from one. It means every category has its own daily id. class Order(models.Model): daily_id = models.SmallIntegerField(default=0) category = models.ForeignKey(Categoty, on_delete=models.PROTECT, related_name="orders") declare_time = models.DateField() ... } daily_id field of new record is being calculated using this method: def get_daily_id(category, declare_time): try: last_order = Order.objects.filter(declare_time=declare_time, category=category).latest('daily_id') return last_order.daily_id + 1 except Order.DoesNotExist: # If no order has been registered in declare_time date. return 1 The problem is that when two different users are registering orders in the same category at the same time, it is highly likely that the orders have the repetitive daily_id values. I have tried @transaction.atomic decorator for post method of DRF APIView and it didn't work! -
returning only one response from the database in Django rest-framework
I'm trying to return all the results from the SQL using this approach I'm able to retrieve it but its the static one. I have tried looping the result_set but its returning only the first response out of 5 responses but I want to return all the 5 response Here, What I have tried expected response: [{"Value8":"Avail-On queue","Value1":"Avail-On queue"},{"Value8":"Coaching","Value1":"Coaching"},{"Value8":"Huddle","Value1":"Huddle"},{"Value8":"Outage","Value1":"Outage"},{"Value8":"Training","Value1":"Training"}] views.py: @api_view(['GET']) def GetClaimsActivity(request, UserId): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaimsPlusActivity] @UserId=%s', (UserId,)) result_set = cursor.fetchall() data = [] # for row in result_set: #data.append({ #'Value8':row[0], #'Value1':row[0], #}) #return Reponse(data) data = [] data.append({ 'Value8':result_set[0][0], 'Value1':result_set[0][0], }) data.append({ 'Value8':result_set[1][0], 'Value1':result_set[1][0], }) data.append({ 'Value8':result_set[2][0], 'Value1':result_set[2][0], }) data.append({ 'Value8':result_set[3][0], 'Value1':result_set[3][0], }) data.append({ 'Value8':result_set[4][0], 'Value1':result_set[4][0], }) return Response(data) -
Conditionally return JSON or XML response from Django django-rest-framework's class based view
How can i get response ap per body request passing output_format = 'json' or 'xml'. It's only return one type of response. How can i get both response as per condition. Below is My code. djangorestframework==3.13.1 Setting.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework_xml.renderers.XMLRenderer', ] } views.py class AddressAPI(APIView): renderer_classes = (XMLRenderer, JSONRenderer) def post(self, request): try: serializer = GeoLocationSerializer(data=request.data) if serializer.is_valid(): address = serializer.data['address'] output_format = serializer.data['output_format'] address_body = format_address(address) url = f"https://maps.googleapis.com/maps/api/geocode/json?address={address_body}&key={api_key}" response = requests.request("GET", url) source = response.text data = json.loads(source) for source in data['results']: if output_format == 'json' or output_format == 'JSON': # print(serializer.data) return Response({ 'coordinates' : source['geometry']['location'], 'address' : address, }) elif output_format == 'xml' or output_format == 'XML': return Response({ 'coordinates' : source['geometry']['location'], 'address' : address, }) else: return Response({ 'message' : 'Invalid output_format' }) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(e) -
Getting HTTP/1.1" 500 27 when debug set to FALSE in my django local environment
I have the settings.py like below Basically our DEBUG will be set to TRUE. But since to the production we need to set FALSE, we have to handle the code to set debug FALSE. even with debug=FALSE the app should work as it is. But in my case, because debug is set to FALSE , my app is giving HTTP/1.1" 500 27 error. May i know what i am missing here. import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'MyApp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django jwt and React redirect to different pages for different users after log in
I have 2 roles which are member and staff, and i want to redirect to the different pages depend on the users' roles using username and password e.g. after logging in as a member would redirect to member page and as a staff would redirect to onlystaff page. How I can do it. I'm using React Django JWT and Material UI. Sorry for my bad English. the code: axios.js const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); const now = Math.ceil(Date.now() / 1000); … -
Error 502: Deploy Django application with Gunicorn and Nginx
I have developed a web application with Django and I am trying to publish it in a virtual machine created with Azure. To do that I'm using the following software stack: Ubuntu (20.04) Django (3.0.7) Virtualenv (20.0.17) Gunicorn (20.1.0) Nginx (1.18.0) To deploy the app I followed that guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 My django project folders are organized as follows: home/ ├─ useradmin/ │ ├─ myproject/ │ │ ├─ proj/ │ │ │ ├─ settings.py │ │ │ ├─ urls.py │ │ │ ├─ wsgi.py │ │ │ ├─ ... │ │ ├─ static/ │ │ ├─ templates/ │ │ ├─ venv/ │ │ ├─ manage.py │ │ ├─ ... This is my /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=useradmin Group=www-data WorkingDirectory=/home/useradmin/myproject ExecStart=/home/useradmin/myproject/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/useradmin/myproject/myproject.sock proj.wsgi:application [Install] WantedBy=multi-user.target This is my /etc/nginx/sites-available/myproject: server { listen 80; server_name mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/useradmin/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/useradmin/myproject/myproject.sock; } } When I navigate to mydomain.com I get a 502 Bad Gateway error. If I check the Nginx logs by running "sudo tail -F /var/log/nginx/error.log" I see the following error: 2022/03/16 08:27:33 [crit] 64480#64480: *3 connect() to … -
gunicorn active: failed, why don`t active gunicorn service?
i hav ubuntu server 20.04 and a django project i set /etc/systemd/system/gunicorn.socket Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target and i have this error gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:49:31 +0330; 12min ago TriggeredBy: ● gunicorn.socket Process: 1891 ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bi> Main PID: 1891 (code=exited, status=217/USER) Mar 16 11:49:31 srv174847 systemd[1]: Started gunicorn daemon. Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed to determine user credentials: No such process:: Failed to determine user credentials: No such process Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed at step USER spawning /home/sammy/myprojectdir/myprojectenv/bin/gunicorn: No such process Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Failed with result 'exit-code'. please help me -
how to get the number of row in a csv file in django
How can i solve? how can i get the count of no. of rows in a csv file using django.how can i solve this issue. while wrote code below its not working it showing the no.of. columns not row. Here my view def upload_csv(request): template = "upload_csv.html" if request.method == "GET": return render(request,template) csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.info(request,'* This is not a csv file') return render(request,template) data_set = csv_file.read().decode('UTF-8') data =io.StringIO(data_set) next(data) for row in csv.reader(data,delimiter=',',): Company.objects.get_or_create( name = row[0], hr_name =row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) context={} file_name = request.FILES['file'].name count = len(list(row)) company =UploadCsv( file_name=file_name, no_of_row =count, user = request.user ) company.save() return render(request, template,context) -
Can't Install xmlsec for Mac
I'm new to django. i am tring to implement python3-saml which requires Xmlsec. i am trying to install it Using "pip install xmlsec" on my virtal environment. but throwing this error. Collecting xmlsec Using cached xmlsec-1.3.12.tar.gz (64 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: lxml>=3.8 in /opt/anaconda3/envs/conda_saml_env/lib/python3.10/site-packages (from xmlsec) (4.8.0) Building wheels for collected packages: xmlsec Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [14 lines of output] running bdist_wheel running build running build_py package init file 'src/xmlsec/__init__.py' not found (or not a regular file) creating build creating build/lib.macosx-10.9-x86_64-3.10 creating build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/__init__.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec running build_ext error: xmlsec1 is not installed or not in path. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for xmlsec Failed to build xmlsec ERROR: Could not build wheels for xmlsec, which is required to install pyproject.toml-based projects I … -
How to get foreign key detailed values based on id in html template in django
In Models.py class Interview(models.Model): Current_Date = models.DateField(auto_now_add=True ) User = models.ForeignKey(User,on_delete=models.CASCADE) Recuirement = models.ForeignKey(Client_Requirement,on_delete=models.CASCADE) Candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) Interviewer = models.ForeignKey(Interviewer, on_delete=models.CASCADE) Interview_Mode = models.ForeignKey(Interview_Mode, on_delete=models.CASCADE) Date = models.DateField() Time = models.TimeField() Interview_status = models.ForeignKey(Interview_status, on_delete=models.CASCADE) Interview_Location = models.CharField(max_length=30) Comments = models.TextField(max_length=1000) Update_Date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.Interviewer) in Views.py def BD(request): Interview_data = Interview.objects.all() context={'Interview_data':Interview_data} return render(request,'Sub/BD.html', context) How i can get all the data individual details of Recuirement, Candidate table In for loop tag in django