Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can extends + with?
I need to pass the value from the template when connecting extends. So that I can check whether to connect the style or not. I need to pass the page title, is main page {% extends "base_not_auth.html" with page="main" %} If main page, i use css file {% if page == "main" %} <link rel="stylesheet" href="{% static 'css/page.css' %}"> {% endif %} -
user.is_authenticated works in html but not views
I just learned about the django.contrib.auth built-in package and am trying to implement user authentication for my blog application! Doing user.is_authenticated in my html works: <div class="footer"> <div class='sub-footer'> <ul style="list-style:none;"> <li>-<a href="{% url 'login' %}">Admin, Login Here!</a></li> <li>- <a href="https://www.flaticon.com">Pencil Icon made by </a><a href="https://www.flaticon.com/authors/becris">Becris </a><a href="https://www.flaticon.com">from www.flaticon.com</a> <li>- <a href="https://www.flaticon.com">Heart Icon made by </a><a href="https://www.flaticon.com/authors/gregor-cresnar">Gregor Cresnar </a><a href="https://www.flaticon.com">from www.flaticon.com</a> </ul> </div> </div> {% if user.is_authenticated %} yo whats good authenticated user {% endif %} But, when I try this in my views: if user.is_authenticated: return render(request, 'admin.html', context) return render(request, 'registration.html') I get this error: NameError at /admin-dash/ name 'user' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/admin-dash/ Django Version: 3.1.2 Exception Type: NameError Exception Value: name 'user' is not defined Exception Location: C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view Python Executable: C:\Users\benja\anaconda3\envs\mysite\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\benja\\Desktop\\mysite\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib', 'C:\\Users\\benja\\anaconda3\\envs\\mysite', 'C:\\Users\\benja\\anaconda3\\envs\\mysite\\lib\\site-packages'] Server time: Sun, 10 Jan 2021 00:03:09 +0000 Traceback Switch to copy-and-paste view C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\benja\anaconda3\envs\mysite\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\benja\Desktop\mysite\mysite\blog\views.py, line 137, in admin_view if user.is_authenticated: … ▶ Local vars It makes sense, but I … -
How to autofocus a Charfield in a Django ModelForm
In my django app I want to set focus to the first CharField (task) when the page loads. my models.py is from django.db import models class ListModel(models.Model): task = models.CharField(max_length=255) status = models.BooleanField(default=False) def __str__(self): return f"{self.task} : {str(self.status)}" and forms.py is from django.forms import ModelForm from .models import ListModel class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] I have tried adding the following widget in my CharField (in models.py): task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True}) but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput' I have also tried adding the following to the ListForm class (in forms.py): def __init__(self): self.fields['task'].widget.attrs.update(autofocus = 'autofocus') though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField? -
Setup a ready signup template in django instead of the UserCreationForm
So I have a designed signup form template in html & css and I want to know how to setup it in Django instead of using its forms -
Django Rest how to test a DELETE request using pytest
So i'm trying to test deleting a post. my post view is using RetrieveUpdateDestroyAPIView which enable me to use GET, PUT and DELETE requests. but for some reason I get a testing error saying: Method Not Allowed @pytest.fixture def delete_post(api_client): post_id = Post.objects.all()[0].id delete_post_url = '/posts/{post_id}/' delete_post = api_client.delete(delete_post_url) return delete_post @pytest.mark.django_db def test_post_detail_render(self, api_client, login, create_post ,delete_post): delete_post_page_render = delete_post assert delete_post_page_render.status_code == 200 E assert 405 == 200 E + where 405 = <HttpResponseNotAllowed [GET, HEAD, OPTIONS] status_code=405, "text/html; charset=utf-8">.status_code WARNING django.request:base.py:101 Method Not Allowed (DELETE): /posts/{post_id}/ WARNING django.request:log.py:224 Method Not Allowed: /recipes/{recipe_id}/ -
Django3 ListView with Conditional WHERE
I have simple ListView in Django 3: path("show/<int:pk>", ApplicantListView.as_view(), name='applicant-list'), my view is as follow: class ApplicantListView(ListView): model = Applicant paginate_by = 100 template_name = 'applicant_list.html' and the model class Work(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(False) date = models.DateTimeField() def __str__ (self): return self.title class Applicant(models.Model): name= models.CharField(max_length=200) email = models.EmailField(max_length=100) country = CountryField(blank_label='(select country)') work= models.ForeignKey(Work, on_delete=models.CASCADE) upload = models.FileField(upload_to='up/') def __str__ (self): return self.name so what I would like to achieve is to show only the applicants for the work ID used in the URL path. At the moment it shows all the records diregrading the pk used in the path. -
"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 …