Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App hosted on IIS suddenly starts to show "Object Moved" Page plus gibberish on 302 redirect
Screenshot It's an internal Django web app is hosted on a Windows Server 2008 with IIS 7.5, with Active Directory SSO enabled. Some links in the app response with a 302. For example, if the request is to go to myapp.com/change, the server will response with a 302 and redirect to myapp.com/change?user=5. In the browser, the url field shows the myapp.com/change?user=5, but the page looks like the picture above. If I hit enter on the url field, it goes to the correct page. I have tried to troubleshoot with DevTools. When clicking on /change, server responses with a 302 followed by a 200, nothing else. The 200 is blank, with no header or body, and says "Caution: request is not finished yet". Meanwhile, there's the spinning icon showing on the chrome tab meaning it's still loading. After a few minutes, the 200 times out and the spinning stops. Nothing in the code was changed in the last couple weeks, and two days ago people started reporting this issue. It didn't happen to me at first. I tried clearing cookie and cache, using different browsers and PCs, couldn't replicate it, then there's a scheduled PC restart yesterday, and I'm getting this … -
How to create an api request in python with apy key
I need to make an api call with api key in django ,this works in postman : i have tried it in python : header={"content-type": "application/json","Authorization": "X-Api-Key %s" %(self.api_key)} r = requests.post(email_meta_path,json=json,header=header) but i got authentication credintionals error , how can i create the postman request in python ? -
Django-Tailwind not working properly in Django
Django-Tailwind initially after setup works well with Django, but as soon as I start progressing with my project, it stops working!!! -
How can I Create Django Object after a Confirmation Form
I am working a Saving App where I want user to confirm Deposit before adding it in the database. I have tried all I could but after clicking on Confirm button in the Dailog Form the system redirects me back to deposit form displaying an error that Field Can Not be Empty. Model Code: class Deposit(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Form Code: class CustomerDepositForm(forms.ModelForm): class Meta: model = Deposit fields = ['deposit_amount'] Views Code: def customer_deposit(request, id): context = {} form = CustomerDepositForm(request.POST or None) #Set Page Title page_title = "Customer Deposit" #Get Current Date current_date = datetime.now().date() #Get Current Month Name from Calendar current_month_name = calendar.month_name[date.today().month] try: #Check the Customer ID in DB customer = Customer.objects.get(id=id) #Customer Account acct = customer.account_number except Customer.DoesNotExist: messages.error(request, 'Customer Does Not Exist') return redirect('customer_create') else: #Get the Customer total deposit deposit = Deposit.objects.filter(customer_id = id).aggregate(total=Sum('deposit_amount') )['total'] or Decimal() if request.method == 'POST': #Deposit Form form = CustomerDepositForm(request.POST or None) if form.is_valid(): amount = form.cleaned_data['deposit_amount'] context.update( { 'deposit':deposit, 'page_title':page_title, 'customer':customer, 'current_date':current_date, 'current_month_name':current_month_name, 'form':form, 'amount':amount, 'acct':acct, … -
Download a file with axios that comes from an api Django
Im trying to download an xlsx that is generated in the backend in django but it seems that the credentials are not provided. axios.get request getPoResume = () => { axios.get( process.env.REACT_APP_IP + `/po/get_resume_pos/?client=${this.state.selectedClientPo}`, { headers: { "Authorization": "Token " + this.userToken }, }).then( function(response) { this.componentDidMount(); window.open(process.env.REACT_APP_IP + `/po/get_resume_pos/?client=${this.state.selectedClientPo}`) this.notify("tr", "success", "Resume downloaded!"); }.bind(this)).catch( function(error) { this.handleError(error, "getResume failed"); }.bind(this) ); }; and this is the answer when i try to download credentials error HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Token { "detail": "Authentication credentials were not provided." } -
Sublime Text 4: Support for Django autocompletion
I'm looking for a way to implement Django's autocompletion and hints. I'm aware that it's possible in Sublime Text 3. I'm looking at how to do it in the Sublime Text 4. For example, I'm unable to use Djanerio in Sublime package browser going: preferences -> Package Control: Djanerio. It doesn't find anything. -
Sign in with Google integration given origin not allowed on django
I am new to the google sign in api, and I am trying to create a simple app in which users sign up/sign in using google one tap sign in and then see their name and email. I was able to get google sign in working as a static webpage on my webserver(apache), but once I moved it to django(I am using django to store the emails in a database), I get the error: [GSI_LOGGER]: The given origin is not allowed for the given client ID. I have added the url tied to my webserver to the list of authorized js origins, hence it was working as a static page from that url, but it is not working when served through django. Is the origin different when it comes from django? Also, I know that there is a way to accomplish what I want using django social auth or django all auth, but I am looking to get the one tap sign in working using this code (heavily based on these docs from google: https://developers.google.com/identity/gsi/web/guides/migration , https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions ) index.html: <script src="https://accounts.google.com/gsi/client" async defer></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <div id="g_id_onload" data-client_id=['my client id'] data-auto_select="true" data-login_uri=['the url which was added to js origins'] … -
Django parameters in URL
I am trying to write a delete function for my CRUD API with Python Rest Framework. In the delete I want to delete a specific item in the database, and I want it to be passed via link parameter like so: path/to/link/to/delete/post3. I did that in the url file: path("link/<int:link_pk>/", views.LinkView.as_view(), name="link_integration") Then, in the ApiView that is the code: @log_request_decorator def delete(self, request: Request, link_pk: int, **kwargs) -> JsonResponse: do_stuff() #print(social_integration_pk) return JsonResponse({}, status=204) And here is the code of the test that I am using to test it: link = "link/1/" factory = APIRequestFactory() request = factory.delete(link) view = LinkView.as_view() ---forced auth--- response = view(request) And I get this as output: TypeError: delete() missing 1 required positional argument: 'link_pk' Do someone know how to fix that? I need to have that parameter in order to do what I am supposed to. Maybe is something silly, but I don't know. If you can, please help me. Thank you -
Trying to revert from class based detail view to a function based view but I keep getting a NoReverseMatch error
I am creating a ticket project with some comment functionality and I know this sounds weird, since the tendency is usually to go from function based to class based. My problem lies in the fact that since the Detail View is designed to just be a Display View, trying to include a comment system on the same page proves to be rather difficult. Right now, I am simply trying to replicate the detail part of the ticket and I keep getting this error Traceback Traceback (most recent call last): File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mikha\bug_env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\mikha\bug_env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\mikha\bug_env\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 176, in render return self._render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 168, in _render return self.nodelist.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 977, in render return SafeString(''.join([ File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 978, in <listcomp> node.render_annotated(context) for node in self File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 938, in render_annotated return self.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\loader_tags.py", line 153, in render return compiled_parent._render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 168, in _render return self.nodelist.render(context) File "C:\Users\mikha\bug_env\lib\site-packages\django\template\base.py", line 977, in render return SafeString(''.join([ … -
Docker and Nginx: port 80 and 403: address already in use
I have a VPS server runs on Ubuntu, I am running multiple Django projects with Nginx and Gunicorn. Recently, I decided to deploy my latest project with Docker. Everything is working, except the port 80. I can run the website on example.com:1330 but once I change it to 80, I get this error: err: ERROR: for nginx Cannot start service nginx: driver failed programming external connectivity on endpoint project-nginx (a4417bdb121b0afb1e57e11b68dd0eb74f770ed74f654a2722f4cd74121): Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use err: Encountered errors while bringing up the project. Here is a part of my: docker-compose.yml nginx: container_name: portfolio-nginx restart: unless-stopped build: ./nginx ports: - "80:80" # doesn't work - "1330:80" # works Nginx upstream project { server project-django:8000; } server { listen 80; server_name example.com; 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/ { root /code; } location /media/ { root /code; } } I thought the problem is I have Nginx already running on port 80: sudo netstat -ntulp | grep 80 Once I kill the process the docker website works on port 80. But I lose the other Django projects that doesn't run on docker. Please, any idea? -
why function' object has no attribute 'user' showing up?
i tried to create 2 users in my project models.py class CustomUser(AbstractUser): user_type_choices = ((1, "Admin"), (2, "NotesUser")) user_type = models.CharField(max_length=10, choices=user_type_choices, default=1) class Admin(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE) class NotesUser(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE) @receiver(post_save, sender=CustomUser) def create_user_profile(sender, created, instance, **kwargs): if created: if instance.user_type == 1: Admin.objects.create(user_id=instance) if instance.user_type == 2: NotesUser.objects.create(user_id=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance, **kwargs): if instance.user_type == 1: instance.admin.save() if instance.user_type == 2: instance.notesuser.save() and i wrote this middleware for checking user access LoginCheckMiddleWare.py from django.utils.deprecation import MiddlewareMixin from django.urls import reverse from django.http import HttpResponseRedirect, HttpResponse class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, view_func, request, view_args, view_kwargs): modulename=view_func.__module__ user = request.user if user.is_authenticated: if user.user_type == "1": if modulename == "todo_app.views" or modulename == "todo_app.AdminViews": pass else: return HttpResponseRedirect(reverse("admin_home")) elif user.user_type == "2": if modulename == "todo_app.UserViews" or modulename == "todo_app.views": pass else: return HttpResponseRedirect(reverse("user_home")) else: pass #return HttpResponseRedirect(reverse("log_in")) else: if request.path == reverse("log_in") or request.path == reverse("login_save") or modulename == "django.contrib.auth.views" or modulename == "todo_app.views": pass else: return HttpResponseRedirect(reverse("log_in")) i mentioned the middleware i created in app into settings.py file settings.py 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', 'todo_app.LoginCheckMiddleWare.LoginCheckMiddleWare', ] but an error is showing when i tried to access my login … -
How can I pass the values of the relevant row into the modal when a click event occurs on a table?
When a click event occurs on a table, I want to pass the values of the relevant row into the modal. I wrote a code like this, but the values of the top row are always passed into the modal. What I want to do is to show the values in the row I clicked in the modal. How can I provide this? my table codes here: <table class="table align-middle" id="customerTable"> <thead class="table-light"> <tr> <th class="sort" data-sort="name">Name Surname</th> <th class="sort" data-sort="company_name">Phone Number</th> <th class="sort" data-sort="leads_score">Note</th> <th class="sort" data-sort="phone">Status</th> <th class="sort" data-sort="location">Personal Name</th> <th class="sort" data-sort="tags">Data Name</th> <th class="sort" data-sort="action">Edit</th> </tr> </thead> <tbody class="list form-check-all"> {% for x in model %} <tr> <td class="table-namesurname">{{x.name}}</td> <td class="table-phonenumber">{{x.phonenumber}}</td> <td class="table-note">{{x.note}}</td> <td class="table-status">{{x.status}}</td> <td class="table-callname">{{x.callname}}</td> <td class="table-dataname">{{x.dataname}}</td> <td> <ul class="list-inline hstack gap-2 mb-0"> <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit"> <a class="edit-item-btn" id="call-button" href="#showModal" data-bs-toggle="modal" data-id="{{x.id}}"><i class="ri-phone-line fs-16"></i></a> <!-- Here is the edit button --> </li> </ul> </td> </tr> {% endfor %} </tbody> </table> my modal here <div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header bg-light p-3"> <h5 class="modal-title" id="exampleModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button> </div> <form action=""> <div class="modal-body"> <input type="hidden" id="id-field" /> <div class="row g-3"> <div … -
How can i make redirect when user login successfully with django-rest-framework
Urls.py from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/int:pk/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/int:pk/', ProductsAPIRemove.as_view()), path('api/v1/auth/', include('djoser.urls')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get country from (intl-tel-input) jquery
how can I get the name of the selected country from intlTelInput? I have a form with an input hidden this would get the name of the country as selected. but I don't know how to do this inttelephoneinput.js $(function() { $("#mobile-number").intlTelInput({ preferredCountries: ["us", "co"], }); }); template I clarify that the selection of countries and enter number works <div class="col-md-6 col-lg-6 mg-t-20 mg-md-t-0"> <input type="code" id="country" vale=" "> <label class="form-control-label">Telephone: <span class="tx-danger">*</span></label> <input class="form-control" type="tel" id="mobile-number" name='phone_number' placeholder="e.g. +1 702 123 4567"> </div> {% block extra_js %} <script src="{% static 'template/assets/plugins/telephoneinput/telephoneinput.js' %}"></script> <script src="{% static 'template/assets/plugins/telephoneinput/inttelephoneinput.js' %}"></script> {% endblock %} -
Apache Reverse Proxy using mod_proxy
0 Introduction I'm trying to setup a server with a main website hosted on ports 80 and 443 (let's call it example.com) and a section on this website that serves umami analytics hosted on port 3000 (let's call it umami.example.com) using a reverse proxy. I'm using Django and Apache (with mod_wsgi as hinted from the django project) and I have to setup DNS using Cloudflare. The main website works as intended, redirecting http traffic to https (more on that on the Apache section) and I'm tring to add this section under umami.example.com but every request ends up in a 404 error given by my main website. Currently I'm trying to make the umami part work using a reverse proxy (as shown in the first section of the Apache Config) #################################################################### 1 DNS DNS are configured using Cloudflare with 3 A records: example.com -> server IP address umami -> same server ip www -> again same ip and some MX and TXT ones. #################################################################### 2 Apache Config <VirtualHost _default_:80> ServerAdmin admin@example.com ServerName umami.example.com ProxyPass "/" "http://127.0.0.1:3000/" ProxyPassReverse "/" "http://127.0.0.1:3000/" </VirtualHost> <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost> <VirtualHost _default_:443> ServerAdmin admin@example.com ServerName example.com ServerAlias www.example.com Alias /static … -
Django Haystack different installation backends
At the Haystack docs there is a section at the installation where it indicates where your site configuration file will live and which backend to use, as well as other settings for that backend. There are mentions to some backends and I don't know which one I should choose... Solr, Elasticsearch, Whoosh, Xapian and Simple. Which one should I choose for a search engine not that complex but also not dumb. I want to look for items in my database by the title but also being able to handle typos? I want something that is open source and that does not use JavaScript. -
django.core.exceptions.ImproperlyConfigured, Requsted setting DEBUG (?)
I am getting the following error: "django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." The only point I can think of is that the project resides on a different mapped drive than local C. Does this mean I have to edit something, like maybe global_settings.py in django? -
Django using global variables
I believe this question can be applied beyond the scope of Django, but Django is all I know: how to handle global 'resource' variables? I am concurrently working on a testing framework for this tutorial project and finding myself copy-pasting field labels and help text to ensure their validity. Going forward, anytime I need to modify the label, I need to manually modify it in my testing framework as well which goes against basic programming principles. For example, # My ModelForm class in /my/path/models.py class MyForm(ModelForm): def clean_field(self): data = self.cleaned_data[<my_field>] ... return data class Meta: model = MyModel fields = [<field_a>, <field_b>, ...] # copy-paste labels = {<field_a>: <label_a>, ...} # copy-paste help_texts = {<field_a>: <help_text_a>, ...} # copy-paste ---- # Corresponding SimpleTestCase in /my/path/test_forms.py class MyFormTest(SimpleTestCase): def setUp(self): self.form = MyForm() def test_field_a_form_label(self): expected = <label_a> # copy-paste fl = self.form.fields[<field_a>].label # copy-paste self.assertTrue(fl is None or fl == expected) ... In Android, your project contains a 'resource' directory which has all the static values (help text, titles, etc) used throughout the project. This directory can then be accessed from anywhere through Context, creating a single source of truth. What is the recommended approach in web development for … -
Django rendering Form object rather than form fields
Sure I've missed something obvious, but any help appreciated. I have a form model: class UserForm(forms.Form): name = forms.CharField() A view: def userform(req): context = {} context['user_form'] = UserForm() context['message'] = 'test message' return render(req, 'apps/userform.html', context) And a template: {% extends 'base.html' %} {% block title %} | User Form {% endblock %} {% block content %} <h1>Form page</h1> <form method='POST'> {% csrf_token %} {{ user_form }} <button type='submit'>Send</button> </form> {{ message }} {% endblock %} I'm pretty sure everything is connected correctly and imported as required - the 'message' property on context renders fine under the form. However, {{ user_form }} in the template renders the actual Form object instance, rather than the actual form field I'm expecting. I see: <userform.views.UserForm object at 0x7fcab17e5c10> Then the form submit button. What have I missed? Django 4, if that matters. -
KeyError: 'lecture' in Django Serializer
I am trying to validate the request of the model. When I try to send patch request to the model there is a problem that I face: Error: if attrs["lecture"].author.id != self.context["request"].user.pk: KeyError: 'lecture' I don't know why I am getting such error. Does anybody know why I am getting the error? Full Code: Serializers class LectureAnnouncementSerializer(serializers.ModelSerializer): class Meta: model = LectureAnnouncement fields = ("id","lecture","teacher","announcement","file","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs["lecture"].author.id != self.context["request"].user.pk: raise ValidationError('Unauthorized Request') return attrs Models class LectureAnnouncement(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) teacher = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True, related_name='lectureannouncementsteacher') lecture = models.ForeignKey(Lecture, on_delete=models.CASCADE,null=True,blank=True, related_name='lectureannouncements') announcement = models.CharField(max_length=1000, unique=False, null=True, blank=True) file = models.FileField(upload_to='images',null=True,blank=True) timestamp = models.DateTimeField(unique=False,auto_now_add=True) -
Check if Djoser user exists by email
I am currently working developing a login screen where I am using djoser for authentication. I already use the /users/ and /token/login/ endpoints to create and log in users respectively in the frontend (JS fetch) and I know that /users/ will return an error message if the user already exists (which I'm displaying with react-hook-form). My question is: is there a way of verifying if the user already exists with their email only (without trying to create an account and working it out from the error message) -
how to create class name in django formset dynamically based on foreignkey value?
How can I pass the value from the slug field from the Product model to my formset and create a dynamic class name that will contain this value? I managed to create a fixed class name form-control in each form but I don't know how to make a dynamic class so it creates the slug that is a field in the Product model. When I put "class": self.related_product it gives me 'CalculatorForm' object has no attribute 'related_product' error. My question is what should I insert here to get slug value? forms.py class CalculatorForm(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) number_of_units = forms.IntegerField(min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units') def __init__(self, *args, **kwargs): super(CalculatorForm, self).__init__(*args, **kwargs) for field in self.fields: new_data = { "class": 'form-control' #how to pass slug value here? } self.fields[str(field)].widget.attrs.update( new_data ) RequestFormset = formset_factory(CalculatorForm, extra=0, can_delete=False) models.py class CERequest(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE) class Product(models.Model): ... slug = models.SlugField(max_length=250) -
How to traverse over reversed queryset in django?
I am trying to traverse twice over one reversed object, initally the for loop works but not on the second loop. x = Subscription.objects.filter(customer_id=customer_id).order_by('-id')[:count] tmp = reversed(x) y = call_function(subs=tmp) # inside this function as well object is of type reversed and i am able to loop over it inside the call_function. for j in tmp: # this loop is not running at all. here as well tmp is a reversed object print(j) # call_function(subs=s) def call_function(s): for i in s: print(i) -
What's the proper way to define this relationship in Django?
Okay, long story short, I have a model with - among other things - the following: class Connection(Model): currentnas = models.ForeignKey(NAS, null = True, blank=True, default = None, on_delete=models.SET_NULL, related_name='active') class NAS(Model): # Various data fields currentnas is, as the name suggests, the representation of the NAS that that connection is currently connecting through. This part works fine, however, now I'm trying to add another field to Connection: permittednas = models.ManyToManyField(NAS) The intention is to check during an authentication step whether currentnas matches one of the elements in permittednas; however, my first attempt to make this work ran into a snag when python informed me that TypeError: argument of type 'ManyRelatedManager' is not iterable. To clarify, I have a number of Connections a, b, c, d and a number of NAS objects 1, 2, 3, 4, and I want to be able to say that (for example) a is permitted to connect via 1, 2 and 4; b may connect via 2 and 4; c can connect via all four, and d may only connect via NAS 1. -
Django admin Valid form with funtion clean
In my django model I defined a clean function to validate additional conditions before saving the data. Here is my model: class TestRange(models.Model): SERVICE = [ ('s1', 'Service 1'), ('s2', 'Service 2') ] service = models.CharField(max_length=2, choices=SERVICE) SDA = [ (False, 'NO SDA'), (True, 'SDA') ] sda = models.BooleanField(choices=SDA) number_start = models.CharField(max_length=10, validators=[valide_phone_number]) number_end = models.CharField(max_length=10, validators=[valide_phone_number]) def clean(self): if int(self.number_end) < int(self.number_start): raise ValidationError({'number_end': _("The end number must be greater than or equal to the start number")}) if self.sda and len(self.number_start)!=10: raise ValidationError({'number_start': _("A SDA number consists of 10 digits")}) super(TestRange, self).clean() Since the definition of this function the default validation of the admin form no longer works, I no longer have to check the fields of the form before registration. So I got an error message: invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/admin/gestnum/testrange/add/ Django Version: 4.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: C:\Users\user\Documents\DEV\test\test\models\TestRange.py, line 25, in clean Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\user\Documents\DEV\test\.venv\Scripts\python.exe Python Version: 3.9.6 how to proceed to keep the default validation and add my additional validation without the function: defaut validate adminform Do you have a solution ? Without …