Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I troubleshoot JavaScript quantity control?
I am currently implementing a page where the price of the option appears when I select the option. The code I wrote shows that the price is 0 won when the quantity is 1 piece. Everything else works fine, but I have no idea where the problem is. Why is this a problem? If you could help me, I'd really appreciate it. " <div class=\"price_btn\">\n" + " <input type=\"button\" value=\"-\" class=\"minus_btn\">\n" + " <input style=\"width: 15%;\" type=\"text\" value=\"0\" class=\"number\" name=\"quantity\" id=\"quantity\">\n" + " <input type=\"button\" value=\"+\" class=\"plus_btn\">\n" + " </div>\n" + " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<strong name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "</strong>원\n" + " <input name=\"price2\" id=\"price2\"\>" + " </div>\n" + " </div>\n" + " </li>\n" + " </ul>" + " </div>" + "\n" + "\n" + " </div>" ; $("#selectOptionList").append(whtml) var checkText = $("#optionSelect option:selected").attr("disabled","disabled"); } $(document).ready(function () { $('.price_btn input[type="button"]').on('click', function () { var $ths = $(this); var $par = $ths.parent().parent(); var $obj = $par.find('input[type="text"]'); var val = $obj.val(); var $input = $par.find('input[id="price2"]'); var $price2 = parseInt($par.find('strong[name="price2"]').text().replace(/[^0-9]/g, "")); if ($ths.val() == '-') { if (val > 1) $obj.val(--val); $input.val($price2); } else if ($ths.val() == '+') … -
Memory issue with Django web app which is receiving frequent data from clients using XMLHttpRequest
I am developing a Django web-application to allows participants to have meeting online (I am using Jitsi for that). During meeting, the application tracks the voice activity (whether someone is speaking or not) using a JS library. So, whenever the application detects the sound, it sends the data with timestamp to server using FormData and XMLHttpRequest. I have included a snapshot of the code below. var fd = new FormData(); fd.append('csrfmiddlewaretoken', "{{ csrf_token }}"); fd.append('session',{{session.id}}); fd.append('user',{{request.user.id}}); fd.append('group',{{group}}); fd.append('strDate',ServerDate.now()); fd.append('activity',speak_time); var xhr = new XMLHttpRequest(); xhr.open('POST', '/vad_upload/', true); xhr.send(fd); I have tested the application with 30-50 people and in each test I observed an increased memory consumption on server. I have included a graph below as well showing server load. I assumed that it may be happening due to high frequency of data sent from client. However, the memory consumption is remaining same even after the activity when all clients are signed off and no data are sent from their side. Restarting the server seems to work at the moment. However, it is not feasible once the application is in use. Could you please share some information on this issue. Any input would be of great help. My Django server is … -
How to fix IntegrityError: FOREIGN KEY constraint failed
I created UserProfile model and when i go to django admin and trying to create/change profile it throws an error IntegrityError: FOREIGN KEY constraint failed. I am new to djnago so I don’t understand why i'm getting this error. users/models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length = 40, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) slug = AutoSlugField(populate_from = 'username', null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Meta: verbose_name = 'User' verbose_name_plural = 'Users' def __str__(self): return self.email def get_absolute_url(self): return reverse('profile', args=[str(self.slug)]) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete = models.CASCADE, null = True, db_constraint=False) avatar = models.ImageField(upload_to = 'avatar', default = "empty_avatar.jpg", blank = True, null = True) description = models.TextField(default = '', null = True) recipe = models.ManyToManyField(Dish, blank = True) slug = AutoSlugField(populate_from = 'user', null=True) class Meta: verbose_name = 'Профиль' verbose_name_plural = 'Профили' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() recipe/models.py class Dish(models.Model): title = models.CharField(max_length = 50) dish_image = models.ImageField(upload_to = 'images') I think it is something wrong with ManyToManyField but i don't know what forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() … -
Add information to DB only after admin approval - Django
I built a site that users can add word and association how to remember the word to a database. However I don't want that the DATA will save automatic I want to add options that only after the approval of admin the word will add to the DB and other users will see it. how can do I do that? Thank you! -
Two model fields referring to each other - django rest
I want to change one of the existing field names in the Django model. But, for the backward-compatibleness, we'd like not to override the existing field with the new one, keep both of them for now. Is there any way to have multiple fields referring to the same database object? i.e Code right now: class NetworkPackage: name = models.CharField(unique=True, blank=False, null=False) inbound = models.CharField(unique=True, blank=False, null=False) ... I want to implement: class NetworkPackage: name = models.CharField(max_length=32, unique=True, blank=False, null=False) inbound = models.CharField(max_length=128, unique=True, blank=True) mobile = models.CharField(max_length=128, unique=True, blank=True) ... Basically, 'inbound' and 'mobile' should refer to the same field and the request could be sent either with 'inbound' field or 'mobile'. -
Django rest framework best practices
I was wondering what would be the best approach . I've been agonizing on what is the best way to accomplish a given task. It is a project with a react frontend and django rest framework backend. I am working on the backend with the django rest framework . Task: To query a user by their phonenumber which is stored as the username field. To add a user to a profile model and add an extra field which is required by the profile model To create the new profile with the user as the profiles user . e.g Profile Model: User - ForeignKey ExtraField - Charfield My question is which of these solutions is better . Should I build a url like this : domain/users/{phonenumber} and post the Extra field and query the user like this. def get_object(self): return get_object_or_404(User,username=self.kwargs['phonenumber']) user= get_object() or Should I post both the phonenumber and the extrafield and query the user from the backend like this. user = get_object_or_404(User,username=request.data.get('phonenumber') both work but which would be the best practice if it even matters at all. -
drf-yasg - read http_method_names from urls.py
I have a Settings subclass of APIView which has 2 methods. class Settings(APIView): def get(self, request, id=None): pass def post(self, request): pass In urls.py, I have the following, urlpatterns = [ path('account/settings/<str:id>', Settings.as_view(http_method_names=['get'])), path('account/settings/', Settings.as_view(http_method_names=['post'])), ] As you can see, I want id to be passed as a parameter in get method, but not in post method. drf-yasg, ideally should only show 2 methods on Swagger page, but it shows 4 methods. 1. GET for /settings/{id} 2. POST for /settings/{id} 3. GET for /settings/ 4. POST for /settings/ I have tried adding @action(methods=['GET']), @api_view['GET']. But it doesn't work. How do I tell drf-yasg to read allowed methods from http_method_names in urls.py. -
save() prohibited due to unsaved related object in inlineformetset_factory
Wondering why inlineformetset_factory couldn't unhide the FK('shoe') in child model? Although I find my way to demonstrate what I am looking for in form, still curious the reason for that and is there possible to solve it? Modles.py class Shoes(models.Model): Sur = [ ('Trl','Trail'), ('Rd','Road') ] nameS = models.CharField(max_length=20) surface = models.CharField(max_length=10,choices=Sur,default='Rd') milage = models.FloatField(max_length=10) brand = models.ForeignKey(Brands, on_delete=models.CASCADE) target = models.ManyToManyField(Targets) def __str__(self): return self.nameS class Runs(models.Model): date = models.DateTimeField(auto_now_add=True) # DateTimeField(default=timezone.now) target = models.ForeignKey(Targets, on_delete=models.CASCADE) mileage = models.FloatField(max_length=3) duration = models.DateTimeField(blank=True) pace = models.IntegerField(max_length=3) shoe = models.ForeignKey(Shoes, on_delete=models.CASCADE) def __str__(self): return self.date.strftime("%Y/%m/%d") Views.py (those were commented is the way I find) def create_run(request): RunFormSet = inlineformset_factory(Shoes, Runs ,fields= '__all__' ,extra=5 ,widgets={'duration':SelectDateWidget()} ,form=RunForm) formset = RunFormSet() if request.method == 'POST': formset = RunFormSet(request.POST,instance=formset.instance) if formset.is_valid(): formset.save() return redirect('/') # Optimal_Num = 6 # if request.method == 'POST': # # print(request.POST) # formSet = [RunForm(request.POST, prefix=i) for i in range(Optimal_Num)] # if any(form.is_valid() for form in formSet): # formSet.save() # return redirect('/') # else: # formSet = [RunForm(prefix=i) for i in range(Optimal_Num)] return render(request, 'Clothes/run_form.html',{ "Forms" : formset }) -
Can I buy a domain name from one service and host a web app on another service?
I bought a domain name from gandi.net .However, it is not the best to host a Django web app. I am considering to switch to heroku. Does anyone has tips or advices when hosting a Django web app? -
this code gives me TypeError: view must be a callable or list/tuple in the case of include()
from django.conf import urls from django.conf.urls import include, url from django.contrib.auth import views as auth_views from django.contrib import admin from cs243.view import login,index2,studentprofile,photo,postgrad,undergrad,srsec,sec,languages,projects from credentials.views import internships,contact,language urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', login), url(r'^index2/$', index2), url(r'^studentprofile/$', studentprofile), url(r'^photo/$', photo), url(r'^postgrad/$', postgrad), url(r'^undergrad/$', undergrad), url(r'^srsec/$', srsec), url(r'^sec/$', sec), url(r'^internships/$', internships), url(r'^languages/$', languages), url(r'^contact/$', contact), url(r'^projects/$', projects), url(r'^language/(?P<language>[a-z\-]+)/$', language), url(r'^auth/$'[enter image description here][1], 'cs243.view.auth_view'), url(r'^invalid/$', 'cs243.view.invalid_login'), url(r'^loggedin/$', 'cs243.view.loggedin'), url(r'^register/$', 'cs243.view.register_user'), url(r'^register_success/$', 'cs243.view.register_success'), ]enter image description here -
How can I fill a table view based on some calculous, resorting to django?
So I'm starting a django web application and I'm new using django... So please be patient with me. So, in my project I have two views: 1- a user profile; 2- a sort of a calculator, that can give several results at the same time according to the user input So, to start, here is my model.py: class Calanalisis(models.Model): sequence = models.CharField(max_length=120000) gc_content = models.DecimalField(decimal_places=3, max_digits=1000) def gc_content_cal(self): if self.sequence == True: gc_content= round((self.sequence.count('C') + self.sequence.count('G'))/len(self.sequence) * 100,1) return gc_content forms.py: class AddSequenceForm(forms.ModelForm): class Meta: model = Calanalisis fields = ('sequence',) views.py: def calc_sequence(request): sequence_items=Calanalisis.objects.filter(person_of=request.user) form=AddSequenceForm(request.POST) if request.method=='POST': form=AddSequenceForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.person_of = request.user profile.save() return redirect('calc_sequence') else: form=AddSequenceForm() myFilter=SequenceFilter(request.GET,queryset=sequence_items) sequence_items=myFilter.qs context = {'form':form,'sequence_items':sequence_items,'myFilter':myFilter} return render(request, 'Add_Calc.html', context) And now I want to introduce gc_content_cal to be calculated in the table. When I introduce the sequence, the sequence appears in the table, however the gc_content_cal continues to be 0, like the image shows. Can someone help me please? -
Python - TypeError querying Solarwinds N-Central via Zeep SOAP
I am using zeep for the first time in Python3, to access XML data from N-central Solarwind and trying to get customer information but I am stuck on Settings parameter I am getting TypeError got an unexpected keyword argument 'Key' I have tried everything but it is giving me the same error, even tried with get_type() method but still getting same error from zeep import Client from zeep import xsd def customer_info(request): client = Client('http://server-name/dms/services/ServerEI?wsdl') # settings_type=client.get_type('ns0:Customer') # value = settings_type(Key='listSOs', Value='true') value={ 'Key': 'listSOs', 'Value': "true", } response =client.service.Customer_List(Username=USER,Password=PASS,Settings=value) response2 =client.service.Device_List(Username=USER,Password=PASS,Settings=xsd.SkipValue) return HttpResponse(response) This is written in its Docs Parameters: username - the MSP N-central username. password - the corresponding MSP N-central password. settings - A list of non default settings stored in a List of EiKeyValue objects. Below is a list of the acceptable Keys and Values. If not used leave null. (Key) listSOs - (Value) "true" or "false". If true only SOs with be shown, if false only customers and sites will be shown. Default value is false. -
django database model relationships
I need to work on something like grade viewing in my web app, for example, my model looks like this: class Subjects(models.Model): subject = models.CharField(max_length= 255) class Student(models.Model): student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) enrolled_subjects = models.ManyToManyField(Subjects) class StudentGrade(models.Model): student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) subject = models.ForeignKey(?) grade = ... period = models.ForeignKey(SchoolPeriod) how can I access the enrolled_subjects of the Student object in Student Grades model? should i do something like: (im not sure if I can do something like this in models.py) class StudentGrade(models.Model): ENROLLED_SUBJECTS_CHOICES = Student.objects.filter(//some filter here) student = models.Foreignkey(Student,related_name="student", on_delete=models.CASCADE) subject = models.ChoiceField(choices= ENROLLED_SUBJECTS_CHOICES, default= None,) grade = ... period = models.ForeignKey(SchoolPeriod) -
Is there any possibility to add fields inside the fields of a Model
Assume I have a model named MyModel and I have a Field Named field Now I want to add three more fields inside the prescription like one field_a , field_b and field_c . Does Django Allow that in any way or we have to make another model for this purpose and then link with Foreign Key to MyModel? -
What is the difference between Geodjango , Geoserver or GeoNode?
I know its a broad spectrum question but I am confused about these three big geospatial technology stack (i don't know is it right to say even individual technology as stack). Does GeoDjango, geoserver and Geodjango all have same objective for making a Webgis application? Who has more capabilities and options to make a full fledge geospatial analysis tool or GIS application ? Are they competitors of each other or can be opt at a time in a single geospatial application or tool? Looking for detailed answer if one can anticipate the pros and cons of each technology it would be a great contribution in this domain? I have searched alot over the internet but not found any useful answer, and finally decided to use this forum. -
Like or dislike comments on Django
I want the comments section to be liked or disliked like the image of the comment when the user clicks on the desired button. in django enter image description here -
AttributeError at /BRMapp/view-books/
I am developing Book Record Management system as my first project on django but after performing all my functionalities I got a problem in my views.py file in a function name view-book in a line(books=models.Book.objects.all()).Although i have made a class name 'Book' in models.py and i also have imported models in my views.py file with a line(form django.db import models).Although it is not working.Kindly help Error showing like this::: module 'django.db.models' has no attribute 'Book' Request Method: GET Request URL: http://localhost:8000/BRMapp/view-books/ Django Version: 3.2.5 Exception Type: AttributeError Exception Value: module 'django.db.models' has no attribute 'Book' Exception Location: G:\Django projects\firstproject\BRMapp\views.py, line 41, in viewBooks Python Executable: C:\Users\amann\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.2 Python Path: ['G:\Django projects\firstproject', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\amann\AppData\Local\Programs\Python\Python39', 'C:\Users\amann\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\amann\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Thu, 12 Aug 2021 10:19:08 +0000 -
True or false validation to check whether web compiled user input is equal to a locally stored value
My question title does not succinctly explain my objective. Let me improve on that. I am mildly familiar with extending an IDE functionality in a web application. Lets assume that in I somehow manage to store a predetermined value, the correct output of a certain formula; a sorted list of x int values -[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] . It can be sorted using any sorting algorithm. An example shell_sort algo: def shell_sort(list): gap = len(list) // 2 while gap > 0: for i in range(gap, len(list)): temp = list[i] j = i while j >= gap and list[j-gap] > temp: list[j] = list[j-gap] j = j - gap list[j] = temp gap = gap // 2 list = [10,9,8,7,6,5,4,3,2,1] shell_sort(list) print(list) The output of the above function should be: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Please note that I somehow have figured a way to store the correct output of the algorithm. False or True, for now. How can, when a user using a web-ide integrated platform solving for example the algorithm above, be able to programmatically determine the correctness of the users output against one stored locally? -
How To View Mysql Blobs In Flutter Using Django
I saved some images in Mysql DB as "Medium Blob" and I am using Django to create the rest api. this is the output I'm receiving from the api: blob image this is my "views" file in Django: from django.shortcuts import render import base64 from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .serializers import PlaceSerializer from .models import Place # Create your views here. class TestView(APIView): def get(self, request, *args, **kwargs): qs = Place.objects.all() serializer = PlaceSerializer(qs, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = PlaceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) I want to convert the image column to an image in flutter. Looking forward for your help, thanks. -
Force Django related_name return another queryset
I have two models: from django.db import models class Task(models.Model): name = models.CharField(max_length=20) class CascadedTask(models.Model): task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='cascaded_from') cascaded_from = models.ForeignKey('tasks.Task', on_delete=models.CASCADE) Data examples: model Task: id name ------------ 1 Task #1 2 Task #2 3 Task #3 4 Task #4 5 Task #5 6 Task #6 7 Task #7 model CascadedTask: id task_id cascaded_from_id ----------------------------- 1 4 1 2 4 2 3 4 3 4 6 2 5 6 3 6 6 5 7 7 4 8 7 6 My goal is to get QuerySet of Task objects but not CascadedTask objects when using related_name as it is now: task = Task.objects.last() # <Task: Task object (7)> task.cascaded_from.all() # <QuerySet [<CascadedTask: CascadedTask object (7)>, <CascadedTask: CascadedTask object (8)>]> I would like task.cascaded_from.all() return <QuerySet [<Task: Task object (4)>, <Task: Task object (6)>]>. How could I reach that? -
Vimeo integration in open-edx
i want to integrate Vimeo in my open-edx platform (open-release/koa.master). I tried below xblock but not working. https://github.com/appsembler/xblock-video https://github.com/sporedata/xblock-vimeo If anyone could help me I would really appreciate it. -
django didn't return HttpResponse Object
I saw many answers about this subject of HttpResponse object in Django, but i can't resolve it. Normally, the user enters the information and the database is saved. def place_order(request, total=0, quantity=0): current_user = request.user # If the cart count is less than or equal to 0, then redirect back to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total)/100 grand_total = total + tax But this is not happening since I get this error. Is there that can help? if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): # Store all the billing information inside Order table data = Order() data.user = current_user data.first_name = form.cleaned_data["first_name"] data.last_name = form.cleaned_data["last_name"] data.phone = form.cleaned_data["phone"] data.email = form.cleaned_data["email"] data.address_line_1 = form.cleaned_data["address_line_1"] data.address_line_2 = form.cleaned_data["address_line_2"] data.country = form.cleaned_data["country"] data.state = form.cleaned_data["state"] data.city = form.cleaned_data["city"] data.order_note = form.cleaned_data["order_note"] data.order_total = grand_total data.tax = tax data.ip = request.META.get("REMOTE_ADDR") data.save() # Generate order number yr = int(datetime.date.today().strftime("%Y")) dt = int(datetime.date.today().strftime("%d")) mt = int(datetime.date.today().strftime("%m")) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") # 20210305 order_number = current_date + str(data.id) data.order_number … -
how to filter related objects for each post django
i'm trying to display current booking in rooms show in my main page for admins my models.py class Room(models.Model): room_no = models.IntegerField(unique=True) some_fields = models.CharField(max_length=20,choices=my_choices) beds = models.IntegerField(default=2) #others class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,related_name='rooms') check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) #others show only that booking which is checkout is none or greater than current date , i need filter related objects for each room to if not_checked_out = Q(check_out__gte=timezone.now()) and not_selected = Q(check_out__isnull=True) my views.py @login_required def all_rooms(request): not_checked_out = Q(check_out__gte=timezone.now()) not_selected = Q(check_out__isnull=True) rooms_show = Room.objects.all().order_by('room_no') return render(request,'rooms/rooms.html',{'rooms':rooms_show}) i dont know how to annotate that! i need to show current booking for each rooms in my template <div class="group cursor-pointer"> <a href="{% url 'booking:add_booking' i.room_no %}"> <div class="overflow-hidden transform transition duration-400 hover:scale-90 "> <img src="{% static 'img/iconbed.png' %}" class="rounded-full w-24 mx-auto" alt=""> </div> </a> <div class="border border-gray-900 rounded-xl overflow-hidden -mt-12"> <div class="p-2 rounded-xl bglightpurple pt-12 items-center"> <div class="text-center rounded bggray text-xs md:text-base"> <p class="inline textorange "><i class="bi bi-list-ol"></i> room no:</p> <p class="inline text-white text-white">{{i.room_no}}</p> </div> <div class="grid grid-cols-2 mt-3 gap-2"> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.room_type}}</span> </div> <div class="p-1 text-center text-xs rounded bggray"> <span class="text-white"><i class="bi bi-columns-gap"></i> {{i.beds}} beds</span> </div> <div … -
Wagtail: How to display streamfield block options/type in a dropdown/autocomplete list
I want to create a generic page with around 100 or more block options in stream field. But to access such long list of block types, would like to display it in a dropdown/autocomplete. Once user select the item from dropdown it should add the streamblock. The block interface should be easily accessible. I can fetch the list of blocks using below code, but how to display that list and add block on selection? def get_context(self, request): context = super().get_context(request) list_of_blocks = list(self.body) return context -
Exclude Django admin fieldsets
Whats the best way of excluding fieldsets, I have been reading different posts like the one's below : Question. but I couldn't get it working with them. I want to negelect the following fieldsets when it's not superuser : Cooperation Partner Settings. email_user (This is an Inline not a field set) Below is the admin.py code @admin.register(CooperationPartner, site=admin_site) class CooperationPartnerAdmin(model.Admin): inline_type = 'stacked' inline_reverse = [( 'email_user', {'fields': [ 'salutation', 'title', 'first_name', 'last_name', 'email', ]}, )] reverse_delete_user = True form = CooperationPartnerAdminForm fieldsets_add = ( (_('Personal Data'), { 'fields': ( 'birthday', 'private_address_street', 'private_address_house_n', 'private_address_extra', 'private_address_postcode', 'private_address_city', ), }), (_('Cooperation Partner Settings'), { 'fields': ( 'pool', 'custom_policy_type', 'custom_database_structure', 'custom_attachments', ) }), (_('Company Data'), { 'fields': ( 'company', 'legal_form', 'business_address_street', 'business_address_house_n', 'business_address_extra', 'business_address_postcode', 'business_address_city', 'international_prefix', 'phone_number', 'career_position', 'loan_intermediary_permission', 'agreed_provision', 'bank_name', 'iban', 'bic', 'account_holder', 'sepa_direct_debit_mandate', 'status_decision_feedback', ), }), ) fieldsets_change = ( (None, { 'fields': ( 'cooperation_partner_id', 'account_state', ), }), ) + fieldsets_add def get_form(self, request, obj=None, change=False, **kwargs): """Overwrite get_form method.""" self.fieldsets = self.fieldsets_change if obj else self.fieldsets_add return super().get_form(request, obj, change, **kwargs)