Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to permanently store the data from my django website into a sqlite3 database?
I am trying to build a Resume Parser website using Django which is connected with a SQLite3 database. The parsed data from the resumes I upload gets stored in the database but whenever I refresh my website it disappears. What I want is to permanently save that parsed data into my database and whenever new data is being added, it should have the previous data and the new data should be added to it. I am new to Django, so this is something I don't know. Any help would be appreciated. I am including my models.py file below. from django.db import models from django import forms from django.forms import ClearableFileInput # for deleting media files after record is deleted from django.db.models.signals import post_delete from django.dispatch import receiver class Resume(models.Model): resume = models.FileField('Upload Resumes', upload_to='resumes/') name = models.CharField('Name', max_length=255, null=True, blank=True) email = models.CharField('Email', max_length=255, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=1000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True) college_name = models.CharField('College Name', max_length=1000, null=True, blank=True) designation = models.CharField('Designation', max_length=1000, null=True, blank=True) experience = models.CharField('Experience', max_length=1000, null=True, blank=True) uploaded_on = models.DateTimeField('Uploaded On', auto_now_add=True) total_experience = models.CharField('Total Experience … -
What's wrong here? It says, services.app Additional property enviornment is not allowed
version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" enviornment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword -
what is difference between room.host.id and room.id in my code
{% for room in rooms %} {% if request.user == room.host %} Edit Delete {% endif %} @{{room.host.username}} <a href = {% url 'room' room.id %}>{{room.id}} >>>{{room.name}} {{room.topic.name}} #views def userProfile(request, pk): user = User.objects.get(id=pk) context={'user':user} return render(request, 'profile.html', context) -
How to Register a user either by Email ID or by Mobile Number in Django?
I can register a user getting both email address and mobile number in my application. But what I really want is to register a user using either email or mobile number. So that if a user provides email address, it must be saved in email field in database and if user provides mobile number, it must be saved in mobile field in database. Also I need to send an activation link if the user provides an email address. Otherwise I need to send an OTP or activation link to the mobile number. Please suggest me a better way to accomplish this task. -
How To Implement Custom Password Hashing in Django?
So my manager has asked me to implement Base64 Password Encryption for our django website. I can't find any base64 hashing algo in django.contrib.auth.hashers. So, I figured that I'd have to write my own Hasher module. Problem is, I don't know how. I have tried reading the django documentation but its still unclear to me. I just need my User's Passwords to be stored using Base64 Encryption in the database. Also, I need my Custom User Authentication to work accordingly. Here's my User Model: from django.contrib.auth.models import AbstractUser from .managers import UserManager class User( AbstractUser ) : email = models.EmailField( verbose_name = 'Email Address', unique = True, null = False ) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__( self ) : return self.get_username() Here's my User Manager: from django.contrib.auth.models import BaseUserManager class UserManager( BaseUserManager ) : def create_user( self, email = None, password = None, first_name = None, last_name = None ) : try : user = self.model( email = self.normalize_email( email ) ) user.set_password( password ) user.is_active = True user.first_name = first_name user.last_name = last_name user.save( using = self._db ) return user except Exception as e : raise Exception( e ) def … -
How to compose Django Model Filter for relation existence?
How can I run the following query using Django Models? SELECT * FROM TABLE_A WHERE (SELECT COUNT(id) FROM TABLE_B WHERE TABLE_A.field1 = TABLE_B.field1) > 0 I want to select records from Table_A that have matching records in Table_B. -
Download byte range requests support for firebase storage
Am trying to narrow down a problem and knowing if firebase storage supports byte range requests for video downloads will help. I can't seem to find that information anywhere. My web app includes video streaming functionality (You-tube style) and I wonder if this is the best choice. If not what better alternative to host the videos? I have already implemented this as follows but my videos plays in all devices and browsers except iphones and ios devices: <video width='100%' height='315' poster='{{ value.image }}' controls loop muted playsinline> <source type='video/mp4' src='{{ value.video }}'> </video> Based on extensive research here and other resources online, Solutions seems to be adding controls playsinline muted to the video tag seemed to work, mine didn't with these. The other problem was video-container type. Have confirmed that mine is mpeg4 container and displayed with video/mp4 in the source type. Last issue I see is that server might not support byte range requests, am trying to determine if this is it with firebase before deciding to move on to another video storing solution. (And any suggestions for these?) Thanks. -
Need to get the Total hours calculated from the multiple entries of hour field in django rest framework
serializers class Consolidated_serializers(serializers.ModelSerializer): project_name = serializers.CharField(source='project.project_name') username = serializers.CharField(source='user.username') user_id = serializers.CharField(source='user.id') class Meta: model = Timelog fields = ('id','username','user_id','project_name','date','hours',) viewset class Total_hours_viewset(viewsets.ModelViewSet): queryset = models.Timelog.objects.all().annotate(sum_delta=Sum('hours')) serializer_class=serializers.Consolidated_serializers the result Iam getting is [ { "id": 13, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" }, { "id": 14, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" } ] But the result i Need is [ Total hours: 16:00:00 { "id": 13, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" }, { "id": 14, "username": "vinoth", "user_id": "14", "project_name": "Inhouse Timesheet", "date": "2022-03-24", "hours": "08:00:00" } ] I tried using the above code but i couldn't able to get the total hours in the json view for multiple entries. Can you please help me to get the total hours by adding the multiple entries of hour field in the model. -
Hindi Conversion is not working with django translation
I am new to django and i am trying to use internationalization feature to translate the content of page. I am able to convert it in languages like French , German but when i am trying to use Hindi it does not work at all. Settings.Py """ Django settings for prj project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_PATH=os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-m$v&xn!i6jcv4pp^!$p)^%h#xolpod8&969@9x!%*wpyxtm2o7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'prj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_PATH], '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', ], }, }, ] WSGI_APPLICATION = 'prj.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases … -
Why does 127.0.0.1:80 not work in apache virtualhost?
I can work around this, but I'd like to understand better what's going on. Using Apache 2.2 on Ubuntu, in a local development environment, a virtual host with *:80 as the address works, but 127.0.0.1:80 doesn't. Neither does localhost:80. I only have one .conf file with virtual hosts in it besides the main appache2.conf file. Here's what's in that separate vhosts file: <VirtualHost CCNM-378B:80 # Does not work. (CCNM-378B is what 'hostname' from the command line says) <VirtualHost 127.0.0.1:80 # Does not work. <VirtualHost localhost:80 # Does not work. <VirtualHost *:80 # WORKS ServerName localhost In etc/hosts I have: 127.0.0.1 localhost access.log says: 127.0.0.1:80 ::1 - - [24/Mar/2022:16:31:12 -0600] "GET /favicon.ico HTTP/1.1" 404 487 "http://localhost/ideatree/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36" In apache2.conf I have: ServerName 127.0.0.1 #ServerName localhost But neither of these seem to make a difference. The app that Apache is serving is a Django app. The Apache docs say the following about vhost name resolution, but it doesn't explain why this is happening since the base apache2.conf defines '127.0.0.1' as ServerName but that isn't recognized in the VirtualHost. If a VirtualHost doesn't specify a ServerName, a server name will be inherited … -
How to restrict Django user account creation to given usernames / addresses / practical values?
We've set up Django user account creation / login through this tutorial, and we've restricted content to auth'd users only through the likes of {% if user.is_authenticated %} and if request.user.is_authenticated. All works great. But there's still nothing stopping anyone from going to the site and registering an account providing any values for username / email address / password. We want to restrict user account creation to specific usernames / emails / IPs / any practical value. Could we check if a value is in some whitelist by inserting something like if email in ['whitelistedemail@example.com']: somewhere? Something that emails out an invite link? We've found the docs on Permissions and Authorization and many SO questions on customizing functionality for types of users, yet we couldn't find any on restricting account creation itself, so perhaps we're missing something. We could start creating different types of users, but we're wary of getting ahead of ourselves by attempting a more advanced solution before figuring out this basic step. Are we approaching this in the right way? -
Django Dockerfile: the difference between Linux Run/Build dependencies
I'm writing a multi-stage / multi-profile Dockerfile for a Wagtail (Django) app. I took this example as my starting point. Also there are two similar examples: Bakery Demo App / AccordBox article. [01] RUN set -ex \ [02] && RUN_DEPS=" libexpat1 libjpeg62-turbo libpcre3 libpq5 \ [03] mime-support postgresql-client procps zlib1g \ [04] " \ [05] && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \ [06] && apt-get update && apt-get install -y --no-install-recommends $RUN_DEPS \ [07] && rm -rf /var/lib/apt/lists/* [08] [09] ADD requirements/ /requirements/ [10] [11] RUN set -ex \ [12] && BUILD_DEPS=" build-essential git \ [13] libexpat1-dev libjpeg62-turbo-dev \ [14] libpcre3-dev libpq-dev zlib1g-dev \ [15] " \ [16] && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ [17] && python3.9 -m venv /venv \ [18] && /venv/bin/pip install -U pip \ [19] && /venv/bin/pip install --no-cache-dir -r /requirements/production.txt \ [20] && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $BUILD_DEPS \ [21] && rm -rf /var/lib/apt/lists/* What's the essential difference between RUN_DEPS and BUILD_DEPS? Why libjpeg62-turbo-dev is inside the BUILD_DEPS and libjpeg62-turbo is inside RUN_DEPS list and not vice versa. How do I know what is the comprehensive list of all required RUN_DEPS / BUILD_DEPS for Wagtail … -
ModuleNotFoundError: No module named 'verify_email.apps'
I am getting an error while trying to run my Django projects. I have run the Django server before on my PC but ever since I installed Anaconda my projects would not work anymore. Please Help Below is the error message. (pyEnv) C:\Users\giova\Documents\giosroom\giosroom>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\giova\Documents\giosroom\giosroom\manage.py", line 22, in <module> main() File "C:\Users\giova\Documents\giosroom\giosroom\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site- packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site- packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\apps\config.py", line 212, in create mod = import_module(mod_path) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'verify_email.apps' -
Como dar permisos a mis usuarios por el admin de django?
Cuando intento darle algun permiso a algun usuario mediante el administrador de django me salta ese error cuando intento guardarlo, alguien me puede ayudar -
Django - How to filter queryset of model, using field two table away
I have three models: class Classroom(models.Model): classroom_subject = models.CharField(max_length=100) classroom_code = models.CharField(max_length= 5, default = '00000') teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_name = models.CharField(max_length=100) classes = models.ManyToManyField(Classroom, blank = True) class WorkItem(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) work_description = models.CharField(max_length=500) date_assigned = models.DateField(auto_now_add=True, blank=True) time_assigned = models.TimeField(auto_now_add=True, blank=True) submission = models.ForeignKey(UserUpload, null = True, on_delete=models.CASCADE) I'm trying to return a queryset of WorkItem objects and filter the queryset through self.request.user. The model WorkItem is related to Classroom, and classroom is related to student. I have tried: x = WorkItem.objects.filter( classroom__student = self.request.user ) Basically the problem is how to reference a field two tables away, because from WorkItem, I need to reference Classroom, then from Classroom I need to reference Student. I don't know how to do this. Thanks for reading my question, any help would be greatly appreciated :). -
Correct way to get/create nested objects with DRF?
I have the following models: class Platform(models.Model): # Get key = models.CharField(max_length=32, unique=True) class PlatformVersion(models.Model): # Get or create platform = models.ForeignKey(Platform, on_delete=models.CASCADE) major = models.IntegerField(db_index=True) minor = models.IntegerField(db_index=True) build = models.IntegerField(db_index=True) class DeviceManufacturer(models.Model): # Get or create name = models.CharField(max_length=64, unique=True) class DeviceModel(models.Model): # Get or create manufacturer = models.ForeignKey(DeviceManufacturer, on_delete=models.CASCADE) platform = models.ForeignKey(Platform, on_delete=models.CASCADE) # ... # And many others POST JSON looks like this: { "device_model": { "manufacturer": { "name": "samsung" }, "platform": { "key": "android" } }, "version": { "platform": { "key": "android" }, "major": 8, "minor": 1, "build": 0 } } I have the following serializers: class PlatformSerializer(serializers.ModelSerializer): class Meta: model = Platform fields = ('name', 'key',) extra_kwargs = { 'name': { 'read_only': True, }, } def create(self, validated_data): return Platform.objects.get(key=validated_data['key']) class PlatformVersionSerializer(serializers.ModelSerializer): platform = PlatformSerializer() class Meta: model = PlatformVersion fields = ('platform', 'major', 'minor', 'build',) def create(self, validated_data): # ? pass class DeviceManufacturerSerializer(serializers.ModelSerializer): class Meta: model = DeviceManufacturer fields = ('name',) def create(self, validated_data): manufacturer, _ = DeviceManufacturer.objects.get_or_create( defaults={ 'name': validated_data['name'], }, name=validated_data['name'] ) return manufacturer class DeviceModelSerializer(serializers.ModelSerializer): manufacturer = DeviceManufacturerSerializer() platform = PlatformSerializer() class Meta: model = DeviceModel fields = ('manufacturer', 'platform') def create(self, validated_data): # ? pass I've marked in serializers … -
DJANGO 4.0.0 127.0.0.1/:81 GET http://127.0.0.1:8000/localhost:8000/media/movies/Vikings__Valhalla_Trailer_rsTJT2H.mp4 404 (Not Found)
I have a problem loading the video I get the following bug: 127.0.0.1/:81 GET http://127.0.0.1:8000/localhost:8000/media/movies/Vikings__Valhalla_Trailer_rsTJT2H.mp4 404 (Not Found) this is my showMovie.html: {% block content %} {% include 'partials/navbar.html' %} <main class='bg-primary_black h-full w-full '> {{ movie|json_script:"movie_data" }} <video src="" controls class="w-full h-screen player"></video> </main> <script type="text/javascript"> const videoEl=document.querySelector('video') const movie_data = JSON.parse(document.getElementById('movie_data').textContent); const url =new URL(location.href) const video_param = parseInt(url.searchParams.get("epi")) ? parseInt(url.searchParams.get("epi")) : 0 videoEl.setAttribute('src',`http:/localhost:8000/media/${movie_data[video_param].file}`) </script> {% endblock content %} And this is the view: class ShowMovie(View): def get(self,request,movie_id,*args, **kwargs): try: movie=Movie.objects.get(uuid=movie_id) movie=movie.videos.values() context = {'movie':list(movie)} return render(request,'showMovie.html',context) except Movie.DoesNotExist: return redirect('core:profile_list') it is a .mp4 file so store it in the static folder I don't know how to fix it. I've searched everywhere but can't find a workable solution. Everything else works great. Regards!! models.pyerror video movieDetail.html -
Is it possible to create a Django model from csv input with non-standardized column names/number of columns
I'm working on a project where the end user will provide a semi-standardized csv input to my program. By semi-standardized, I mean that most columns will always be present, but each csv has the potential to have an extra column or two that is unique to that csv alone. Because of this I don't think it's possible to pre-define an all encompassing Django model (I may be wrong, and would love to be shown otherwise), so my question is: is it possible to update/change the Django model's structure from views.py (or in some other way), based on the csv input file, to capture these non-standard columns and store the uploaded CSV to my db? If not, is there another way to go about solving this problem? -
Remove library root on venv
I created a project in django ear the venv folder The words library root appear why is it happening? How do I remove / cancel it? I want it to look like this without library root just venv Screenshot attached I tried to use this guide (link attached) the link Attached is a screenshot from my project On the screen marked in green, I removed line 1 I thought it would solve the problem but it did not help Could it be that it also created another problem? -
Django : How do you check if an user has the rights or not to Url
I am a newbee in django. In my website, when the user logs in, he is redirected to a page with a dropdown menu where he has to choose a contract on which he wants to work. After selecting the contract he is redirected to the specific homepage define with a pk value in the url.The pk value comes from the ID of the contract in the database. How can I check by a function or a decorator that the user has the rights to this ID. Because any user could right the numbers in the url and access to the page. Here is my view of the dropdown menu : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) Here the views of the home page : @authenticated_user def home(request, id_contrat=None): context = initialize_context(request) return render(request, 'home.html', context) The urls : from django.urls import path from . import views urlpatterns = [ path('home/<int:id_contrat>/', views.home, name="home"), path('', views.loginAD, name="login"), path('signin', views.sign_in, name='signin'), path('callback', views.callback, name='callback'), path('selectcontrat', views.selectcontrat, name='selectcontrat') The model is the relation between a user and a group. which group the user … -
Django complex annotation comparing childrens
I have a DJANGO Profiles model and a Answer model with a foreignkey to Profile Imagine that every Profile will have multiple Answers like lists of integers What I want is to order my queryset by the most similar answers to mine. So I found this method (rmse) to compare arrays: np.sqrt(((list_a - list_b) ** 2).mean()) If the arrays are equals this returns 0 and so on.. How can I create a Annotation to Profiles queryset that compare my answers to others using this method above? -
Django redis cache cannot access redis cache set outside of django
I'm setting up redis as a docker service and connect to it through django-cache and python redis library. First: from django.http import HttpResponse from django.core.cache import cache def test_dj_redis(request): cache.set('dj_key', 'key_in_dj', 1000) return HttpResponse("Redis testing\n" "- in dj view: {}\n" "- in other: {}".format(cache.get('dj_key'), cache.get('py_key'))) Second: import redis r = redis.Redis( host='redis', port=6379 ) def cache_it(): r.set('py_key', 'key in py', 1000) print(r.get('py_key')) print(r.get(':1:dj_key')) print(r.keys()) If I run both of them first one by refresh the web page related to that django view second one by python cache_it(). In first, I cannot access 'py_key', it will return None. But second, I can see the cache set in django view. Django cache added a prefix to it and turn 'dj_key' into ':1:key_in_dj', but I can access it nonetheless. Also in second, the redis_r.keys() return [b'py_key', b':1:key_in_dj']. The value of the key 'py_key' remained the same, so how come I can't access it through django cache.get('py_key') -
auth.authenticate(username=username, password=password) returns none on DJANGO
I have a simple login url test needed to login: def test_logInUsingLoginAPI(self): self.user = UserFactory() data = dict(username=self.user.username, password=self.user.password) print("Client is sending") print("username: " + self.user.username) print("password: " + self.user.password) response = self.client.post('https://localhost:8000/api/users/login/', data, headers={'Content-Type': 'application/json'}, follow=True) print("Server responded with:") print(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) The factory looks like: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ["username"] username = factory.Faker("user_name") email = factory.Faker("email") is_superuser = False @factory.post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else fake.password( length=42, special_chars=True, digits=True, upper_case=True, lower_case=True ) ) self.set_password(password) The backend view looks like this: @method_decorator(ensure_csrf_cookie, name='dispatch') class UserLoginView(APIView): permission_classes = [AllowAny] def post(self, request, format=None): data = self.request.data if not ("username" in data and "password" in data): return Response({"error": "Missing fields: username and password are all required fields"}, status=status.HTTP_400_BAD_REQUEST) username = data['username'] password = data['password'] user = auth.authenticate(username=username, password=password) print('Backend received. Trying to authenticate with') print('username: ' + username) print('password: ' + password) passwordFromUserName = User.objects.get(password=password).username print('extracted username from password: ' + passwordFromUserName) print('-------------------------------------') print("After authenticating with those username and password") if(user is None): print("user is not found") else: print("user is found") I keep on getting this on my console when I run pytest: I am not sure … -
Django project on Cloud Foundry not loading admin interface CSS
I have a simple Django project deployed with Cloud Foundry. The admin interface (the only interface used by my simple project) looks fine when running locally. When deployed, however, the CSS is visibly broken. The URLs for the CSS and JS assets return 404. Other answers to similar questions say that the solution is the collectstatic command. To run this in the context of Cloud Foundry, I type the following (obviously with the real app name and path): cf run-task app-name -c "python app-path/manage.py collectstatic" The output logged from this looks very promising: 128 static files copied to '/home/...path.../settings/static'. Yet, in spite of this apparent promise, the CSS is still broken. FYI, my settings include this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') -
how to add slug to html template url tag in Django?
I want to have a URL path like this: www.example.com/html/html-introduction. Now there are two slugs here html and html-introduction. when i maually type in the slug in the url input, it works, but when i pass into a button in my html template it does not work and it shows this error Reverse for 'programming-languages-category' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['getting\\-started/(?P<prglangcat_slug>[-a-zA-Z0-9_]+)/$'] this is my template where i have the button i want to pass the slug into <div> {% for p in prglangcat %} <a href="{% url 'base:programming-languages-category' slug=p.prglangcat_slug.slug=p.prg_slug.slug %}" > <h4>{{p.title}}</h4> </a> {% endfor %} </div> views.py def index(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/index.html', context) def gettingStarted(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/getting-started.html', context) def programmingLanguageCategoryDetail(request, prglangcat_slug): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) context = { 'prglangcat': prglangcat } return render(request, 'base/language-category.html', context) def programmingLanguageTutorial(request, prglangcat_slug, prg_slug ): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat) context = { 'prglangtut': prglangtut, 'prglangcat': prglangcat } return render(request, 'base/tutorial-page.html', context) urls.py app_name = 'base' urlpatterns = [ path('', views.index, name="index"), path('getting-started/', views.gettingStarted, name="getting-started"), path('getting-started/<slug:prglangcat_slug>/', views.programmingLanguageCategoryDetail, name="programming-languages-category"), path('getting-started/<slug:prglangcat_slug>/<slug:prg_slug>/', views.programmingLanguageTutorial, name="tutorial-page"), ] models.py class ProgrammingLanguagesCategory(models.Model): title = models.CharField(max_length=100) icon …