Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
some import in the project get error separated by newlines or semicolons
so i have many import in django project. suddenly, the import got red mark (like error sign) but i don't change anything. can someone fix it so it's not detect as error? i want to fix the error, so the color code can be appear again -
bad request 400 on POST request (Django React and axios)
I have a problem with Bad Reqauest 400 when trying to register new user in my app. I am using Django 4 and React 18. I've set up CORS headers and I added localhost:3000. I also checked login and it works fine. I have a problem with registration. I am new to React and I am not sure what is wrong with the code. When I check comsole I get the following error: my django files are below: serializers.py class UserRegistrationSerializer(serializers.ModelSerializer): # Confirm password field in our Registration Request password2 = serializers.CharField(style={'input_type':'password'}) class Meta: model = User fields=['email', 'password', 'password2'] extra_kwargs={ 'password':{'write_only':True} } # Validating Password and Confirm Password while Registration def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and Confirm Password doesn't match") return attrs def create(self, validate_data): return User.objects.create_user(**validate_data) views.py def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class UserRegistrationView(APIView): renderer_classes = [UserRenderer] def post(self, request): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = get_tokens_for_user(user) return Response({'token':token, 'msg':'Registration Successful'}, status=status.HTTP_201_CREATED) my react files are below: client.js import config from './config'; import jwtDecode from 'jwt-decode'; import * as moment from 'moment'; const axios = require('axios'); class DjangoAPIClient … -
How to combine two forms with one submit?
I have two forms and one submit button. But the content is only showing in one textbox. And if I try to upload a file with the second form. There is no output. SO I have the template like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ excel_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content.excel" cols="70" rows="25"> {{content.excel}} </textarea> </div> </div> </div> <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </form> </div> </span> </div> </body> </html> and the views.py: lass ReadingFile(View): def get(self, *args, **kwargs): pdf_form = UploadFileForm() excel_form = ExcelForm() return render(self.request, "main/controle_punt140.html", { 'pdf_form': pdf_form, "excel_form": excel_form }) def post(self, *args, **kwargs): pdf_form = UploadFileForm( self.request.POST, self.request.FILES) excel_form = ExcelForm( self.request.POST, self.request.FILES) content = '' content_excel = '' if pdf_form.is_valid() and … -
How to merge two queryset on specific column
Hello I am using a postgres database on my django app. I have this model: class MyFile(models.Model): uuid = models.UUIDField( default=python_uuid.uuid4, editable=False, unique=True) file = models.FileField(upload_to=upload_to, null=True, blank=True) path = models.CharField(max_length=200) status = models.ManyToManyField(Device, through='FileStatus') user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, blank=True) when = models.DateTimeField(auto_now_add=True) canceled = models.BooleanField(default=False) group = models.UUIDField( default=python_uuid.uuid4, editable=False) What I want is to group my MyFile by group, get all the data + a list of file associated to it. I managed to get a group associated to a list of file with MyFile.objects.all().values('group').annotate(file=ArrayAgg('file', ordering='-when')) which is giving me a result like: [{'group': 'toto', 'file':['file1', file2']}, ...] I can also get all my MyFile data with: MyFile.objects.all().distinct('group') What I want is to get a result like: [{'group': 'toto', 'file':['file1', file2'], 'when': 'ok', 'path': 'ok', 'user': 'ok', 'status': [], canceled: False}, ...] So I fought I could merge my two queryset on the group column but this does not work. Any ideas ? -
FieldError: Invalid field name(s) given in select_related: 'posts'. Choices are: (none)
I am getting this error when using the method select_related. FieldError: Invalid field name(s) given in select_related: 'posts'. Choices are: (none) models.py class Group(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) class Meta: default_related_name = 'groups' class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) group = models.ForeignKey( Group, blank=True, null=True, on_delete=models.SET_NULL, ) class Meta: default_related_name = 'posts' views.py class GroupPostView(DetailView): model = Group queryset = Group.objects.select_related('posts') # queryset = Group.objects.all() slug_field = 'slug' But if you use all(), then the request is successful and there is no error. -
Django model import from app to onether model
Good Day. Could you please give me a directie. I has extended basic User model and I need to import it to another app Django. Could you please explain me a bit how and there is my mistake.? models.py user extended model from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) hb_photo = models.ImageField('User photo', default='incognito.png', upload_to='users/%Y/%m/%d/') hb_phone = models.CharField('Phone number', max_length=50, null=True) hb_department = models.CharField('Department name', max_length=50, null=True) def __str__(self): return f'User profiles {self.user.first_name} {self.user.last_name}' models.py there i truing to import User extendet model from higabase.members.models import Profile class NewPlacement(models.Model): np_nationality = CountryField('Nationality', null=True) np_coming_date = models.DateField('Coming date', null=True) ex_test_user = models.ForeignKey(User, on_delete=models.PROTECT) location = models.ForeignKey('FeelFlexLocation', on_delete=models.PROTECT) ff_hb_photo = models.ManyToManyField('User photo', default=Profile.hb_photo) ff_hb_phone = models.ManyToManyField('Phone number', default=Profile.hb_phone) ff_hb_department = models.ManyToManyField('Department name', default=Profile.hb_department) Then i truing to makemigrations. from higabase.members.models import Profile ModuleNotFoundError: No module named 'higabase.members' (venv) PS C:\Users\Feelflex\Desktop\TESTING2\higabase> I do not understend how i can fix it :( -
How to output fields to html template correctly from User model in Django ORM?
Task: Create a Django SQL query, pulling out only the required fields. Submit them to the template. I have a Post model with a foreign key to a standard User model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts" ) Here is the required fragment in the HTML template, where you need to insert the author's name: {% for post in posts %} <h3> Author: {{ post.author.first_name }}, Date: {{ post.pub_date|date:'d M Y' }} </h3> view function: from django.shortcuts import render from .models import Post def index(request): latest = ( Post .objects .order_by('-pub_date')[:10] .select_related('author') .values('pub_date', 'author__first_name') ) return render(request, 'index.html', {'posts': latest}) Here's what the page fragment looks like on the local server: template And here is the final sql query shown by django debug toolbar: Query In the user table, I have one user and all posts are related to him. If I do not use .values in the view, then all the attributes of the author that I request in the template are displayed perfectly (for example, last_name, username, get_full_name()), but then sql requests all the fields of the user table (as … -
How to make html drag and drop only accept videos
I'm using this HTML code to upload video files to my website. <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-6"> <form method="post" action="#" id="#"> {% csrf_token %} <div class="form-group files"> <label class="d-flex justify-content-center">Upload Your File </label> <input type="file" class="form-control" multiple="" accept="video/mp4,video/x-m4v,video/*"> </div> <div class="row row-cols-auto"> <div class="col mx-auto my-2"> <button class="btn btn-primary" type="submit">Upload</button> </div> </div> </form> </div> </div> </div> and this CSS .files input { outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; padding: 120px 0px 85px 35%; text-align: center !important; margin: 0; width: 100% !important; } .files input:focus{ outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; border:1px solid #92b0b3; } .files{ position:relative} .files:after { pointer-events: none; position: absolute; top: 60px; left: 0; width: 50px; right: 0; height: 56px; content: ""; background-image: url(https://image.flaticon.com/icons/png/128/109/109612.png); display: block; margin: 0 auto; background-size: 100%; background-repeat: no-repeat; } .color input{ background-color:#f1f1f1;} .files:before { position: absolute; bottom: 10px; left: 0; pointer-events: none; width: 100%; right: 0; height: 57px; content: " or drag it here. "; display: block; margin: 0 auto; color: #2ea591; font-weight: 600; text-transform: capitalize; text-align: center; } when I … -
django.template.exceptions.TemplateSyntaxError: 'bootstrap_field' received some positional argument(s) after some keyword argument(s)
i was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able too ` i was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able tooC:\Users\hp\Desktop\fastparcel\core\templates\sign_in.html, error at line 25 'bootstrap_field' received some positional argument(s) after some keyword argument(s) {% bootstrap_field form.username show_lable=False placeholder ="Email" %}` {% extends 'base.html' %} {% load bootstrap4 %} {% block content%} <div class="container-fluid mt-5"> <div class="justify-content-center"> <div class="col-lg-4"> <div class="card"> <div class="card-body"> <h4 class="text-center text-uppercase mb-3"> <b> {% if request.GET.next != '/courier/'%} Customer {% else %} Courier {% endif %} </b> </h4> <form action="POST"> {% csrf_token %} {% bootstrap_form_errors form %} {% bootstrap_label "Email" %} {% bootstrap_field form.username show_lable=False placeholder ="Email" %} {% bootstrap_field field form.password %} <button class="btn btn-warning btn-block "> Sign in</button> </form> </div> </div> </div> </div> </div> {% endblock %} -
I can't run the form properly in django
html {% block content %} <div> {% for post in mesajlar %} <span>{{ post.mesaj }}</span> {% endfor %} </div> <form method="POST" style="color: #fff; margin-left: 40px; margin-top: 90px;" novalidate enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-primary" type="submit" value="Gönder" style="margin-top: 30px; margin-bottom:50px; margin-left:30px;"> </form> {% endblock %} views def sorucozum(request, id): post = get_object_or_404(YaziSoru, id=id) if request.method == "POST": form = CozumChatForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("sorucozum") else: form = CozumChatForm() context = { 'form': form, 'post': post } mesajlar = CozumChat.objects.all() return render(request, 'sorucozum.html', context, {'mesajlar': mesajlar}) i get this error in browser enter image description here plz help me i want to the form work right but i cant -
Django Custom filter "a GROUP BY clause is required before HAVING"
I wrote a custom filter, linked to a MultipleChoiceFilter with 5 choices (0,1,1.75,2.5,3.25 and 4) : def filtre_personnalise(self,queryset, name,value): query=FicheIdentification.objects.none() for i in value: if i=='0': query|=queryset.prefetch_related(Prefetch('entreprise',Entreprise.objects.all())).exclude(pk__in=[x.entreprise.siret for x in EvaluationGenerale.objects.all()]) else : query|=queryset.prefetch_related(Prefetch('entreprise',Entreprise.objects.all())).annotate(note_moyenne=Avg('entreprise__evaluationgenerale__note')).filter(note_moyenne__range=(float(i),float(i)+0.75)) return query If I tick each value individually everything works as expected, the returned queryset is what I want it to be. Everything also works fine if I tick several values simultaneously as long as 0 is not one of them (eg. 1 and 4 work fine together). But as soon as 0 is ticked with another value I get the following error : a GROUP BY clause is required before HAVING I honestly have no idea on why it behaves this way. I tried to replace | by .union but got this error : django.db.utils.ProgrammingError: each UNION query must have the same number of columns I think this one is related to the use of .annotate. -
IntegrityError at /admin/api/user/6/change/ FOREIGN KEY constraint failed
I am developing a website on django. When I am trying to delete a user via admin panel i get an error. I can change e.g. staff status (while still getting an error, but changes are getting apllied) The code is below: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): emailSpam = models.BooleanField(default=True) email = models.EmailField('email', unique=True) first_name = None last_name = None confirmedEmail = models.BooleanField(default=False) REQUIRED_FIELDS = ["emailSpam"] forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('email',) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import User class Admin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(User, Admin) -
How hide image path in django?
Is it possible to hide the path to the image so that it is not visible in the element expect? I dont want to allow user know where is my images are a storing. How i can hide this in django? -
Django Forms does not submit radiobutton value and does not showing any output in terminal as well
This is HTML Code. <form action = "." method = "post"> <div class="form_data"> {% csrf_token %} <br><br> {{form.myfield}} <br><br> <input type="submit" value="Submit" class="btn btn-success" /> </div> </form> This is forms.py code class TestForm(forms.ModelForm): class Meta: model = TestModel fields = "__all__" widgets = {'myfield': forms.RadioSelect()} This is models.py code class TestModel(models.Model): git_Id = models.CharField(max_length=200) git_Response = models.CharField(max_length=200) is_approved = models.IntegerField() MY_CHOICES = ( ('opt0', 'Approved'), ('opt1', 'Not Approved'), ) myfield = models.CharField(max_length=10, choices=MY_CHOICES, default="N/A") views.py code def test(request): if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data['myfield'] print(selected) if selected == 'opt0': from config import request_id as r rq = r["request_id"] print(rq) s = sql() query = f"""update request_form_mymodel set is_approved=1 where request_id = '{rq}' """ print(query) s.update_query(query) else: pass else: form = TestForm() return render(request, 'test.html', {'form': form}) I am not getting any output, if i try to submit after selecting radio button then it does not working and not printing any variables values in terminal as well and form is not submitted. What I want - I want to getting form is submitted and if radiobutton is selected opt0 then s.update() is called. -
Pyton django urlpatterns , url like localhost:8000/auth/?code=Rdsraj4v7BGNhH2
Pyton django urlpatterns , url like http://localhost:8000/auth/?code=Rdsraj4v7BGNhH2 How send value"Rdsraj4v7BGNhH2" from url to views url= localhost:8000/auth/?code=Rdsraj4v7BGNhH2 ` urlpatterns = [ path('?????', views.auth, name ='auth'), ] ` expectations : from url send value to views -
On admin django choose one element in a list and have same result in the inline
If we consider that "client" is a dropdown list, would it be possible to reflect the choice made in StatusAdmin in my StatusTextInline class in order to have only one client associated please? Or to check if the two clients are the same before saving? class StatusTextInline(admin.TabularInline): model = StatusText extra = 0 list_display = ( "id", "client", "label" ) @admin.register(Status) class StatusAdmin(admin.ModelAdmin): list_display = ( "id", "client" ) inlines = [ StatusTextInline, ] Knowing that client is a list, if I choose client 1 in StatusAdmin, then I will automatically have client 1 in my StatusTextInline. -
How to add field in django admin non related to model?
I want to add a checkbox in Django Admin that is not related to a field in my model. Depending on the value of the checkbox, I want to do some extra actions. class DeviceAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): #if checkbox: # do_extra_actions() super(DeviceAdmin, self).save_model(request, obj, form, change) How to add this checkbox in the django admin form for my model Device and get the value in save_model function ? -
['“test” value must be either True, False, or None.']
I am trying to create a register API but it returns a error: views.py class RegisterAPI(APIView): permission_classes = () authentication_classes = () def post(self, request, *args, **kwargs): serializer = RegisterSerializer(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) user = serializer.save() print(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) Models.py class CustomUser(AbstractBaseUser): username = models.CharField (max_length= 200) first_name = models.CharField (max_length = 300) last_name = models.CharField (max_length = 300) email = models.EmailField (max_length=255,unique=True) password_f = models.CharField (max_length=100,) profile_pic = models.ImageField (upload_to = r'Computerizer/static/Oauth/media') sub_to_newsletter = models.BooleanField(default=True) own_pc = models.BooleanField(default=False) active = models.BooleanField(default=True,null=True) #can login staff = models.BooleanField(default=False,null=True) #staff user not superuser admin = models.BooleanField(default=False,null=True) #admin / superuser USERNAME_FIELD = 'email' #username #email and password is requierd by default REQUIRED_FIELDS = [] #python manage.py createsuperuser objects = CustomUserManager() def __str__(self): return self.email def get_first_name(self): return self.email def get_last_name(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active def get_absolute_url(request): return reverse('') Serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','username','first_name','last_name','email','password_f','sub_to_newsletter','own_pc') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'username','first_name','last_name', 'email', 'password_f','sub_to_newsletter','own_pc') def create(self, validated_data): user = CustomUser.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password_f']) return user the error is: ['“test” value … -
Listing Kafka clusters and brokers with Python
I try to develop a Kafka GUI on Django. I can list topics of brokers, partitions and clients using kafka-python. Is a programmatic way to retrieve list of clusters and brokers? I can save clusters and related brokers as database tables as an alternative. -
How to put other model classes belonging (linked) to a main model class. And how to write this in Views.py. (This is Not FK)
I have a main model, called "Employees", and I need to link to it another 16 model classes (Employees Additional Data, Employees Observations, etc) in the same app. What would be the best way to write these classes in models.py? Could be like that? class Employees(models.Model): class Meta: db_table = "employees" #fields #fields class EmployeesObs(models.Model): class Meta: db_table = "employeesobs" #fields #fields class EmployeesAdditionalData(models.Model): class Meta: db_table = "employeesaditional" #fields #fields Now, in this views.py i need: Explaining this in the template, I need to have these other tabs (Employees Additional Data, Employees Observations, etc) in the employee register, as in the image: Now how do I write this in views.py? I'm using Class Based Views. Can someone help me by giving me an example of code, function or documentation? Part of code in CBV: class AddEmployeesView(SuccessMessageMixin, CreateView): model = Employees form_class = EmployeesForm template_name = '../templates/employees/form_employees.html' success_url = reverse_lazy('list_Employees') success_message = "Employees %(EmployeesNome)s Added!" class EditEmployeesView(SuccessMessageMixin, UpdateView): model = Employees form_class = EmployeesForm template_name = '../templates/employees/form_employees.html' success_url = reverse_lazy('list_Employees') success_message = "Employees %(EmployeesNome)s Edited!" I tried to put the other model names in the "model" part of the CBV, but I got errors. -
Access Multiple PDF Files with Django Rest Framework and REACT frontend
I am trying to access the uploaded files from my Django-rest-Framework which I uploaded with my React Frontend. The Upload is in my opinion const fetchDocuments = async () => { return await axios.get(`${URLS.courses}${params.courseId}/documents/`, { headers: { authorization: `Bearer ${getAuthenticationTokens().access}`, }, }); }; CourseDocument: class CourseDocument(models.Model): title = models.CharField(max_length=30, default='') document = models.FileField(upload_to='courses') course = models.ForeignKey(to='Course', on_delete=models.SET_NULL, null=True) To my DRF endpoint: @action(methods=['GET', 'POST'], detail=True, url_path='documents', permission_classes=EMPLOYEE_PERMISSION) def course_documents(self, request, *args, **kwargs): """ Returns the attached documents of the given course """ if request.method == 'GET': qs = CourseDocument.objects.filter(course_id=kwargs['pk']) fs = FileSystemStorage() filename = qs.first().document.path if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response else: print("NOT FOUND") if request.method == 'POST': serializer = CourseDocumentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=200) else: return Response(data=serializer.errors, status=400) return Response(status=200) I tried it so far with the FileSystemStorage to send it in an HTTP Response with content type application/pdf. This did work, but only for one single PDF File. I want to avoid to pass the pdf as a link to my backend because of security reasons. How can I achieve sending multiple pdf files to my frontend? -
responseType blog in django unit tests
How to add responseType blob while making a post request with django_test unit tests, below is my test code snippet : from django.test import TestCase def test_export_business_plan(self): """Test export business plan.""" data = { 'location_creation': 'berlin', 'date_creation': datetime.now().strftime('%Y-%m-%d'), 'company_name': 'Captiq', 'email_address': 'test@captiq.com', 'phone_number': '0704594180', 'street': 'Berlin Katherinenstrasse', 'house_number': '17b', 'additional': 'test', 'post_code': '43567', 'city': 'Frankfurt', 'sub_title': 'test' } response = self.client.post( reverse( 'api:financing:business_plan-export', kwargs={'pk': self.loan_application.pk}), data) print('**********==', response.data) print('**********==', dir(response)) self.assertEqual(response.status_code, 200) -
Django filter relation model mutiple fields at the sime time
I have a problem to filter following condition: class Plan(models.Model): name = models.CharField(max_length=50) class PlanAttribute(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name="attributes") key = models.CharField(max_length=50) value = models.CharField(max_length=50) I want to filter Plan with attr key="key1" and value="value1" at the same time Plan.objects.filter(attributes__key="key1", attributes__value="value1") is not what I want Please help me to filter like this cases -
Add Field Update
With the help of a button, I developed a code that allows the area I want to be added as the button is pressed, and this code works without any problems. When I reopen the form to update it, the data comes in as I added and I save it again, then when I enter the updated form, the data is lost. So I'm giving an example, I pressed the button 3 times and 3 fields came to enter, I filled in 3 of them and saved, then when I enter to update, it appears in 3 data. When I exit the update screen and enter that form again, only the most recently added data appears from the 3 data. models.py class Records(models.Model): username = models.CharField(max_length=1000, verbose_name='Ad Soyad',null=True,blank=True) date = models.CharField(max_length=1000,null=True,blank=True) hours = models.CharField(max_length=1000,blank=True,null=True) tel = models.CharField(max_length=1000,verbose_name='Telefon Numarası',null=True,blank=True) tcNo = models.CharField(max_length=1000, verbose_name='TC Numarası',null=True,blank=True) adress = models.CharField(max_length = 1000,verbose_name='Adres/Köy',null=True,blank=True) kurum = models.CharField(max_length=1000,verbose_name='Kurum',null=True,blank=True) diagnosis = models.CharField(max_length=1000, verbose_name='Tanı',null=True,blank=True) intervention = models.CharField(max_length=1000, verbose_name='Müdahale', null=True,blank=True) # medications = models.CharField(max_length=1000, verbose_name='İlaçlar', null=True,blank=True) conclusion = models.CharField(max_length = 1000,verbose_name='Sonuç',null=True,blank=True) doctor = models.CharField(max_length=1000, verbose_name='Doktor',null=True,blank=True) record_one_measurement = models.CharField(max_length=1000, verbose_name='1.Ölçüm',null=True,blank=True) record_one_blood_pressure = models.CharField(max_length=1000, verbose_name='1.Tansiyon',null=True,blank=True) record_one_pulse = models.CharField(max_length=1000, verbose_name='1.Nabız',null=True,blank=True) record_one_spo2 = models.CharField(max_length=1000, verbose_name='1.SPO2',null=True,blank=True) record_one_respirations_min = models.CharField(max_length=1000, verbose_name='1.Solunum/DK',null=True,blank=True) record_one_fire = models.CharField(max_length=1000, verbose_name='1.Ateş',null=True,blank=True) record_second_measurement … -
Auto list fields from many-to-many model
I've created a model of analysis types and then i created a table that groups several analysis to one group: class AnalysisType(models.Model): a_name = models.CharField(max_length=16,primary_key=True) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # analysis_group = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) def __str__(self): return f"{self.a_name} - {self.a_measur}" class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" I want to have an option to multiple add values via admin panel (I.E. i chose Analysis type then below appear fields to fill) class PatientGroupAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) # amalysis_data = ??? def __str__(self): return f"{self.patient}: {self.analysis_date} - {self.analysis_type} - {self.analysis_data}" enter image description here Tried to use amalysis_data = analysis.type.objects.all() and etc. but that's the wrong way i guess .. :(