Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create secure token authentication with Django Rest Framework/React?
I am currently creating a website using React for the frontend and Django Rest Framework for an API. I decided to use token authentication as I figured it would be an extensible option if I ever decide to create a mobile app in addition to my web application. At the moment, I am creating one token for each new user, and I have no method of refreshing or changing the token. On login, the frontend passes the username and password to Django, which either creates or retrieves a token and sends it back to be used for future calls to the API. This is the view I am using to do so: class GetAuthToken(ObtainAuthToken): # Used to retrieve an auth token with a username and password def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, }) The fact that my tokens never change doesn't seem especially secure and makes me think I have to rethink my authentication/authorization strategy. I'm really not sure where to go from here though, and I had trouble finding help online since my combination of React and DRF isn't especially popular … -
Django, how to join "page" argument to current link instead of replacing it
It's me again. Have not been coding in django for a while and forgot many basics :/ I'm struggling with pagination this time. My code instead of adding page arg to the main link, replaces it, what redirects me to nowhere. Here is my code. urls: urlpatterns=[ path("search/", Search.as_view(), name="search") ] GET form: <b-nav-form method="GET" action="{% url 'search' %}"> <b-form-input size="lg" v-model="search" :value="search" name="search" :cities="selected" class="mr-sm-2" placeholder="Position"></b-form-input> <b-form-input size="lg" :value="AllCities()" name="city" class="d-none" placeholder="Position"></b-form-input> <b-button size="lg" class="my-2 my-sm-0" type="submit">Search</b-button> </b-nav-form> pagination html: <nav> <ul class="pagination justify-content-center" style="margin:20px 0"> {% if objects.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ objects.previous_page_number }}"> <span>Prev</span> </a> </li> {% else %} <li class="disabled page-item"> <a class="page-link" href="#"> <span>Prev</span> </a> </li> {% endif %} {% for page in range %} <li {% if page == objects.number %} class="active page-item" {% endif %}> <a class="page-link" href="?page={{ page }}">{{ page }}</a> </li> {% endfor %} {% if objects.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ objects.next_page_number }}"> <span>Next</span> </a> </li> {% else %} <li {% if not objects.has_next %}class="disabled page-item"{% endif %}> <a class="page-link" href="#"> <span>Next</span> </a> </li> {% endif %} </ul> </nav> views: class Search(View): template_name="search.html" def get(self, request, **kwargs): search_phrase = request.GET["search"] if "city" in request.GET: cities = request.GET["city"].split(",") … -
How to cache Django rest framework generics.ListAPIView response
models.py class PaymentMode(models.Model): name = models.CharField(max_length=20) icon = models.CharField(max_length=350, default='', null=True) serializer.py class PaymentModeSerializer(serializers.ModelSerializer): class Meta: model = PaymentMode fields ='__all__' Views.py class PaymentModesList(generics.ListAPIView): queryset = PaymentMode.objects.all() serializer_class = PaymentModeSerializer URL to DRFcaching documentation can someone please help me with how I can cache this response and not do a query as I think this response will be the same for all user for a vast majority of the time. -
Running into ModuleNotFoundError: No module named 'django_elasticsearch_dsl' despite having installed "pip install django_elasticsearch_dsl"
I was trying to build a Django app with ElasticSearch DSL. I have done: pip install django_elasticsearch_dsl pip3 install django_elasticsearch_dsl pip install django-elasticsearch-dsl pip3 install django-elasticsearch-dsl However, whenever I run: python manage.py runserver The console returns the error message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_elasticsearch_dsl' Here is my code in the settings.py file, in which I think I have done what is specified in the documentation over here https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'search.apps.SearchConfig', 'django_elasticsearch_dsl', 'django.contrib.admin', 'django.contrib.auth', … -
How can I send logged user in Response?
I have created API for signup and login from rest_framework import generics, permissions, viewsets from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer from django.contrib.auth import login from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login API class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None)``` my views.py looks like this. And Response from the LoginAPI is like { "expiry": "2021-01-10T06:34:23.280110Z", "token": "d27640f364a159c0cb573cd66cadc1172606a0655bcf99fa8ceaf11f955b005e" } How can I send user's data(UserSerializer(user).data) with the response? It's an object like `{ "id": 4, "username": "test", "email": "test@gmail.com" }` I don't know what's wrong but ``` didn't work in the above:) LOL Can you help please":)) It looks like your post is mostly code; please add some more details.? -
How to add new foreignkey not present in the database?
When creating a new quote, I`ve got a new form. The form asks the user to select a contact. The contact is selected with a foreignkey and entry existing in the database. If the entry is not existing in the database, how can I give the option to add one, without having to leave the quote form? Many Thanks, -
RecursionError: maximum recursion depth exceeded while calling a Python object in Django
enter image description here pankajenv) PS F:\mydjangoexamples\myvsdjangoproject\Hospital_Management> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\hp\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\hp\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) [Previous line repeated 987 more times] File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 58, in _load_all_namespaces namespaces = [ File "F:\mydjangoexamples\myvsdjangoproject\pankajenv\lib\site-packages\django\core\checks\urls.py", line 60, in if getattr(url, 'namespace', None) is not None RecursionError: maximum recursion depth exceeded while calling a Python object -
Django add to cart as a guest without logging in
I'm working on a ecom website project and I follow Dennis Ivy's course about cart functionality. I want to add to cart whether the person is logged in or not. I place my code down below, where products are added to the cart as a order when you're logged in and everything's fine but when user is not logged in nothing happen even though I created the device key inside cookies. models: class User(AbstractBaseUser): email = models.EmailField(verbose_name='email',max_length=255, unique=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(max_length=50, default=None, unique=False, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] objects = UserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True class Guest(models.Model): name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) def __str__(self): if self.name: name = self.name else: name = self.device return str(name) class Order(models.Model): klient = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) gosc = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True, blank=True) data_zamowienia = models.DateTimeField(auto_now_add=True) dostarczona = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) produkt = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) ilosc = models.IntegerField(default=0, null=True, blank=True) data_dodania = models.DateTimeField(auto_now_add=True) … -
Django REST API TestCase Normalize Email failing
I keep failing a test case that tests whether the email passed into the create_user function is normalized correctly. However the normalize_email() method does not seem to be working properly. test_modles.py from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_new_user_email_normalized(self): """Test the email for a new user is normalized""" email = 'TEST.TES.com' user = get_user_model().objects.create_user( email, 'test1213' ) self.assertEqual(user.email, email.lower()) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custome user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_teamMember = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' error ====================================================================== FAIL: test_new_user_email_normalized (core.tests.test_models.ModelTests) Test the email for a new user is normalized ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_models.py", line 27, in test_new_user_email_normalized self.assertEqual(user.email, email.lower()) AssertionError: 'TEST.TES.com' != 'test.tes.com' - TEST.TES.com + test.tes.com ---------------------------------------------------------------------- Ran 2 tests in 0.484s FAILED (failures=1) -
Convention of error pages in Django and how to test them
I want to create custom error pages for my Django application. I have created 500 and 404 custom error pages. They work well. I have two questions about custom error pages in Django. The first question is, which HTTP status code should I create a custom error pages by convention? Maybe 400 and 403? Second question is about testing. I want to create a test for 500 status code (and for other status codes that I will include after the first question). I don't want to just "check" the custom page (by including it in the urls.py file as it suggested in previous topics, rather I want to create a unittest). I have the following test for 404: class ErrorHandlers(TestCase): def setUp(self): super().setUp() def test_404(self): response = self.client.get("/non_existing_url/") self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, 'error_pages/404.html') self.assertIn('Page Not Found', response.content.decode('utf-8')) I want to do something similar with 500 page (and other status codes). It's easy for 404 because I had to just get an invalid URL. Other status codes are more tricky. What is the proper way to check it? Should I somehow mock? -
Why i get this error IndexError at /pdf_download/6 list index out of range
I want to download a pdf file but when i discharge the second patient in the list than this error is come.. Here is my views.py def download_pdf_view(request,pk): dischargeDetails = PatientDischarge.objects.all().filter(admitted=pk).order_by('-id')[:1] dict = { 'assign_doctor': dischargeDetails[4].assign_doctor, 'admitted': dischargeDetails[4].admitted.patient_name, 'phone': dischargeDetails[4].admitted.phone, 'address': dischargeDetails[4].admitted.address, 'symptoms': dischargeDetails[4].admitted.symptoms, 'release_date': dischargeDetails[4].release_date, 'medicine_cost': dischargeDetails[4].medicine_cost, 'other_charge': dischargeDetails[4].other_charge, 'days_count': dischargeDetails[4].days_count, 'room_bill':dischargeDetails[4].room_bill, 'total_bill': dischargeDetails[4].total_bill, } return render_to_pdf('hospital/pdf_template.html',dict) Here is the photo -
Django with Mongodb not creating id
I am trying Mongodb with Django and for that I am using djongo engine. I have created a simple model with two fields class questions(models.Model): question = models.CharField(max_length=3000) answer = models.CharField(max_length=300000) I ran the makemigrations and migrate. Using the admin option I am trying to add the data but when I am adding the record its creating with id as none. Please refer the below screenshots. From similar questions from the internet I tried to add the site Id in settings.py. Delete the migration files and rerun the migration but no luck. When I checked the 0001_initial.py I found the model as below which has Id field. class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='questions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question', models.CharField(max_length=3000)), ('answer', models.CharField(max_length=300000)), ], ), ] I browse the data with Mongodb compass, there is no autogenerated ID field. Now I am stuck and not able to figure out what exactly going wrong. Please help.. Thank you. -
"non-zero exit status 1" due to pdf file not found when using pypdftk to fill pdf forms in Django project in virtual env on dev server in Windows
The following python code successfully fills out a pdf form: import pypdftk data_dict = {key:value pairs} PDF_PATH = 'form.pdf' #form to be filled out in same folder as the file executing this code out_file = 'out_file.pdf' #completed pdf file generated_pdf = pypdftk.fill_form( pdf_path = PDF_PATH, datas = data_dict, out_file = out_file, ) However, the same code used in my django project results in the following error message: Error: Unable to find file. Error: Failed to open PDF file: form.pdf Errors encountered. No output created. Done. Input errors, so no output created. ... REMAINDER OF TRACEBACK EXCLUDED FOR BREVITY IF YOU WANT TO SEE IT I'LL POST... raise subprocess.CalledProcessError(retcode, cmd, output=output) output=output) df fill_form C:\Users\Home\AppData\Local\Temp\tmpbqq__7c4 output out_file.pdf flatten subprocess.CalledProcessError: Command 'pdftk l_a_r.pdf fill_form C:\Users\Home\AppData\Local\Temp\tmpbqq_0 87495_7c4 output out_file.pdf flatten' returned non-zero exit status 1. pypdftk is installed in the virtual environment the project is running in. The pdftk server is added as a windows path variable. In the above example, and every other time this has happened the temp file referenced at the end of the error message contains all of the expected data in XML. I've tried the following combinations of code to try to make this work: Running the exact … -
Django 3 | UpdateView Movie matching query does not exist, when using 2 models
I'm hoping this is a very simple issue and I'm over complicating it. Lets say I have two models (movie and checkin). When updating a checkin object, I receive an error "Movie matching query does not exist", however creating works perfectly fine. Models class Movie(models.Model): title = models.CharField(max_length=150) genre = models.CharField(max_length=25) description = models.TextField() slug = models.SlugField() class Meta: ordering = ["title"] def get_absolute_url(self): return reverse("movie_detail", args=[str(self.slug)]) def __str__(self): return self.title class Checkin(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) movies = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name="checkins", ) notes = models.TextField(max_length=255, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="checkins", null=True, blank=True, ) class Meta: ordering = ["-added_date"] def __str__(self): return f"{self.user} checked into {self.movies.title} on {self.added_date}" def get_absolute_url(self): return reverse("checkin_detail", args=[str(self.id)]) The goal for my checkin views is to create a checkin based on the slug from the details page of the movie object. This way the user does not have to scroll through hundreds of movie objects just to find the one they are interested in. I am using get_form_kwargs() to accomplish this (which could be the problem but couldn't figure out a better way to accomplish this). class CheckinCreateView(CreateView): model = Checkin template_name = "checkin/checkin_create.html" context_object_name = "checkin_create" form_class = CheckinForm success_url … -
Autofill Django signup page with automatically generated password
I created a simple page for staff members that adds users by entering a username and password, very similar to the way users are added in the admin page. How can the password field be automatically filled with a random password instead of staff members having to manually enter one in? I have seen a method that sends the user a password-reset email, allowing them to enter their own password. This method however doesn't suit our needs. Please take it step by step as I am still new to this language. Any help is much appreciated! -
React - Django page is blank on refresh
Hello I am using Django as my backend and React as frontend. I have an issue when I refresh page and I am not on root page '/' the page goes blank. Also If Ill try to go instantly somewhere else then the home page such as /contact it is blank also. I know it is because the backend server was not contacted as it is said here. I tried to fix it with useHistory but it did not work showing useContext error. What is the best way to fix this issue with Django - React stack? main urls.py: urlpatterns = [ ... path('', TemplateView.as_view(template_name='index.html')) ] app urls.py: router = routers.DefaultRouter() router.register('frontpage', FrontpageViewSet, 'frontpage') router.register('gallery', GalleryViewSet, 'gallery') urlpatterns = router.urls React index.js: import {BrowserRouter} from "react-router-dom"; ReactDOM.render( <React.StrictMode> <BrowserRouter> <App/> </BrowserRouter> </React.StrictMode>, document.getElementById('root') ); App.js: const location = useLocation(); return ( <div className="App"> <GlobalStyle/> <Nav/> <Switch location={location} key={location.pathname}> <Route exact path='/'> <HomePage/> </Route> <Route exact path='/gallery'> <GalleryPage/> </Route> <Route exact path='/contact'> <ContactPage/> </Route> </Switch> </div> ); -
How to automatically count length of total items in Django ArrayField?
I'm trying to create a column called stock_count that counts the total number of items in an ArrayField, in my case the ArrayField is called stock_list. I've created a function in my model class that doesn't seem to do anything. class Bucket(models.Model): class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() ... stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() I would like this column to be automated, meaning whenever an item is added to an ArrayField, the stock_count automatically increments by 1. Am I on the right track to create this? -
How to resize/compress or Set default height width / stylesheet classes of Images Upload by django Ckeditor
I'm Using Django-Ckeditor for RichTextUploadField, However, some images are pretty large and I need to resize/compress before sending it to server or If i can set default width and height or Stylesheet classes I tried this but no luck: CKEDITOR_CONFIGS = { 'default': { 'stylesSet': [ { 'name': 'Image-Fluid', 'element': 'img', 'attributes': {'class': 'img-fluid'}, }, ], }, } Need your help community. Any Idea How to make this possible. My CKeditor config: gist -
How to create Django formset from jquery dynamically form?
After user fill a basic form, the data will be showed in table, dynamically created via jquery. index.html <form> <div class="row"> <div class="col-md-6 mb-3"> <label for="sourceip">Source IP:<span> *</span></label> <input type="text" class="form-control" id="sourceip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="sourceip_error_message"></span> </div> <div class="col-md-6 mb-3"> <label for="destip">Destination IP:<span> *</span></label> <input type="text" class="form-control" id="destip" placeholder="_._._._ , _._._._ , _._._._" value="" > <span class="error_form" id="destip_error_message"></span> </div> </div> <div class="mb-3"> <label for="service">Service:<span> *</span></label> <div class="input-group"> <input type="text" class="form-control" id="service" placeholder="" > <span class="error_form" id="service_error_message"></span> </div> </div> <div class="mb-3"> <label for="comment">Comment: </label> <textarea type="text" class="form-control" id="comment" placeholder="Add comment"> </textarea> </div> <hr class="mb-4"> <input type="button" class="btn btn-primary btn-lg btn-block add" value="Add rule"> </form> <div id="tabulka" class="table col-md-10"> <form method="POST" action="#" enctype="multipart/form-data"> {% csrf_token %} <!--{{ formset.management_form }}--> <table > <thead class="thead-dark"> <th scope="col">Source IP</th> <th scope="col">Destination IP</th> <th scope="col">Service</th> <th scope="col">Comment</th> <th scope="col" colspan="2">Action</th> </thead> <tbody id="tbody"> </tbody> </table> <input type="submit" value="insert record"> </form> </div> script.js $(".add").click(function () { var SourceIP = CheckIPAdresses($("#sourceip").val()); var DestIP = CheckIPAdresses($("#destip").val()); var Service = CheckService($("#service").val()); var Comment = $("#comment").val(); for (sadd in SourceIP ){ for (dadd in DestIP){ for (srv in Service){ var markup = "<tr class='table-row' > <td class='SourceIP'> <input name='sip' type='text' class='sip' readonly value='"+SourceIP[sadd] + "'> … -
How to change the default error messages displayed by Django forms
I have created a form in Django which has a charfield with max_length=255 as follows: task = models.CharField(max_length= 255) Now I want to let the user know how many characters he has typed if he exceeds the 255 characters limit, so I did the following if form.is_valid(): #some code else: messages.info(request,(form.errors.get("item").as_text())) now consider two scenarios (1) I am leaving the field blank (2) type 445 characters in the form field and submit then by default I am getting the following error messages: Scenario 1: * This field is required. Scenario 2: * Ensure this value has at most 255 characters (it has 445). but instead, I want to change these messages to: Scenario 1: No task added! Scenario 2: Error: maximum length limit is 255 characters (it has 445). So I tried the following: class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] error_messages = { 'task': { "required": ("No task added!") 'max_length': ("Error: maximum length limit is 255 characters"), }, } Now the messages have been changed to: Scenario 1: * No task added! Scenario 2: * Error: maximum length limit is 255 characters. My Problem: I don't want the * which is being displayed in front … -
raise Http404 returns 500 page instead of 404 custom page
In my app urls.py I have: handler404 = 'app.views.page_not_found' In my views.py I have: def page_not_found(request, exception): return render(request, '404.html', status=404) Entering invalid url will display the custom 404 page as should be. But when I raise 404, in views.py of some module of the Django app, it return 500 page instead of 404 page (I use raise Http404). Do I need to add something in the urls.py of that module? Why it does not show the 404 page? -
DoesNotExist at /adminpanel/ Inspector matching query does not exist
I am trying to fetch some data from the database by satisfying a particular field's value true. my models.py: class Inspector(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, related_name='inspector_releted_user') name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) nid = models.IntegerField(blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) inspector_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name Now I try to fetch only those data which case inspector_varified 's value is True. my views.py: def adminpanel(request): adminpanel_dict = { 'inspector' : Inspector.objects.get(inspector_varified=True) } return render(request, 'app/adminpanel.html', adminpanel_dict) but it shows error like: Inspector matching query does not exist. How can I fix it? -
Reason for Serializer not working in Django Project
I am working on a Django Project and added a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. I create a mode app and it has the current attributes: class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name In the views the user setting is not reflecting properly as it is always showing User don't have a setting., however the updateTheme is working perfectly fine. This is the first time I configure rest_framework to my app. from .serializers import UserSerailizer def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) else: return JsonResponse({'message': "User don't have a setting."}, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user = request.user setting = Setting.objects.update_or_create( user=user, defaults={'value': theme}, name='theme') print('Request:', theme) return JsonResponse('Updated..', safe=False) serializer.py from rest_framework import serializers from .models import * class UserSerailizer(serializers.ModelSerializer): class Meta: model = Setting fields = '__all__' Everytime a User logs in in the console I am receiving the error Data: {message: "User don't have a setting."} In the … -
django - adding new Inline form using smart-selects nothing happens
I have a code below. class Evaluation(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) class EvaluationDisability(models.Model): disability = models.ForeignKey(Disability, on_delete=models.CASCADE) disability_details = ChainedManyToManyField( DisabiltiyDetail, horizontal=True, chained_field="disability", chained_model_field="disability") # evaluation = models.ManyToManyField(Evaluation,blank=False) evaluation = models.ForeignKey(Evaluation, on_delete=models.CASCADE) class EvaluationDisabilityForm(forms.ModelForm): model = EvaluationDisability class EvaluationDisabilityInline(admin.TabularInline): model = EvaluationDisability form = EvaluationDisabilityForm extra = 1 # autocomplete_fields = ['disability_details'] @admin.register(Evaluation) class EvaluationAdmin(admin.ModelAdmin): model = Evaluation inlines = [EvaluationDisabilityInline] right there is says extra=1 So on the admin page the smart-selects is workin fine just for only 1 row. But adding new row.. smart-selects not working anymore. Same thing if i change the extra to any number. for example extra=5. smart-selects works for the first 5 rows but adding a new one will do nothing. Please help been looking for the resolution on this for weeks now -
Django - How get IP of request in a custom receiver?
I have following code: @receiver(user_logged_in) def user_logged_in_callback(sender, request, user, **kwargs): ip = request.META.get('REMOTE_ADDR') AuditEntry.objects.create(action='User logged in', ip=ip, username=user.username) It works great. In views.py I have a custom receiver: @receiver(pre_save, sender=User) def user_updated(sender, **kwargs): user = kwargs.get('instance', None) ip = request.META['REMOTE_ADDR'] if user: new_password = user.password try: old_password = User.objects.get(pk=user.pk).password except User.DoesNotExist: old_password = None if new_password != old_password: AuditEntry.objects.create(action='Password has changed', ip="127.0.0.1", username=user.username) For sure it falls with "no request found" error. I can't figure out how to extract IP. Thank you.