Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conflict between python-slugify and awesome-slugify
I am using the awesome-slugify python library (1.6.5) but for another Django app I need also to use the csvkit python library (version 1.0.3). Once I install the csvkit (pip install csvkit), I start getting an error when importing the Slugify. I figured out, that this is cause csvkit also required the python-slugify (2.0.1) in order to work. There is a conflict between awesome-slugify and python-slugify. In the past I have used all 3 together without any issue. The versions I have used were the following: python-slugify: 1.2.4 csvkit: 1.0.0 awesome-slugify: 1.6.2 I thought I could solve the issue by doing: pip install csvkit==1.0.0 <-- this still installs the latest python-slugify pip install python-slugify==1.2.4 pip install awesome-slugify==1.6.2 But unfortunately it doesn't seem to work. Cause somehow the two slugify libraries share the same folders. The problem is that python-slugify is installed as a dependency of the csvkit. So its not straightforward to me, how I could define the folder name of the insllation inside the site-packages.. What a mess.. -
How to enforce logger format during Celery task execution?
I have some service which uses Python logging module to log debug logs. my_service.py: import logging logger = logging.getLogger(__name__) class SomeService: def synchronize(self): logger.debug('synchronizing stuff') external_library.call('do it') logger.debug('found x results') Then, I use this service from celery task tasks.py: @shared_task def synchronize_stuff(): stuff = some_service.synchronize() Worker then outputs log like this: worker_1 | [2019-01-22 11:39:19,232: DEBUG/MainProcess] Task accepted: my_task_name[48d706d7-0d92-43aa-aa9d-d5db8d660af8] pid:12 worker_1 | [2019-01-22 11:39:19,237: DEBUG/ForkPoolWorker-1] Starting new HTTPS connection (1): example.com:443 worker_1 | [2019-01-22 11:39:19,839: DEBUG/ForkPoolWorker-1] https://example.com:443 "GET /api/stuff HTTP/1.1" 200 None worker_1 | [2019-01-22 11:39:19,860: DEBUG/ForkPoolWorker-1] Processing 35 worker_1 | [2019-01-22 11:39:19,862: DEBUG/ForkPoolWorker-1] Item 35 already closed, ignoring. worker_1 | [2019-01-22 11:39:19,863: DEBUG/ForkPoolWorker-1] Processing 36 worker_1 | [2019-01-22 11:39:19,865: DEBUG/ForkPoolWorker-1] Item 36 already closed, ignoring. worker_1 | [2019-01-22 11:39:19,865: DEBUG/ForkPoolWorker-1] Processing 49 worker_1 | [2019-01-22 11:39:20,380: DEBUG/ForkPoolWorker-1] https://example.com:443 "GET /api/detail/49 HTTP/1.1" 200 None worker_1 | [2019-01-22 11:39:20,429: DEBUG/ForkPoolWorker-1] Processing 50 worker_1 | [2019-01-22 11:39:20,680: DEBUG/ForkPoolWorker-1] https://example.com:443 "GET /api/detail/50 HTTP/1.1" 200 None worker_1 | [2019-01-22 11:39:20,693: DEBUG/ForkPoolWorker-1] Processing 51 worker_1 | [2019-01-22 11:39:21,138: DEBUG/ForkPoolWorker-1] https://example.com:443 "GET /api/detail/51 HTTP/1.1" 200 None worker_1 | [2019-01-22 11:39:21,197: INFO/ForkPoolWorker-1] Task my_task_name[48d706d7-0d92-43aa-aa9d-d5db8d660af8] succeeded in 1.9656380449960125s: None Which is good enough for debugging, but I'd like to include the task name and uuid in these logs. … -
Adding a Geo Django project to AWS Lambda using Zappa. Getting OSError: cannot open shared object file: No such file or directory
I am trying to deploy my Geo-Django app to Zappa 1st I got django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Then I followed this link and added the below I set these environment variables in my AWS Lambda console: "LD_LIBRARY_PATH": "/tmp/code/lib/", "PROJ_LIB": "/tmp/code/lib/proj4/", and in my (Django) app's settings file, I set: GDAL_LIBRARY_PATH = "/tmp/code/lib/libgdal.so.20.1.3" GEOS_LIBRARY_PATH = "/tmp/code/lib/libgeos_c.so.1" Now I am getting the error OSError: /tmp/code/lib/libgdal.so.20.1.3: cannot open shared object file: No such file or directory Just a bit of FYI. When I deploy on EC2 on my Ubuntu instance I used in my server_setup.sh file. I have terminated that instance apt-get install -y python3-dev python3-venv python-pip supervisor nginx git python-gdal postgresql postgresql-contrib postgis python3-distutils Below is my pip freeze argcomplete==1.9.3 boto3==1.9.82 botocore==1.12.82 certifi==2018.10.15 cfn-flip==1.1.0.post1 chardet==3.0.4 Click==7.0 defusedxml==0.5.0 Django==1.11.15 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap3==11.0.0 django-braces==1.13.0 django-cleanup==2.1.0 django-debug-toolbar==1.10.1 docutils==0.14 durationpy==0.5 future==0.16.0 hjson==3.0.1 idna==2.7 jmespath==0.9.3 kappa==0.6.0 lambda-packages==0.20.0 oauthlib==2.1.0 Pillow==5.3.0 placebo==0.8.2 psycopg2==2.7.5 psycopg2-binary==2.7.5 PyJWT==1.6.4 python-dateutil==2.6.1 python-slugify==1.2.4 python3-openid==3.1.0 pytz==2018.5 PyYAML==3.13 requests==2.20.0 requests-oauthlib==1.0.0 s3transfer==0.1.13 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 sqlparse==0.2.4 stripe==2.10.1 toml==0.10.0 tqdm==4.19.1 troposphere==2.4.1 Unidecode==1.0.23 urllib3==1.24 uWSGI==2.0.15 Werkzeug==0.14.1 wsgi-request-logger==0.4.6 zappa==0.47.1 How can I fix this -
Queryset in one to many relation
I'm trying to get a json of elements with their related elements I had two tables, Service and Room. One service have many rooms. I'd like to get the service where have room_id = x. Models class Service(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = True db_table = 'Service' class Room(models.Model): name = models.CharField(max_length=255, blank=True, null=True) service = models.ForeignKey(Service, models.DO_NOTHING, blank=True, null=True) class Meta: managed = True db_table = 'Room' Serializer class ServiceSerializer(serializers.ModelSerializer): room_set = RoomSerializer(many=True, read_only=True) class Meta: model = Service fields = ('name','room_set') class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' View queryset = Service.objects.filter(room__id=1) serializer = ServiceSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) I expect a json like this: { "name": "Hotel1", "room_set": [ { "id": 1, "name": "Room1" }, But I get this: { "name": "Hotel1", "room_set": [ { "id": 1, "name": "Room1", }, { "id": 2, "name": "Room2", }, { "id": 3, "name": "Room3", } } Is it possible to get a json like the one I'm expecting? -
How to avoid end user actions based on stale data in DB
I have a database table at the backend, that provides various items for sale and their prices as well. For the sake of simplicity, let us assume that the schema for the same is like so:- class Product(models.Model): item_id = models.Integer() item_name = models.CharField(max_length=30) item_price = models.CharField(max_length=30) item_count = models.Integer() There is an API getProducts(), that is used to show to the enduser all the products available, including their price. There is another API buyProduct(product_id), exposed to the enduser, using which he may purchase the item after seeing its price. There is a third API, updatePrice(product_id, new_price) available to the administration backend using which the price may be modified. Now w/o having a database transaction that spans across >1 HTTP requests, how can I ensure that the API buyProduct() succeeds only if the price is the same as what the enduser saw (basically whatever getProducts() had returned last to the browser). It is possible that a customer sees the price of a product as 1$, and clicks BUY, but simultaneously the price at the backend was changed to 2$. I have two solutions:- Fix the buyProduct() API to include a price, which indicates whichever price that was shown to the … -
Django separate settings files in Docker
Following multiple articles around the web, I've split my Django 1.11 settings.py file into multiple files, base.py, local.py, staging.py, production.py, in a settings folder. The Django app runs in a Docker container. docker-compose.yml: django: build: context: . env_file: .env command: ["/wait-for-it.sh", "mariadb:3306", "--", "/gunicorn.sh"] In the Dockerfile I export the DJANGO_SETTINGS_MODULE as the local settings file (which in turn imports the base.py settings file). Dockerfile: FROM python:3.6.4 RUN mkdir /app ADD requirements/*.txt app/requirements/ RUN pip install -r mira/requirements/dev.txt ADD . /app RUN export DJANGO_SETTINGS_MODULE=app.settings.local RUN export DJANGO_SECRET_KEY=dummy-secret-key COPY ./docker/web/entrypoint.sh ./docker/web/gunicorn.sh ./docker/web/wait-for-it.sh ./docker/web/logging.conf ./scripts/setup.sh / RUN chmod +x /entrypoint.sh /gunicorn.sh /wait-for-it.sh /setup.sh WORKDIR ./app settings/base.py: SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] .env: DJANGO_SECRET_KEY=FOOBAR When I try to up the container, I get this error: The SECRET_KEY setting must not be empty. -
How to filter objects by filtering related objects
I'm using python 3.7, and django 2.1. I'm trying to filter parent object by the "latest" kid object properties I'm able to do so using 2 queries (see - Django Query That Get Most Recent Objects From Different Categories) Class Bakery(models.Model): town = models.CharField() Class Cake(models.Model): bakery = models.ForeignKey(Bakery, related_name="cakes") baked_at = models.DateTimeField() is_chocolate = models.BooleanField() What I would like to do is something like: bakeries_whose_latest_cake_was_chocolate = Bakery.objects \ .annotate(latest_cake=F('cakes__baked_at=Max(cakes__baked_at')) \ .filter(is_chocolate=True) -
"Django not found" using venv in Eclipse/PyDev
I'm having trouble setting up Eclipse IDE for JavaScript and Web Developers (version 2018-12 4.10.0) with PyDev to use Django from a virtual environment. I'm using Ubuntu 18.04. TL;DR: when I create a new Django project in PyDev, Eclipse doesn't find Django, although it is installed in the venv. Details: My workspace structure is as follows: └── workspace └── djangogirls ├── mysite ├── djvenv ├── manage.py ├── db.sqlite3 └── requirements.txt I set up the virtual env with python3 -m venv djvenv I installed Django~=2.1.5 from requirements.txt using pip install -r requirements.txt I activate the venv in shell and test Django is installed (returns '2.1.5') source djvenv/bin/activate django-admin --version In Eclipse, I create a new workspace in directory workspace; installed PyDev and activated its perspective in Window>Perspective>Open perspective>Other>PyDev. I set the Python interpreter to match the one from the virtual environment in directory djvenv Window>Preferences>PyDev>Interpreters>Python Interpreter> When I attempt to create a Django project with File>New>Project>PyDev>PyDev Django Project, this leads to a "Django not found." message: I'm not sure what I'm doing wrong, as Django seems perfectly well installed in the venv (as it can be accessed from the shell), and it is listed in the packages of the selected python … -
Django: how do you deal with queries that can not scale?
In my code, I have a few queries that are not scalable at all. For example, take a look at this code: class OrderQuerySet(query.QuerySet): def for_day(self, day: date): """ Return all orders that concerns the given service day """ day_order_pks = [order.pk for order in self.all() if localdate(order.service.start) == day] return self.filter(pk__in=day_order_pks) At the beginning, it perfectly worked. The problem is, when order amount increase, the performance seems to decreases in a linear way, which makes senses because all orders need to be tested each time. Having 1000 new orders every day, it's obvious my system will not be usable anymore in a few time! Usually, how do you deal with this kind of problem in Django? I mean, sometimes I can find a trick to write a better query, using Django ORM only. But sometimes, to get what I want, I seems to be forced to create my queryset this way, using Python and a for loop. -
Django: How to get select2 to start working, basic hello world
I would like to use select2 in Django to create a multi-select combobox (pillbox), such as: However, my result looks like: Efforts: I have downloaded, as well as tried to link directly to CDN <link rel="stylesheet" type="text/css" href="{% static 'product/lib/select2/css/select2.min.css' %}"> <script src="{% static 'product/lib/select2/js/select2.min.js' %}"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> I have also, step by step, trying to identify the problem, as well as analysing and comparing in the browser using the inspector. I do not use Bootstrap (save for importing some functionality from the js) and cannot see it is related to the conflict mentioned in some forums and on the help page for select2. Using the basic example on https://select2.org/getting-started/basic-usage, produces the same result. Its like it cannot "activate", despite using the script and checking linkage. What could be the problem? I'm using Django 2.1.5, Python 3.6, and latest select2 (both css and JS, header and near bottom of body) -
Can't open a page's advanced settings in browser
So I have a Django CMS installation, and I did some configurations and I can't figure out the problem. AttributeError at /admin/cms/page/5/advanced-settings/ attribute app_title not found Error during template rendering In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/includes/fieldset.html error at line 19 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} Sorry I can't copy paste or take screenshot. -
How to Order by ForeignKey of parent Model in Django
Hello I have 2 models: Model User class User(models.Model): name = models.CharField(max_length=20, null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True, related_name='checkin', on_delete=models.SET_NULL) Model Location class Location(models.Model): name = models.CharField(max_length=100) How can I order Location by number of checkin of User Model? I tried this but not success: Location.objects.annotate(checkin_count=Count('user')).order_by('-checkin_count') -
Create mupltiple models at a time DRF
I know there are similar questions like this but I've gone through them all and didn't find the right answer. I have a Question model and POST method in my APIView looks like this: def post(self, request): """Create a new question""" description = request.data['description'] question_type = request.data['type'] answers_to_close = request.data['to_close'] question = Question.objects.create( description=description, question_type=question_type, answers_to_close=answers_to_close ) return Response({ 'status': 'SUCCESS', 'question_id': question.id, 'message': 'New question has been created successfully!', 'question': f"'{description}'" }) It works fine but I also want to add a possibility to create multiple questions within one request. I tried something like this (another instance of APIView: def post(self, request, **kwargs): """Create a session of questions""" session = kwargs['session'] description = request.data['description'] question_type = request.data['type'] answers_to_close = request.data['to_close'] Question.objects.create( description=description, question_type=question_type, answers_to_close=answers_to_close, session=session ) return Response({ 'status': 'SUCCESS', 'session': session, 'message': 'A new session has been created!' }) So when I try this curl request: curl -X POST http://127.0.0.1:8000/api/sessions/create/21383/ --data ['description=Am I Strong&type=YESNO&to_close=3', 'description=Best js framework&type=TEXT&to_close=10'] It says 'django.utils.datastructures.MultiValueDictKeyError: 'description' ' What's wrong with me APIView? -
Nginx serves static files for admin page but not for my project
I try to handle that for few days already, and I cannot make it after reading many tutorials docs and questions here. The problem is that my django project, with gunicorn and nginx in docker container does not have static files for my website (404), but it has static files for admin page (which is very strange for me). Here are my configs: DJANGO DOCKERFILE FROM python:3 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=memes.settings_prod RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r env_properties/prod/base.txt RUN pip install -r env_properties/prod/prod.txt RUN python manage.py collectstatic --noinput RUN python manage.py migrate --noinput NGINX DOCKERFILE FROM nginx RUN adduser --system --no-create-home --shell /bin/false --group --disabled-login nginx RUN apt-get update RUN apt-get install nano -y COPY env_properties/nginx/nginx.conf /etc/nginx/nginx.conf RUN mkdir /code RUN mkdir /code/static WORKDIR /code COPY ./static /code/ NGINX CONFIG location /static { autoindex on; alias /code/static; } DOCKER-COMPOSE version: '3' services: web: container_name: django_web build: context: . dockerfile: ./env_properties/prod/Dockerfile command: gunicorn -w 4 memes.wsgi:application -b 0.0.0.0:8000 environment: - DJANGO_SETTINGS_MODULE=memes.settings_prod volumes: - .:/code ports: - '8000:8000' nginx: container_name: nginx_server_2 command: nginx -g 'daemon off;' build: context: . dockerfile: env_properties/nginx/Dockerfile depends_on: - web ports: - "0.0.0.0:80:80" tty: true I go to my pages and … -
django customization of save method for change the default db
I want to customize the save method to change my db and also I have connected my django project to a mysql db . I have tried to create a user in the shell which is from my models.py : >>> from adabazi_test.models import Users >>> user = Users(user_name = 'mamad' , password= 'bikbik') >>> user.save() and here is my models.py: from django.db import models class Users(models.Model): user_name = models.CharField(blank=False , max_length = 40) password = models.CharField(blank = False , max_length = 40) in mysql db i have adabazi_test scheme and Users scheme and save method automatically put new instances of my models.Users in adabazi_test and i whould put them in Users scheme. How can i customize save method for making this change? -
Get played time from html5 player and send to Django function
I'm trying to get played time from html5 video player. I successfully get start and end time of first played time range. I would like to send time range to function in Django 2.0 every time when user will start and stop video. Any idea how to fix that? <!DOCTYPE html> <html> <body> <video id="videoPlayer" width="320" height="176" controls> <source src="https://r1---sn-8xjug5oxu-f5fe.googlevideo.com/videoplayback?mime=video%2Fmp4&key=yt6&fvip=6&sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cexpire&ip=109.197.67.187&ipbits=0&expire=1548168440&lmt=1472784021038997&pl=23&signature=DDDF5812EBA03434A7A729EC800B56146CC05041.C7FA04CAD5D8A50FF75AA9E1F73C0C372DAC83&dur=10393.901&ei=mNhGXIOJFo2V7QT6oKrYAw&source=youtube&itag=22&ratebypass=yes&mt=1548146723&mv=m&ms=au%2Crdu&mm=31%2C29&mn=sn-8xjug5oxu-f5fe%2Csn-f5f7ln7y&id=o-AF-Y-B2o5xYN4x7hMQGhb9cRO7GCMR6bS0U818w8BuKV&requiressl=yes&initcwndbps=1621250&c=WEB" type="video/mp4"> </video> <script> setInterval(function() { var vid = document.getElementById("videoPlayer"); var start_pl = vid.played.start(0); var end_pl = vid.played.end(0); document.getElementById("start_pl").innerHTML = start_pl; document.getElementById("end_pl").innerHTML = end_pl; }, 400); </script> start: <div id="start_pl"></div> end: <div id="end_pl"></div> </body> </html> Thank You for any help! https://jsfiddle.net/7vfpazsw/ -
Unable to get django declared app routes working as pages
I am creating an Django app and am facing issues with routes not being identified. It is the same DJango poll app I am trying to create but the documentation code does not work. Here is my code below: djangoproject/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^simpleapp/', include('simpleapp.urls')), url(r'^admin/', admin.site.urls), ] simpleapp/views.py from django.shortcuts import render from django.http import HttpResponse, request def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) simpleapp/urls.py from django.conf.urls import url from . import views urlpatterns = [ # ex: /simpleapp/ # url('', views.index, name='index'), # ex: /simpleapp/5/ url('<int:question_id>/', views.detail, name='detail'), # ex: /simpleapp/5/results/ url('<int:question_id>/results/', views.results, name='results'), # ex: /simpleapp/5/vote/ url('<int:question_id>/vote/', views.vote, name='vote'), ] If I un-comment the first url of '' path of simpleapp/urls.py code, all the pages shown are '' path. However, if I keep the url '' path commented, then the routes give me the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/simpleapp/34/ … -
AttributeError - 'RawQuerySet' object has no attribute 'exclude'
I am using raw query because i wanted `select unique rows based on single distinct column - Django context['reports'] = TimesheetEntry.objects.raw('SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id WHERE timesheet_is_running=False') context['reports'] = context['reports'].exclude(pk=36) It is giving me error - AttributeError - 'RawQuerySet' object has no attribute 'exclude' How can i exclude? Or How to Convert above RawQuerySet to QuerySet -
Is it possible to find the username of a client pc using python ?(Not server's username)
Is it possible to find the username of a client pc using python ?(Not server's username) print(socket.gethostname()) it will return the server's username. I want client PC's user name. Thanks in advance. -
django authentication new user created unnecessarily - auth0
So I'm trying to integrate auth0 with my existing django app and sqlite database. Login is working, the problem is I can't get the usernames inputted by auth0 through request to map on to the ones already present in my db. This is the auth0 backend and right now I've hardcoded to return eq3 and 21 respectively for username and user_id. def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') # CLIENT_ID payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': 'eq3', 'user_id': 21} However when I go to views.py and put a print(request.user.username) and print(request.user.id) it prints eq306fa23456g204e8c and 51. When I go into my database, I see that it has indeed created a new user in the auth_user table, even though there's already a user with eq3 and user id 21 in the same table. Furthermore, if I input a random username such as foobar, it will still create a new user, but it won't add the nonsensical alphanumeric string to the username, just foobar. What is going on here? How can I get … -
How to serve wordpress themes when a user creates a page
What is the best way to serve wordpress templates to user accounts with django? Kind of like how shopify lets users pick the template of their website and then make their account that template. I've created the templates but can't seem to figure out how to update each users account specifically with the templates. I just need help with the concept not the code. -
Django: handler403 doesn't work, but 404 does
Here is content of MyProj/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('general.urls')), # Main app ] handler403 = 'general.views.handler403' handler404 = 'general.views.handler403' As you can see, both handlers point to the same view, and first one, which I need most, doesn't work! For example, data of other's user at /obj/12 shows default browser 403 page: [22/Jan/2019 08:39:14] "GET /obj/12 HTTP/1.1" 403 0 But the second one works well and shows correct page (when try to access some not existing data at /obj/768). Why and how can I solve it? The debug mode is off. My Django version is 2.0.6 -
Exclude All and keep one Django Query
This is my Query where i am getting all users who are manager and employee. User.objects.exclude( Q(userprofile__user_is_deleted = True)| Q(userprofile__user_company__company_is_deleted=True) ).filter( Q(userprofile__user_company =company_name) ) Now i want to query such that when logged in user is manager, then exclude all manager except him (the logged in user which is manager) if request.user.userprofile.user_role.id == 3: # 3 for manager context['users'] = context['users'].exclude() I am not getting how to query. How can i do it. -
Container's content is ignoring the navbar and main banner in mobile view
Good Day Everyone! So I recently finished my first website, however I'm busy polishing it since there is some compatibility issues with some screen sizes. There is one thing I haven't been able to figure out or fix and that is the fact that in my teams page if you look at it in a mobile view (either through a mobile or chrome dev tools) you will notice that my container is ignoring my banner and navbar. This results in a huge space at the bottom of the page. The only solution I've thinked of is perhaps creating margin-top for the container but that would result in a lot of media queries. Is there perhaps a reason why it is ignoring it or a better solution? Thank You! The website: SeveregamingZA The HTML: <html lang="en"> <head> <!-- Title of Page --> <title> Teams - Severe Gaming </title> <!-- Bootstrap CDN and requirements --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"> <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Custom CSS --> <link rel="shorcut icon" type="image/png" href="/static/images/favicon.png" /> <link rel="stylesheet" type="text/css" href="/static/css/style.css"> <link rel="stylesheet" href="/static/css/teams.css"/> <script src="/static/scripts/teams.js"></script> … -
How to extend a user model without use profile method?
I want to add a column to django auth_user table. But I do not want to create a new table. As the document peovided for extending User model, there are four ways. proxy model Add a oneToOne field Creating a Custom User Model Extending AbstractUser Creating a Custom User Model Extending AbstractBaseUser It works some time. But How could I add a field to the auth user model it provied?