Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Unable to log in with provided credentials."
When I tried to login and get the token, I get this error(with superuser works without error.): { "non_field_errors": [ "Unable to log in with provided credentials." ] } I am sure that I am sending the correct password and login I searched a lot for an answer and met someone. He says that the problem is that the password is encrypted on the base and I send it in plain text. If someone understands, please help! My code: Settings.py DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': False, 'SERIALIZERS': {}, } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('auth/', include('djoser.urls.jwt')), ] -
Django - Redis SESSION_ENGINE only allow one session at a time
I would love to use redis (django-redis-cache) at my website as SESSION_ENGINE and site cache. The problem is that I only want to allow one session per user at a time. Previously It did that using the following signal: @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions old_sessions = Session.objects.filter(usersession__user=user) if request.session.session_key: old_sessions = old_sessions.exclude(session_key=request.session.session_key) old_sessions.delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) and the following model: class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) which was working pretty well so far. Sadly I made the experience that when using a scaleable Database like Galera wired HTTP error 400 are getting returned by my site as the session key seems to be unreachable on high I/O, that's why I wanted to switch over to Redis and have it all located at the In-Memory Database Redis provides. But how I can fetch session keys to check if there is already a session existing for a user and if so delete the session like shown above ... Thanks in advance -
Make Calculations and Output result
I am creating an App using Django and React. I would like the user to input several numeric values on the Frontend and based on these values to perform some calculations and output the result in the Frontend (also store the values in the database). I am confused on where on the backend I should add the logic to perform the calculations. On views.py or admin.py or on another file? I am currently trying to create the logic on the admin.py file but I am not sure if this will allow me to make the result visible on the frontend. -
Sort by aggregated foreign field in Django ModelAdmin changelist
In my current project I am trying to set up a simple testing app in Django. For management I use the generated Django admin, but I struggle to include a sortable computed field with best test result in changelist view of a model. My models are as follows (simplified): class Candidate(models.Model): name = models.CharField(max_length=255, null=False) email = models.EmailField(unique=True, null=False) class Test(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, null=False) result = models.PositiveIntegerField(null=True) class Question(models.Model): text = models.TextField(null=False) correct_answer = models.CharField(max_length=1, choices=OPTIONS, null=False) class Answer(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=1, choices=Question.OPTIONS, null=True) A candidate may have multiple tests and I want to display a field with his best result in the changelist view and be able to sort by it. The result is a percentage of correct answers (Answer.question.correct_answer == Answer.answer) out of all answers with the same test FK. Discovered I cannot use a custom computed field defined by a function, because Django then cannot sort by it as sorting needs modification of a queryset which translates directly to SQL. So I added the Test.result field with calculated percentages (which denormalized the scheme :-/ ) and try to add annotated field in queryset with SELECT MAX(Test.result) … -
Django - Login page with Username, Company Code and Password
How to create a custom field in the User model where besides email and password it will also require Company Code in the Login page. I am currently using the default Forms and Views that comes with User. forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] urls.py path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), -
Django: Unable to load embedded PDF dynamically
I'm trying to display a PDF (uploaded by the user) in my template in an embedded frame. What's strange is that the url only works if I use an anchor tag but not if it's embedded. I get : Template ✓ Works <a href="{{booking.lease.url}}">Lease</a> (url = http://127.0.0.1:8000/media/leases/lease_CZORz79.pdf) X Doesn't Work <embed src="{{booking.lease.url}}" width="500" height="375" type="application/pdf"> (url = http://127.0.0.1:8000/media/leases/lease_CZORz79.pdf) (ie, exact same) Views.py def review_lease(request, pk): booking = Booking.objects.get(id=pk) context= { 'booking': booking, } return render(request, 'dashboard/review_lease.html', context) Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] Models.py class Booking(models.Model): status = models.PositiveSmallIntegerField(choices=BOOKING_STATUS_OPTIONS, default=0) tenant = = models.ForeignKey('TenantProfile', on_delete=models.CASCADE, related_name='booking') lease = models.FileField(upload_to='leases/', null=True) -
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] + "'> …