Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form widget - Add suffix while keeping the NumberInput
I have a form input on body height. I would like to put 'cm' after the height number (e.g. 183cm instead of just selecting 183) but keep it as a NumberInput. Is it possible to add the suffix in the widget? I have the following form.py: from django import forms from .models import Account class RegistrationForm(forms.ModelForm): body_height = forms.NumberInput(attrs={'min':120,'max':230,'step':1, 'required':False,}) class Meta: model = Account fields = ['body_height','otherfields'] def __init__(self, *args, **kwargs): self.fields['body_height'].widget.attrs['placeholder'] = 'Your height (centimeters)' -
How to assign default value of the model based on the value of ForeignKey
I have the Account model were I store information about preferred units. However I also want to allow user to change the units for particular exercise which by default should be Account.units. Here are my models: class Account(models.Model): """Model to store user's data and preferences.""" UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False) units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=UNIT_CHOICES[0], null=False, blank=False) weight_metric = models.FloatField(null=True, blank=True) height_metric = models.FloatField(null=True, blank=True) weight_imperial = models.FloatField(null=True, blank=True) height_imperial = models.FloatField(null=True, blank=True) def __str__(self): return self.owner.email class CustomExercise(models.Model): UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False) preferred_units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=owner.units, null=False, blank=False) # <- throws an error that "ForeignKey doesn't have units attribute." name = models.CharField(max_length=255, null=False, blank=False) measure_time = models.BooleanField(default=False) measure_distance = models.BooleanField(default=False) measure_weight = models.BooleanField(default=False) measure_reps = models.BooleanField(default=False) def __str__(self): return f'{self.owner}:{self.name}' As posted in code sample I tried to get that default value from ForeignKey, which not unexpectedly did not work out. So my question is: what is the correct solution to implement this kind of feature? -
VsCode not Auto-importing Django depenencies
I'm learning Django and working with VsCode. In PyCharm, the imports are working fine. PyCharm importing However in VsCode: VsCode importing Is VsCode just not capable of this? Or is there something iffy with my configuration? I have the correct Python interpreter configured as well. I have Pylance installed and it suggests imports automatically for some other things, rather unhelpfully usually. e.g., VsCode importing unhelpful I have tried settings some options in settings.json. The python.analysis.extraPaths adding the path to django on the Python installation. I have tried python.analysis.indexing set to true as well. I haven't found any other solutions. -
Django APIView: how to display calculated value
I have to display a calculated value in APIVIEW, but I can't figure out how to set up the view, it's giving me an error. The code, that returns a simple JSON is working fine: def protein_coverage(request, protein_id): try: proteins = Protein.objects.filter(protein=protein_id) domain_length = 0 coverage = domain_length / protein_length except Protein.DoesNotExist: return HttpResponse({'message': 'This Protein does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProteinCoverageSerializer(coverage) return JsonResponse(serializer.data,safe=False) I tried this for the APIView: class ProteinCoverage(generics.RetrieveAPIView): serializer_class = ProteinCoverageSerializer def get_queryset(self): pk = self.kwargs['protein_id'] proteins = Protein.objects.filter(protein=pk) domain_length = 0 coverage = domain_length / protein_length return coverage But it's giving me an error: Expected view ProteinCoverage to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I'm not sure, which API is suitable for this situation and how to pass a single variable to it. I also checked the documentation, but it's not clear. How do I convert this JsonResponse to APIView? -
Making Password First name in signup page in Django [closed]
Is there a way to not show password in the signup page and make the password the first name by default in Django and they will be able to login with that default password which is there first name I tried using the AbstractBaseUser But it did not Work -
Create multiple model instances upon creation of another model
What I am trying to achieve is the following: The user searches for a keyword in a form. The search query is saved in a model called TweetSearch. When the search is submitted a function get_tweets() will be run which scrapes tweets with the keyword that the user submitted. These tweets must be saved in a model called TweetInstance. Then some data from TweetInstance is shown in a dashboard. I don't know how to create instances of multiple models in one view, so I added a view in between the searchform and the dashboard that runs the function get_tweets() and adds them to the database. This does not work well and there must be a better way to do this. Can anyone help me? I tried the following: models.py: class TweetSearch(models.Model): from datetime import datetime, timedelta search_term = models.CharField(max_length=200, blank=True) QUERY_CHOICES = ( ('t', 'in tweet'), ('h', 'in hashtag'), ('u', 'username'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4) query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t') start_default = datetime.now() - timedelta(days=30) start_date = models.DateTimeField(default=start_default) end_date = models.DateTimeField(default=datetime.now) language = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): … -
Websockets won't work on docker with nginx
I have a problem with a real-time chat application on Django. The websockets won't work on nginx server. Am I missing something? The app only says: /ws/socket-server/ not found nginx.conf upstream project { server web:8000; } server { listen 80; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } #path to proxy my WebSocket requests location /ws/socket-server/ { proxy_pass http://project; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } asgi.py """ ASGI config for project project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import scrumboard.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. from django.template.context_processors import media BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = int(os.environ.get("DEBUG", default=0)) # 'DJANGO_ALLOWED_HOSTS' should be … -
Building wheel for lxml (setup.py): finished with status 'error'
I have this error while running docker Everything works in server but locally lxml finishes with this error: #0 55.92 Stored in directory: /root/.cache/pip/wheels/02/f8/c2/4a8e9dce6caefe8931213e951f7d1b19e6a7d86fc2becc228e #0 55.92 Building wheel for lxml (setup.py): started #0 57.58 Building wheel for lxml (setup.py): finished with status 'error' #0 57.60 error: subprocess-exited-with-error #0 57.60 #0 57.60 × python setup.py bdist_wheel did not run successfully. #0 57.60 │ exit code: 1 #0 57.60 ╰─> [88 lines of output] #0 57.60 Building lxml version 4.6.3. #0 57.60 Building without Cython. #0 57.60 Building against libxml2 2.9.10 and libxslt 1.1.34 #0 57.60 running bdist_wheel #0 57.60 running build #0 57.60 running build_py #0 57.60 creating build #0 57.60 creating build/lib.linux-x86_64-cpython-311 #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/sax.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/cssselect.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/builder.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 copying src/lxml/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-cpython-311/lxml/includes #0 57.60 creating build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-cpython-311/lxml/html #0 57.60 copying src/lxml/html/diff.py … -
get the id of a related field and save data
I'm kinda new to DRF, I am building a database for attendance. I want to save an instance of AttendanceSlot in my Attendance but I don't know how to get id, so i can save it... models.py class AttendanceSlot(models.Model): department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE) course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE) lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE) date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True) start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) longitude = models.CharField(_("longitude"), max_length=50) latitude = models.CharField(_("latitude"), max_length=50) radius = models.CharField(_("radius"), max_length=50) def __str__(self): return '{0}'.format(self.course_id.course_code) class Attendance(models.Model): slot_id = models.ForeignKey("attendance.AttendanceSlot", verbose_name=_("attendance slot"), on_delete=models.CASCADE) student_id = models.ForeignKey("students.Student", on_delete=models.CASCADE) performance = models.CharField(max_length=50) serializers.py class AttendanceSerializer(serializers.ModelSerializer): # student_id = serializers.SlugField(read_only=True) slot_id = serializers.PrimaryKeyRelatedField(queryset=AttendanceSlot.objects.all(), many=False) class Meta: model = Attendance fields = ['student_id', 'slot_id', 'performance'] views.py class Attendance(ListCreateAPIView): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def get_queryset(self, *args, **kwargs): id = self.kwargs['pk'] slot = AttendanceSlot.objects.get(id=id) return slot def perform_create(self, serializer): serializer.save(user = self.request.user, slot_id=self.get_queryset()) return super().perform_create(serializer) urls.py path('<int:pk>/', views.Attendance.as_view(), name='attendance'), -
Django - Storing user info sessions vs database
In my django website I have a login system which uses sessions to keep the user logged in across all pages. I would like to store recently viewed items for users if they are logged in or browsing as a guest user. When a user is logged in I would like the user to see their recently viewed items even when they access my website on another device. I understand that if a user is browsing as a guest recently viewed items would be stored locally in the browser. Would i need to store recently viewed items in a database so that it can be accessed and displayed on other devices. Or is there a way to achieve this with the use of sessions. example of request.session dict { "user_id":-1, # (-1), flag value when no user is logged in (browsing as guest) "recently-viewed":['sw0001a','sw0036a',...], "login_attempts":2, } -
serve Static Files and Media Files of Django app in Production using NGINX
The project works correctly, but I get a 404 error when reading static files! my settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/home/static' MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') nginx.conf: user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream main { server 127.0.0.1:8000; } server { listen 80; server_name localhost; charset utf-8; location /static/ { alias /home/static; } location / { proxy_pass http://main; } } } I`m not using gunicorn. are my settings wrong? -
I have a django website hosted on heroku so I want to setup site to site vpn connection between fortgate vpn. My site and another site. How?
I have a djano app hosted on heroku an I want it to exchange data with another site that is using Fortigate vpn. So I am required to setup my vpn connection to my site but heroku's private space and shiel are to expensive for me. Please help. I could find any vpn that is easy to configure its all complex. -
Django - Disable editing via view button
I am making a customer portal on django and on the admin panel i have created a list for all the users in the database. Apart from that i have also added 3 buttons in my table to View, Edit and Delete as shown: Now the problem is that when i click edit or delete button the code runs as it is intended to do. But when i click the view button it still allows the person to modify the details. I only want to use it as read-only. Can someone please help? This is my admin.py from django.contrib import admin from .models import Customer from .forms import CustomerForm from django.http import HttpResponse from django.utils.html import format_html # Write your models here class CustomerAdmin(admin.ModelAdmin): form=CustomerForm list_display = ['id','first_name','last_name','profile_picture', 'gender', 'date_of_birth', 'email', 'phone_number', 'address', 'marry_status','country','state','city','view_button', 'edit_button', 'delete_button'] list_display_links = ['id'] ordering = ('id',) def view_button(self, obj): return format_html('<a class="button" style="background-color: darkgreen;" " href="/admin/customer_form/customer/{}/">View</a>'.format(obj.id)) view_button.allow_tags = True view_button.short_description = 'View' def edit_button(self, obj): return format_html ('<a class="button" style="color: black; background-color: yellow;" href="/admin/customer_form/customer/{}/change/">Edit</a>'.format(obj.id)) edit_button.allow_tags = True edit_button.short_description = 'Edit' def delete_button(self, obj): return format_html('<a class="button" style="background-color: #ba2121;" href="/admin/customer_form/customer/{}/delete/">Delete</a>'.format(obj.id)) delete_button.allow_tags = True delete_button.short_description = 'Delete' admin.site.register(Customer, CustomerAdmin) -
No reverse match at /create Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name
Reverse for 'employees-list' not found. 'employees-list' is not a valid view function or pattern name. im getting the error like this what can i do plz any one resolve thisenter image description here getting like want to redirect to the employees-list ... -
User object has no attribute 'code', when code is not passed to User.objects.create
Im using Django Rest Framework to create a view that verifies an otp. Currently, it works just fine. models.py class User(AbstractUser): phone_number = PhoneNumberField(blank=True) def __str__(self) -> str: return f"{self.username}" views.py class VerifyOTPCode(APIView): permission_classes=[AllowAny] def post(self, request): serializer = UserOTPCodeSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors) serializers.py class UserOTPCodeSerializer(serializers.ModelSerializer): code = serializers.IntegerField() class Meta: model = User fields = ("first_name", "last_name", "email", "phone_number", "code") def validate(self, data): code, phone_number = str(data['code']), data['phone_number'] if is_six_digits(code) and is_otp_approved(code, phone_number): return data raise serializers.ValidationError('Code was not approved') def create(self, validated_data): del validated_data['code'] return User.objects.create(**validated_data) However, I want to use a generic for the view instead, so I tried refactoring it into the following views.py class VerifyOTPCode(generics.CreateAPIView): permission_classes= [AllowAny] serializer_class= UserOTPCodeSerializer Now, when I try to hit the endpoint, I get an error at create, that the User object has no attribute code, even though create removes code from validated_data, and another thing is that even with the error, a User object still does get created. Why is this error occurring and how can I fix it? Internal Server Error: /user/register/verify-otp/ Traceback (most recent call last): File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py", line 97, in … -
django rest framework serializer raising invalid errors
class AdvanceSearchSerializer(serializers.Serializer): all_of_these_words = serializers.CharField(allow_null=True, required=False) this_exact_phase = serializers.CharField(allow_null=True, required=False) any_of_these_words = serializers.CharField(allow_null=True, required=False) class myclass(viewsets.Viewsets): serializer = AdvanceSearchSerializer(data = request.data) it works fine. for now im passing data from post request in postman as form-data but when I change it to raw and wih json format it raising the below errors. show that this field is required even though i have set it to null true. { "response": false, "return_code": "field_error", "result": [], "message": { "all_of_these_words": [ "This field may not be blank." ], "this_exact_phase": [ "This field may not be blank." ], "any_of_these_words": [ "This field may not be blank." ] } } -
How to update dynamic form fields in Django
The users can dynamically add more fields and edit fields to the forms. The problem is I don't know how exactly I should pass the dynamic multiple dynamic 'city' ids and edit-update them. Models.py class Cities(models.Model): cityname = models.CharField(max_length=5000, null = True, blank = True) owner = models.ForeignKey(User, null = True, on_delete=models.CASCADE) relcountry = models.ForeignKey(Country, null = True, on_delete=models.CASCADE) Index.html <form method = "post" action='cityupdate/{{city.id}}' enctype="multipart/form-data"> {% csrf_token %} {% for city in cities %} <input type="text" name = "{{city.id}}" value= "{{city.name}}" </input> {% endfor %} <input type="submit" name = "cityupdate" value= "Update" </input></a> </form> Urls.py path('cityupdate/<str:id>',views.cityupdate,name='pk') Views.py def cityupdate(request,pk): if request.method == 'POST' and 'cityupdate' in request.POST: ----------------- I need help to complete the views.py code -
How can I send Boolean fields via Django send_mail
I am fairly new to Python and Django, I am trying to use the build in send_mail and having a few issues with the boolean fields I want to be included in the email that is sent, I have had no issues with the form being printed to the terminal for testing but as soon as I added the other fields that are on the form(b oolean fields) I am getting the following error (TypeError: sequence item 4: expected str instance, bool found), probably an easy fix but I am struggling to find anything on the web that will help. I am not fussed is the boolean fields that are False are excluded on the email as this is not relevant, any help would be much appreciated. I have managed to get the email side working when it comes to Firstname, Lastname, Email, Phone, but when adding the boolean fields I am getting an error. Views.py from django.shortcuts import render, redirect from django.http import JsonResponse from main.models import WFHSHEET from django.http import HttpResponse, response, HttpResponseRedirect from .forms import WFHLIST, RETURNLIST from django.core.mail import send_mail, BadHeaderError def home(response): return render(response, 'home.html', {}) def wfhsheet(request): if request.method == 'POST': form = WFHLIST(request.POST) … -
Can't show specific model field in my HTML template
On my main page i want to show a category just like {{ post.body }} but instead {{ post.body }} would be {{ post.category }} here. {% extends "base.html" %} {% block title %}Articles{% endblock title %} {% block content %} {% for post in post_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold"><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a> | </span> &middot; <span class="text-muted">by {{ post.author }} | {{ post.created_at }}</span> </div> <div class="card-body"> <!-- Changes start here! --> <p>{{ post.body }}</p> <p>{{ post.category }}</p> <a href="{% url 'post_edit' post.pk %}">Edit</a> | <a href="{% url 'post_delete' post.pk %}">Delete</a> | <a href="{% url 'category_list' %}">Category</a> </div> <div class="card-footer"> {% for comment in post.comment_set.all %} <p> <span class="font-weight-bold"> {{ comment.author }} &middot; </span> {{ comment }} </p> {% endfor %} </div> <!-- Changes end here! --> </div> <br /> {% endfor %} {% endblock content %} but cannot to figure out how. But cannot figure out how. Here is my models from django.conf import settings from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) … -
I can't get Django custom error pages to work
I am trying to get custom error pages (404 & 500) to work in my Django application. So far I have the following: urls.py handler404 = views.error_404 handle500 = views.error_500 views.py def error_500(request, exception): return render(request, '500.html', status=500) def error_404(request, exception): return render(request, '404.html', status=404) DEBUG is set to FALSE. However when I try access an error page I get the following error: "A server error occurred. Please contact the administrator." Which (obviously) is not my error template. Any help appreciated! -
Django localisation, internationalization
How to add different language buttons so that it translate my django website online? Or any other method? I want to translate my whole website. In easy way -
I hosted a django website on namecheap but it has changed structure
I have hosted a django business directory system on namecheap but the home page has changed. That's my localhost display of the front end [This is the display of app on thena.thenadaka.com][2] I checked the console to see if there's any static file that is not served but all are served. I know am supposed to learn Docker to ease this but for now your help with be paramount. The code for both is exactly the same, i also disabled Cache under Network on localhost so the locally hosted site doesn'd display cached data -
Django API rejects file
I'm trying to send a csv file to my Django API and response with process data, but when I send it, I get the error: django.utils.datastructures.MultiValueDictKeyError: 'file' this is my react code: import { useState } from 'react'; import './App.css'; function App() { const [file, setFile] = useState(null); const uploadFiles = e =>{ setFile(e); } const insertFile = async() => { const f = new FormData(); f.append("file", file); await fetch( 'http://localhost:8000/api/', { method: 'POST', headers: { 'content-type': 'multipart/form-data' }, body: f, }) .then((response) => response.json()) .then((data)=>{ console.log(data); }) .catch(error=>{ console.log(error); }); } return ( <> <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/> <button onClick={()=>insertFile()}>Insertar</button> </> ); } export default App; And this is my view.py file that will process the information, for now, I just want to get the csv info in the frontend side, so the logic of how to process data doesn't matter right now. @api_view(['POST']) def eda(request): file = request.FILES['file'] data = [] with open(file, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for rows in csvReader: data.append(rows) response = { 'csvData': data } return Response(response) -
Get a Foreign Key value with django-rest-framework serializers
I'm using the django rest framework to create an API. models.py class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('Genin', 'Genin'), ('Chunin', 'Chunin'), ('Jonin', 'Jonin'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default="Genin", choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName serializer.py from appemployee.models import EmployeeModel,DepartmentModel class EmployeeSerialize(serializers.ModelSerializer): class Meta: model = EmployeeModel fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): emp_dept = serializers.CharField(source='DepartmentModel.DeptName') class Meta: model = EmployeeModel fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept') views.py class EmployeeTable(APIView): def get(self,request): try: emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerialize(emp_obj,many=True) except Exception as err: return Response(err) return Response(empserializer.data) this would provide me with: [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 1 }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 2 }, { "EmpID": 3, "EmpName": "Hiruzen Sarutobi", "Email": "hiruzen.sarutobi@konaha.com", "EmpLevel": "Jonin", "EmpPosition": 5 } ] what i really want is [ { "EmpID": 1, "EmpName": "Hashirama Senju", "Email": "hashirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" }, { "EmpID": 2, "EmpName": "Tobirama Senju", "Email": "tobirama.senju@konaha.com", "EmpLevel": "Jonin", "DeptName": "Hokage" … -
any docs abot django + htmx for JSON
I found many reference (docs and video) about how to use htmx in django for doing parent-child crud UI. Is there any docs or excample on how to do 'dynamicaly added form field' with just single model class? My case is to make an app that take care of business mailing templates. models.py class MailTemplate(models.Model): code = models.CharField(verbose_name='Code',max_length=10, unique=True) name = models.CharField(verbose_name='Name', max_length=30) docx = models.FileField(verbose_name='docx File') dataschema = models.TextField(null=True, blank=True) class Mail(models.Model): mailtemplate = models.ForeignKey(MailTemplate, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) data = models.TextField(null=True, blank=True) What I want is a form to add/edit record of 'MailTemplate'. that form will 'look like' 'stacked inline' but the 'child' is from parsing MailTemplate.dataschema. Example of MailTemplate.dataschema : [ { "name": "to", "label": "To", "type": "string", }, { "name": "platenumber", "label": "Plate Number", "type": "string", }, ] I really appreciate any help. Sincerely -bino-