Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deployment not found error on deploying django project on cpanel
I have an issue in deploying my django project to cpanel after creating the python setup on cpanel pointing my subdomain to the setup project .I get 404(deployment not found) error once i click the url how can i fix that i expect the project should show the passenger_wsgi.py IT Works Screen on click of the url -
make authenticated and login work for multiple table other then auth User table django?
I have created hostTable model in hostlogin app and I want to use this table for login purpose for that i have created custom authenticate function because default authenticate() was working for auth user table only. Also login() is not attaching current session to the users from hostTable. Although it working fine if I set AUTH_USER_MODEL ='hostlogin.HostTable' but then admin page is not working also this is not acceptable solution because hostTable I will use for teaches login (127.0.0.1:8081/tlogin/) and studentlogin table I will use for student login (127.0.0.1:8081/slogin/) that time how will I use two different table for different login() and authenticate (), for non of these two users I don't want to provide admin access (127.0.0.1:8081/admin/) that's why I am not using auth user table. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser,AbstractBaseUser,PermissionsMixin from django.contrib.auth.hashers import make_password, check_password class HostTable(AbstractBaseUser): pid=models.AutoField(primary_key=True,auto_created=True) username=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=128) createdtime =models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(default=timezone.now) is_authenticated=models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS=['hostname','ownername','password'] def save(self, *args, **kwargs): self.password = make_password(self.password) super(HostTable, self).save(*args, **kwargs) def __str__(self): return self.hostname view.py def hostlogin(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') print('view',username,password) user = hostTableAuth.authenticate(request,username,password) … -
When we upload a selfie we get a 500 error [closed]
def upload_selfie_document(self,cleardil_id,document_id,selfie_image): url = f"{self.url}customers/{cleardil_id}/identifications" print(url, "url") selfie_image.seek(0) selfie_image = selfie_image.read() selfie_image_base64 = base64.b64encode(selfie_image).decode('utf-8') payload = json.dumps({ 'document_id': document_id, 'selfie_image': selfie_image_base64, }) # print(payload, "payload") headers = { **self.headers , 'Content-Type': 'application/json'} print(headers, "headers") try: response = requests.post(url, headers=headers, data=payload) print(response, "response") if response.status_code in range(400, 505): {response.text}") return None return response.json() except Exception as e: logger.error(f"Request exception: {str(e)}") return None I am trying to upload a selfie but I get response <Response [500]> response -
No output in serializermethodfield()
I defined a serializermethodfield. My problem in displaying the output. When this method exists, the image field is empty for me. But if I delete this serializermethodfield, my image output will be correct. serilizer: class ArticleSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) image=serializers.SerializerMethodField() class Meta: model=Article fields="__all__" validators=[Checktitle()] def get_image (self , obj ): request=self.context.get("request") if obj.image: image_url=obj.image.url return request.build_absolute_uri(image_url) return None view: class ArticleListview(APIView): def get(self,request): query_set=Article.objects.all() ser = ArticleSerializer(instance=query_set,many=True,context={'request':request}) print(request) return Response(data=ser.data) I wanted to change the url image. But by defining this method, the image is not saved at all. -
Unable to start Django app, error related to what seems like a circular import?
I'm currently attempting to build my first django app, a resume website. I get this error when trying to start the app. <class 'mainapp.admin.CertificateAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'is_active', which is not a callable, an attribute of 'CertificateAdmin', or an attribute or method on 'mainapp.Certificate'. This is what I have in my models.py file related to "certificate" (comments included): `class Certificate(models.Model): class Meta: verbose_name_plural = 'Certificates' verbose_name = 'Certificate' date = models.DateTimeField(blank=True, null=True) # When the certificate was earned name = models.CharField(max_length=50, blank=True, null=True) # Name of the certificate title = models.CharField(max_length=200, blank=True, null=True) # Title or description of the certificate description = models.CharField(max_length=500, blank=True, null=True) # Additional details about the certificate is_active = models.BooleanField(default=True)` And this is what I have in my admin.py file: @admin.register(Certificate) class CertificateAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'title', 'is_active') # Display 'id', 'name', and 'is_active' fields ChatGPT has been no help so far, only circular answers to make sure 'is_active' is properly called, I'm not sure it is, it seems like it (I'm sort of a beginner). I'm following instructions from a youtube video (yes, I have been learning python and django since last year, did not follow THAT blindly!), the "is_active" … -
Memcached-MemcacheIllegalInputError - Data values must be binary-safe: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128
I'm doing some tests with memcached on my django project to understand if I can get benefit of it. But I stuck at unicode character caching. I read many article about it but still could not understand how can I make it work. Here is my code block: def cache(request): client = Client("127.0.0.1:11211") cache_key = '123' # needs to be unique cache_time = 86400 # time in seconds for cache to be valid data = client.get(cache_key) # returns None if no key-value pair if not data: print("setting cache") #data contains unicode characters - Throws an error datafromdb = Subject.objects.all() #unicode characters - Throws an error unicodestr="abçüıö" #encoded unicode characters - Working fine encodedunicodestr=str.encode("abçüıö") client.set(cache_key,unicodestr , cache_time) else: print("getting from cache") return HttpResponse(data) So If I use str.encode on text values It works fine and data can be cached. But If I retrieve data from database(postgres) and this data contains unicode memcached throws an error. I'm wondering if is there a way to use str.unicode on my queryset/list etc that returned from database or something else may be. -
Unit Test pipeline - Django Unit tests
I am working on a django project and it has 20+ apps in it which means i have to run tests of 20+ apps which includes 3000+ tests. So I decided to make subjobs in my pipeline and now running 20 jobs for the unit tests on commit. But the issue is that when more than 1 developer commits and tests runs for both, pipeline get stucks. Pipeline runners are registered on a VM of 32 CPU cores and 24 GB of RAM. CPU utilization becomes 100% and jobs stuck(deadlock). How can I optimize my pipeline subjobs so that if multiple devs work it didnt stuck. unit_test: stage: test rules: - changes: - backend/ tags: - workstream-unit-test when: manual allow_failure: false parallel: matrix: - APP_NAME: - apps.app1 - apps.app2 - . - apps.app20 before_script: - apt-get update - apt-get install -y unixodbc unixodbc-dev - pip install virtualenv - virtualenv venv - source venv/bin/activate - pip install -r requirements.txt script: - COVERAGE_FILENAME=$(echo "$APP_NAME" | tr '.' '_')_coverage.xml - coverage run --source=$APP_NAME ./manage.py test $APP_NAME --settings=hrdb.test_settings --keepdb --noinput - coverage xml -i -o $COVERAGE_FILENAME - coverage report -m --fail-under=90 --skip-covered coverage: '/(?i)TOTAL.*? (100(?:\.0+)?%|[1-9]?\d(?:\.\d+)?%)$/' artifacts: expire_in: 2 hour paths: - $CI_PROJECT_DIR/$APP_NAME_coverage.xml I am … -
Find Template in django
My code is like below. {% if request.path != '/login/' %} {% include "/hospital/templates/header.html" %} {% endif %} I am getting error TemplateDoesNotExist at /dashboard/ /hospital/templates/header.html How to include a template ? -
Django Rest Framework APIClient login is not working
I have test function to test whether user can login or not. I am using DRF's APIClient and logging in. When I do a get request to a protected API endpoint I get 401 response. I tried to print: print(client.login(username='instructor', password='asdf')) And it is returning True, which means user is found and logged in. But still when I do: response = client.get(reverse('recommend-list')) I am getting 401. Here is my test function: ` def test_user_authentication(self): client = APIClient() user_data = { 'username': 'instructor', 'email': 'myemail@example.com', 'password': 'asdf' } client.post(reverse('user-list'), user_data, format='json') self.assertTrue(User.objects.filter(username='instructor').exists()) print(client.login(username='instructor', password='asdf')) response = client.get(reverse('recommend-list')) self.assertEqual(response.status_code, 200) ` Here is how I create a new user: `class UserViewSet(viewsets.ViewSet): def create(self, request): serializer = UserSerializer(data=request.data) User = get_user_model() if serializer.is_valid(): validated_data = serializer.validated_data try: user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) return Response({'id': user.id, 'username': user.username}, status=status.HTTP_201_CREATED) except IntegrityError: return Response({'error': 'Username is already taken.'}, status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` Making get request to here: `class RecommendViewSet(viewsets.GenericViewSet): authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] def list(self, request): user_id = request.user.id movies = recommend_movies_for_user(user_id) return Response({"message": movies}, status=status.HTTP_200_OK) ` -
I want to add social links to my template in django
<ul class="list-unstyled d-flex"> <li class="ms-3"><a class="link-body-emphasis" href="#" ><i class="fa-brands fa-square-github fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-facebook fa-lg" ></i></a></li> <li class="ms-3"><a class="link-body-emphasis" href="#"><i class="fa-brands fa-linkedin fa-lg" ></i></a></li> </ul> i want to add social links of my facebook , github and linkedin how can i do that in django without writing a view or url path just pasting my social links in href did'nt working -
how to save image in Django project
when i try to create new employee in my project the instance has been save but image not. here is my model,view and form from my django project my model- `class Emp(models.Model): emp_first_name=models.CharField(max_length=20,null=False) emp_last_name=models.CharField(max_length=20,null=False) emp_father_name=models.CharField(max_length=15,blank=False,default='') emp_mother_name=models.CharField(max_length=15,blank=False,default='') emp_photo=models.ImageField(null=True,blank=True,upload_to='static/image/emp',)` my view- `def EmpAdd(request): if request.method=='POST': form=EmpForm(request.POST,request.FILES) if form.is_valid(): form.save() messages.success(request,'New Employee has been added') else: messages.error(request,'There has been error') else: form=EmpForm() return render(request,'emp/emp_crt.html',{'form':form})` my form - `class EmpForm(ModelForm): class Meta: model=Emp fields='__all__' widgets={ 'emp_id':TextInput(attrs={'class':'form-control',}), 'emp_bod':DateInput(attrs={'type':'date','class':'form-control',}), 'emp_first_name':TextInput(attrs={'class':'form-control',}), 'emp_last_name':TextInput(attrs={'class':'form-control',}), 'emp_father_name':TextInput(attrs={'class':'form-control'}), 'emp_mother_name':TextInput(attrs={'class':'form-control'}), 'emp_photo':FileInput(attrs={'class':'form-control'}), }` when i try to creat new employee in my django project, new employee has been created but image has not been saved.what should i do? -
type error in api profile in django rest framework
typeError at /api/profile/ init() got an unexpected keyword argument 'write only' Request Method: GET Request URL: http://127.0.0.1:8000/api/profile/ Django Version: 3.2.25 Exception Type: TypeError Exception Value: init() got an unexpected keyword argument 'write only' Exception Location: /home/vagrant/env/lib/python3.6/site-packages/rest_framework/fields.py, line 738, in init Python Executable: /home/vagrant/env/bin/python3 Python Version: 3.6.9 Python Path: ['/vagrant', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/vagrant/env/lib/python3.6/site-packages' everything in the code was correct, can't able to access the api/profile page in django server. -
How to fetch all the API urls from django project in Python?
I have a django project, where some API URLs are present in urls.py in urlpatterns path and some are registered as routers(rest_framework_extensions.routers). ref: # urls.py urlpatterns = [ path("healthcheck/", health_check_view, name="healthcheck"), path("something/", include(router_something.urls)) ] here, router_something is being used to register further urls like: router_something = DefaultRouter(trailing_slash=False) router_something.register(r"path1/(?P<pk>\d+)/roles", SomeViewSet) I want to fetch all the urls in the django project with their complete path, for example: healthcheck/ something/path1/1/roles # here i am replacing the placeholder pk with 1, this is something I can do ... -
triggers error in admin default not showes. Why?
InternalError at /admin/entities/branch/add/ The type of building does not match the expected type: 'Branch' CONTEXT: PL/pgSQL function check_outlet_type_consistency() line 9 at RAISE How show in default django admin this error? googled, :( but no info -
I can't import TinyMCE
HELLO. No matter what I did, I couldn't import Tinyemc. I don't just get this error on Tinyemc; This problem exists in everything that is similar. [enter image description here](https://i.sstatic.net/5GjZoaHO.png) [enter image description here](https://i.sstatic.net/BHWlmsFz.png) [enter image description here](https://i.sstatic.net/65a3OvdB.png)your text` I couldn't find a solution to the problem in any way.`your text`` -
Text with Image Django Admin
i'd like to know how can i have a fancy editor in django admin, that can add images inside the content, like ckeditor, but when it saves, it converts all in base 64 and store it in the database istead uploading the files to a media folder. Thanks. I've tried to use ckeditor 5, but it stores the images appart the content in a separated folder. -
default datetime value at django form
i'm trying to use a default value class MSeguimientoEtnicoForm(forms.ModelForm): ... fecha_reporte = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'form-control'})) ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Establece la fecha y hora actuales como valor inicial para fecha_reporte self.fields['fecha_reporte'].initial = timezone.now() template: <div class="col-sm-4"> <div class="form-group"> <label for="fechaReporte">Fecha Reporte: </label> <input class="form-control" id="fechaReporte" type="datetime-local" name="fecha_reporte" required> </div> </div> but doesn't take the timezone.now() value at the view template view and default value don't working i was searching for aroud but i didn't found nothing -
Create superuser in ktor
in django, there's manage.py createsuperuser for creating a user with elevated privileges. For ktor, I have resorted to creating a user programmatically when the app starts, (first checking if the user already exist) Is there a more elegant or standard way of doing this? I assume it would be a similar process in other frameworks, express, flask etc since they don't also have that -
I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem
def txttopdf(request): if request.method == 'POST': txt = request.FILES['txt'] pdf = fpdf.FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt.read().decode('utf-8'), 0, 1) return HttpResponse(pdf.output(dest='S'), content_type='application/pdf') return render(request, 'txttopdf.html') I create the pdf file but I cannot view its content. I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem. -
Django allauth: Unable to get Access token when login using google social account
I am using django allauth for google authentication. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-9#c!e&s(-o9-6u^mt#w(w6s$ober^f(m45)=f)=m&zo1$dlcg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'allauth', # Social login App 'allauth.account', # login App 'allauth.socialaccount', # Social login App 'allauth.socialaccount.providers.google', # Google login App 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "API", # API APP ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware" ] ROOT_URLCONF = 'MassMail.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.normpath(os.path.join(BASE_DIR, 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', # requirements for django-all-auth ], }, }, ] WSGI_APPLICATION = 'MassMail.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Google Authentication … -
Django Unit Test Fail when i test UpdateView
In my project i have UserUpdateView like this: class UserUpdateView(AuthenticationMixin, AuthorizationMixin, SuccessMessageMixin, UpdateView): '''Update User info(username, full/second name, password)''' model = User form_class = UserForm template_name = 'form.html' permission_denied_message = _("You can't change this profile, this is not you") permission_denied_url = reverse_lazy('users-detail') success_message = _('User Profile is successfully changed') success_url = reverse_lazy('users-detail') extra_content = { 'title': _('Update user'), 'button_text': _('Update'), } User model like this: class User(AbstractUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) def __str__(self): return self.get_full_name() And test for UserUpdateView: class UpdateUserTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='tota123', first_name='Andrey', last_name='Totavich', password='lexA456132') def test_update_user(self): self.client.login(username='tota123', password='lexA456132') response = self.client.post( reverse('user-update', kwargs={'pk': self.user.pk}),{ 'username': 'tota321', 'first_name': 'Sergey', 'last_name': 'Simo', 'password1': 'lexA456132', 'password2': 'lexA456132' }) self.assertEqual(response.status_code, 302) # Redirect after successful update self.assertEqual(self.user.username, 'tota321') The tests result: self.assertEqual(self.user.username, 'tota321') AssertionError: 'tota123' != 'tota321' - tota123 ? -- + tota321 ? ++ How can i solve this problem & why model of user dont change? When i run my project localy - i can change user info, and it work, UserUpdateView works correctly. What i missing ? -
AttributeError while loading pickle file from views.py
I am getting AttributeError: Can't get attribute 'predictionFunction' on <module 'main' from location of manage.py . When I don't register the viewfunction in the url, the predictionFunction gets loaded but when I register it in the urls it shows error. For your reference here is what my views.py file looks like: api_view(['GET']) def predictLaptopPrice(request): parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) file_path = os.path.join(parent_dir, 'predictionFunction.pkl') print("File path:", file_path) with open(file_path, 'rb') as file: predictionFunction = pickle.load(file) file.close() print("Loaded prediction function:", predictionFunction) processor_speed = request.GET.get('processor_speed') ram_size = request.GET.get('ram_size') storage_capacity = request.GET.get('storage_capacity') result = predictionFunction([[processor_speed, ram_size, storage_capacity]]) return Response({'price': result[0]}, status=status.HTTP_200_OK) I searched everywhere what this error is about but don't know what is happening. -
How to filter a queryset by a many2many field
I have a Notification model which has a field called seen_users like so: from django.contrib.auth import get_user_model User = get_user_model() class Notification(models.Model): title = models.CharField(max_length=255) seen_users = models.ManyToManyField(User, blank=True) Whenever a user sees a notification (.e.g notification_obj), that user will be added to notification_obj.seen_users. Now how can I filter notifications that has not seen by a specific user like user1 In most efficient way? I've tried to query like below: class NotificationView(generics.ListAPIView): authentication_classess = [TokenAuthentication] permission_classes = [] def get_queryset(self): unseen_only = self.request.GET.get("unseen_only", "0") if unseen_only == "1": # THIS IS WHERE I GOT TROUBLES # Because other users may have seen this and its not empty return Notification.objects.filter(seen_users__in=[]) return Notification.objects.all() -
Django forms, blank line
In my Django form I have a blank line (_____) when I look at my choices, how to fix this? Trying to remove this line Here is the code special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')]) -
Why celery doesn't run the code and how can i fix it?
I'm developing an api in django, for this api I need to use celery to do delayed actions. eventually, the aim would be to remove data from the database after a certain period of inactivity. I've set up celery and Rabbitmq, but when I try to execute something with a print to try nothing happens. here's how I set up celery in settings.py: #celery settings import ssl CELERY_BROKER_URL = 'amqps://guest:guest@localhost:5671/' CELERY_BROKER_USE_SSL = { 'ca_certs': '/etc/rabbitmq/cacert.crt', 'keyfile': '/etc/rabbitmq/key.pem', 'certfile': '/etc/rabbitmq/cert.crt', 'cert_reqs': ssl.CERT_REQUIRED } CELERY_RESULT_BACKEND = "rpc://" here's the code I'm trying to run: from __future__ import absolute_import, unicode_literals from celery import shared_task from django.utils import timezone from datetime import timedelta #DELAY_FOR_DATA_DELETION = timedelta(days=30) # 30 jours par exemple @shared_task def delete_user(): print("test") return that's how I call the function: delete_user.apply_async(countdown=5) and here's how I set up the celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') app = Celery('base', broker="amqps://guest:guest@localhost:5671/") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() I've tried to do “celery status” to see the worker status but I get this error # /home/transcendence/venv/bin/celery status Traceback (most recent call last): File "/home/transcendence/venv/lib/python3.11/site-packages/amqp/connection.py", line 515, in channel return self.channels[channel_id] ~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: None During handling of the above exception, another …