Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Heroku: ProgrammingError at / relation "theblog_category” does not exist
I already read those other Django Heroku questions and I'm still having an error. I'm appreciating your help. My website is running on localhost:8000. It's working perfectly and no complaints there. My heroku website is running, but my database isn't there on my heroku server. On Heroku: https://data.heroku.com/datastores/... Health: Available 0 of 10,000 Rows In Compliance 8.1 MB Data Size 0 Table(s) I suspect that it's a Django migrations problem, but I can't fix it. I tried the following code: 'heroku run python manage.py migrate' Same error as before. I tried add, commit and push for the heroku server. git add 'theblog/migrations/* git commit -am 'Heroku' git push heroku It was successful, however 'heroku run python manage.py migrate' was not sucessful. Same message as before. Possible, delete the heroku server and I'll try again. On my Heroku website: relation "theblog_category" does not exist Traceback Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs … -
Why Django Rest Framework - Serializer validation doesn't work
I have a simple serializer in my serializers.py and I want to validate one of the fields using validate(self, data) but it doesn't work. My Models.py: class UserRole(models.Model): role = models.CharField(max_length = 100, blank=True, null=True) permission_read = models.BooleanField(null=True) permission_edit = models.BooleanField(null=True) permission_write = models.BooleanField(null=True) permission_delete = models.BooleanField(null=True) superuser = models.BooleanField(null=True) def __str__(self): return self.role My serializers.py: class CreateRoleSerializers(serializers.ModelSerializer): class Meta: model = UserRole exclude = ['superuser'] My views.py: @api_view(['POST']) @permission_classes([IsAuthenticated]) @write_required def user_role_api(request): if request.method == 'POST': json = JSONRenderer().render(request.data) stream = io.BytesIO(json) data = JSONParser().parse(stream) serializer = CreateRoleSerializers(data=data) if serializer.is_valid(): serializer.save(superuser=0) return Response(status=rest_framework.status.HTTP_200_OK) return Response(serializer.errors, status=rest_framework.status.HTTP_400_BAD_REQUEST) I don't know what's wrong with this code. Thanks in advance for the help! -
Django, why media images' urls don't work in production?
I am working on a blog that needs to set in production, the problem comes when I set it production. All the static files load perefectly but the images I upload. I have tried with images previously uploaded before setting it in production, also after. Screenshot of webpage settings.py DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'core.apps.CoreConfig', 'unities.apps.UnitiesConfig', 'ckeditor', 'ckeditor_uploader', 'django_cleanup.apps.CleanupConfig' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ... STATIC_URL = '/static/' STATIC_ROOT= os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) STATICFILES_STORAGE='whitenoise.storage.CompressedManifestStaticFilesStorage' # Media files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # CKEditor Settings CKEDITOR_ALLOW_NONIMAGE_FILES = False CKEDITOR_UPLOAD_PATH = 'ckeditor_uploads/' urls.py urlpatterns = [ path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), path('', include('core.urls')), path('<slug:unity_slug>/', include('unities.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT I'm using pythonanywhere -
Problem with Django startproject: TypeError: '_sre.SRE_Match' object is not subscriptable
Trying to run django-admin startproject mysite and there occurs such problem Traceback (most recent call last): File "/Users/username/Desktop/test/venv/bin/django-admin", line 10, in <module> sys.exit(execute_from_command_line()) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/commands/startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/core/management/templates.py", line 158, in handle template = Engine().from_string(content) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/engine.py", line 136, in from_string return Template(template_code, engine=self) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/base.py", line 155, in __init__ self.nodelist = self.compile_nodelist() File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/base.py", line 193, in compile_nodelist return parser.parse() File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/base.py", line 447, in parse filter_expression = self.compile_filter(token.contents) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/base.py", line 563, in compile_filter return FilterExpression(token, self) File "/Users/username/Desktop/test/venv/lib/python3.6/site-packages/django/template/base.py", line 638, in __init__ var, constant = match['var'], match['constant'] TypeError: '_sre.SRE_Match' object is not subscriptable I guess there is a problem with versions, but don't know exactly what is it. On version 1.8.6 everything is ok, but when I try to use from django.urls import path, include I see that there is no django.urls in this version. So I'd like to use the latest version and will be grateful, if you can help me! Python version: Python 3.6.0a4 -
How to deploy Django page to heroku
how to implement a django project on heroku server -
Multiple possible data types in a single Django model field?
TLDR One of my models contains data that could either be a charfield, textfield, or boolfield based on a choice made in a separate model that it is connected to through a foreignkey. What's the most efficient way to model this in Django? My problem I'm putting together a Django app that outputs a python {'key': 'value'} dictionary in a somewhat lengthy two-step process. In the first step, users design a custom 'Template' that contains a collection of 'TemplateEntries'. In pseudo-code: Template MODEL foreign key: User description = textfield name = charfield TemplateEntry MODEL foreign key: Template key = charfield value_type = charfield(choices='CharField', 'TextField', 'BoolField') description = textfield order = positivesmallintegerfield (So users can re-arrange the order of TemplateEntries when creating the Template) EXAMPLE TEMPLATE FORM #1 [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, Bool Field] [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, Bool Field] [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, Bool Field] [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, Bool Field] [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, Bool Field] In the second … -
'list' object has no attribute 'get' printing problem
I cannot use the get method in form operations and I get an error as it appears in the header. Forms.py class LoginForms(forms.Form): username = forms.CharField(max_length=50,label="Kullanıcı Adınız") password = forms.CharField(label = "Şifreniz", widget = forms.PasswordInput) Views.py def loginUser(request): form = LoginForms(request.POST or None) context = { "form":form } if form.is_valid(): username = form.changed_data.get("username") password = form.changed_data.get("password") user = authenticate(username = username, password = password) if user is None: messages.info(request,"Kullanıcı Adı Yada Şifre Hatalı") return render(request,"login.html",context) messages.success(request,"Başarıyla Giriş Yaptınız!") login(request,user) return redirect(request,"index") return render(request, "login.html", context) Error; AttributeError at /user/login/ 'list' object has no attribute 'get' Request Method: POST Request URL: http://127.0.0.1:8000/user/login/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'get' Exception Location: C:\Users\pc\Desktop\blog\user\views.py, line 46, in loginUser Python Executable: C:\Anaconda3\python.exe Python Version: 3.8.3 Python Path: ['C:\Users\pc\Desktop\blog', 'C:\Anaconda3\python38.zip', 'C:\Anaconda3\DLLs', 'C:\Anaconda3\lib', 'C:\Anaconda3', 'C:\Anaconda3\lib\site-packages', 'C:\Anaconda3\lib\site-packages\win32', 'C:\Anaconda3\lib\site-packages\win32\lib', 'C:\Anaconda3\lib\site-packages\Pythonwin'] Server time: Fri, 27 Nov 2020 02:46:07 +0300 -
Django Template Image not displaying even with media url and media root
Static images are showing properly. The files in the media folder are not displaying in html. I tried setting up media_url in various ways but in vain. I uploaded the image via django admin panel. The name of product is showing fine. The img.url shows /media/p2.jpg models.py class Product(models.Model): name = CharField(("Name"),max_length=256,blank=False) title_img = models.ImageField(null=True, blank=True) settings.py PROJECT_ROOT = (os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "media_root") urls.py urlpatterns = [ path('', ProductList.as_view() , name="product"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template.html {{p.name}} <img src="{{p.title_img.url}}> the name is displayed while image is not displayed -
Conditional override leaflet attrs in form
I've been trying to set up a conditional to override the DEFAULT_CENTER value for the django leaflet app, I managed to set conditional form to delete fields according to selected type, but to alter the widget values it gives me a "'Propv_Cr_2' object has no attribute 'widgets'" forms.py class Propv_Cr_2(forms.ModelForm): rol_fk = forms.ModelChoiceField( queryset=BaseRoles.objects.all(), widget=autocomplete.ModelSelect2(url='roles-autocomplete') ) #geom = PointField() class Meta(): model = PropVenta fields = ['titulo', 'direccion', 'dir_numero', 'sector','anio_const', 'amoblado', 'estado','valor_vta', 'valor_vta_uf', 'dormit','banios', 'living', 'terraza','estacionam', 'home_office', 'descr','const_regu', 'piscina', 'area_verde','pisos','rol_fk', 'const_regu', 'ac_piscina', 'ac_quincho','ac_salon', 'orient', 'gastos_com_est', 'piso','oficinas', 'sala_reu', 'urbanizado', 'geom','publicado'] widgets = {'acerca': Textarea(attrs={'cols': 80, 'rows': 5}),'rol_fk': autocomplete.ModelSelect2(),} help_texts = { 'geom':'Boton "Draw a Marker" para ingresar ubicación geográfica' } def __init__(self, *args, **kwargs): super(Propv_Cr_2, self).__init__(*args, **kwargs) if self.instance.tipo_prop == 'casa': fields_to_delete = ('ac_piscina', 'ac_quincho', 'urbanizado') elif self.instance.tipo_prop == 'depto': fields_to_delete = ('const_regu', 'piscina') elif self.instance.tipo_prop == 'oficina': fields_to_delete = ('home_office', 'ac_piscina', 'living') elif self.instance.tipo_prop == 'terreno': fields_to_delete = ('ac_piscina', 'ac_quincho','estacionam', 'home_office', 'orient') elif self.instance.tipo_prop == 'Bodega': fields_to_delete = ('ac_piscina', 'urbanizado') elif self.instance.tipo_prop == 'loft': fields_to_delete = ('const_regu', 'piscina', 'sala_reu', 'urbanizado') elif self.instance.tipo_prop == 'local_comercial': fields_to_delete = ('ac_piscina', 'ac_quincho', 'home_office', 'orient') for field in fields_to_delete: del self.fields[field] if self.instance.ciudad == 'a1': leaf_set = LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS) elif self.instance.ciudad == 'a2': leaf_set = LeafletWidget(attrs={'settings_overrides': … -
Get element from for loop in Django template for JavaScript
I am doing a to-do app on Django with a progress circle. I need to get the percentage from for loop in Django Template by using getElementById, however, it only takes the first element in the for loop. This is my code: <div class="todo-list"> {% for goal in goals %} <div class="item-row"> {% if goal.complete == True %} <strike>{{ goal }}, {{ goal.due | timeuntil }}</strike> {% else %} <span>{{ goal }}</span> <span style="float: right;" class="timer"><b>Due: </b>{{ goal.due | timeuntil }}</span> <div class="box"> <div class="percent"> <svg> <circle cx="100" cy="100" r="100" class="track"></circle> <circle cx="100" cy="100" r="100" class="progress"></circle> </svg> <div class="number"> {% load templatetag %} <h2 id="due">{{ goal|convert_to_seconds }}<span>%</span></h2> </div> </div> </div> {% endif %} <a class="btn btn-sm btn-light" href="{% url 'update_goal' goal.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'delete_goal' goal.id %}">Delete</a> </div> {% endfor %} </div> And the script part: var percentage = parseInt(document.getElementById("due").innerText); let progressCircle = document.querySelector(".progress"); progressCircle.style.strokeDashoffset = 620 - (620 * percentage) / 100; I tried to use forloop.counter but it did not work. Could you help me please? Thank you in advance. -
Custom Django Management Command not being executed by Celery Task
I have created this custom management command in a Django application, to delete all but one record in a database table: from django.core.management.base import BaseCommand from tokenizer.models import OauthToken class Command(BaseCommand): help = 'Deletes all but the most recent oauthtoken' def handle(self, *args, **options): latest_token_id = OauthToken.objects.latest("gen_time").id OauthToken.objects.exclude(id=latest_token_id).delete() and it works as expected when run manually, like so: python manage.py oauth_table_clearout However, when I try and get a Celery Task to execute it, whilst the task appears to be picked up and succeeds, the records are not deleted from the db, and there are no obvious errors given. I am running docker-compose like so: version: '3.7' services: redis: image: redis:alpine django: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" env_file: - ./.env depends_on: - redis celery: build: . command: celery -A token_generator worker -l debug --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo volumes: - .:/usr/src/app/ depends_on: - redis env_file: - ./.env celery-beat: build: . command: celery -A token_generator beat -l debug volumes: - .:/usr/src/app/ depends_on: - redis env_file: - ./.env note that I have tried appending '--without-gossip --without-mingle --without-heartbeat -Ofair' to the worker command, (which seems to be what has solved this particular problem for everyone else!) … -
Django Quill Editor Display Saved Field
It's probably really simple, but can't figure out how to do that... I have one really simple model: from django.db import models from django_quill.fields import QuillField class Race(models.Model): name = models.CharField(max_length=50, unique=True) description = QuillField() In admin.py from races.models import Race @admin.register(Race) class RaceAdmin(admin.ModelAdmin): pass So, thru the admin panel, I can use Quill to write text with HTML and add image. Great ! It is saved in the database in Quill delta format. Now, if I want to display that description field in a template, as html... How Am I suppose to do? Thank you very much ! -
Providing equal rank when Players score the same
This is my first time posting a question here. If I am missing anything, please let me know! I am trying to create a table, which provides individuals' ranks to Players. One thing I am struggling is, if Players score the same, they should have the same Ranks. The current code shows the rank of Players who score the same differently... (e.g., as in Rank 1 and 2). I tried several ways that I found on this website but I couldn't manage it to show properly... Does anyone have any idea? I call in data using the code below: rpi = self.get_rpi() rpi.sort(key=lambda x: x['rpis'], reverse=True) goals = self.get_goal() ranks = [] index = 1 for rpis in rpi: ranks.append({'id': rpis['id'], 'rpis': rpis['rpis'], 'rank': index}) index = index + 1 ranks.sort(key=lambda x: x['id'], reverse=False) index = 0; newRanks = [] for goal in goals: newRanks.append({'id': ranks[index]['id'], 'rank': ranks[index]['rank'], 'goal': goal['goals']}) index = index + 1 return newRanks Then, I create a table using the code below: <table class="table mb-2"> <thead> <tr> <th scope="col">Participant No.</th> <th scope="col" class="text-center">Goal</th> <th scope="col" class="text-center">Performance Rank</th> </tr> </thead> <tbody> {% for item in player.get_ranks %} <tr> <td> {% if player.id_in_group == item.id %} Participant {{item.id}} … -
Would Django or Flask be better for a larger app? Or something else?
Me and a friend are looking to build a travel planning web app and we are in a bit of dispute whether to use flask or django, any advice or help? -
Django Rest Framework: Modify Serializer to return dictionary using a field as the key instead of an array of objects
Currently I have an API View that returns a dictionary that looks like this: [ { "id": 1, "name": "Fly in the sky", "thumbnail": "games/fly_in_the_sky", "maps": [ { "id": 1, "name": "Blue Sea", "thumbnail": "maps/blue_sea.jpg" }, { "id": 2, "name": "Red Mountain", "thumbnail": "maps/red_mountain.jpg" } ], "characters": [ { "id": 1, "name": "Steve", "thumbnail": "characters/steve.jpg" }, { "id": 2, "name": "Peter", "thumbnail": "characters/peter.jpg" } ] } ] I would like it to look like this instead, moving the names of all items as keys. (I would make sure ahead of time that all the names are unique so there is no key conflict) { "Fly in the sky": { "id": 1, "thumbnail": "games/fly_in_the_sky", "maps": { "Blue Sea": { "id": 1, "thumbnail": null }, "Red Mountain": { "id": 2, "thumbnail": "maps/red_mountain.jpg" } }, "characters": { "Steve": { "id": 1, "thumbnail": "characters/steve.jpg" }, "Peter",{ "id": 2, "thumbnail": "characters/peter.jpg" } } } } Is there any way of telling Django to return elements as a dictionary using a field as keys instead of an array? My views and serializer currently look like this: class GamesView(APIView): def get(self, request): game_objects = Game.objects.all() game_serializer = GameListSerializer(game_objects, many=True) return Response(game_serializer.data) class MapListSerializer(ModelSerializer): class Meta: model = … -
There is a way to get a value from views.py into nodels.py?(Django)
I'm making a little django project of money management, i'm using a table layout, wich inside the tables there are many transactions, i have two sql tables: "Table" and "Transactions"and i need that when i open the link of one specific table, i need to get just the items wich were created in the table page. Example: i open 'table1' and inside it i create 'value1', 'value2','value4' after, i open 'table2' and inside it i create 'value3' and 'value5' after that, when i open the 'table1' page i need to show 'value1','value2' and 'value4' and when i open 'table2', i need 'value3' and 'value5' i wonder if there is a way to take the id of the table i'm inside in the moment and write it into the transactions form to make some kind of 'id', so i can filter the values by it id Here are my files: urls.py from django.urls import path import tables1.views as vw urlpatterns = [ path('admin/', admin.site.urls, name = 'admin'), path('mytables/', vw.mytables, name = 'mytables'), path('',vw.home), path('table/<int:pk>',vw.table, name = 'tableurl'), path('newtable/',vw.newtable,name = 'newtable') ] views.py from .models import Table from .forms import TableForm def home(request): now = {} return render(request,'tables1/home.html',now) def mytables(request): data = … -
Django SaaS multiple users for one client
I hope you are all safe and not too crazy yet :) Here is my use case: Company A signs up and creates an account and can add 5 additional users / employees to be able to login and see all that companies info and no other. Now Company B signs up and can add 15 additional user / employees as they have a higher tier plan and same thing they can't see the other company. Since this is not highly sensitive data, I'll just use a low level isolation ie. "SELECT * FROM 'table' WHERE tenant_uuid = 1" This is the first time looking at the whole multi-tenant thing, and I sorta get that but I am struggling to see how I can have multiple users tied to the one account. The only thing I can think of is an abstract user that has a FK to the company. The company would be created with the owner user attached to the company, a custom model manager will accomplish this and then the owner can go in and add his employees. Is this my solution or has anyone seen or used something different? any help in the matter would be … -
How do you configure a Google Domain with Digital Ocean?
For context, I'm working through the Obey the Testing Goat book for Test-Driven Development with Python/Django and am on chapter 9. I purchased a domain from Google, specified the three customer name servers for Digital Ocean on Google Domains, created a Digital Ocean droplet, set up DNS A-records that point to my subdomains on my site, and uploaded my repository server-side. However, when I try to curl the website address development server via Git Bash from my local machine, I get the error: curl: (6) Could not resolve host: <my-domain-here> This same error does not happen when I curl server-side. I've confirmed through DNS checkers that the server propagated. Nothing I've tried gets me passed this step of curling. I realize the issue could be multiple things, but I just started learning web-frameworks and don't have a frame of reference on how to debug. Thanks in advance! -
Getting the error ModuleNotFoundError at / No module named 'sekizai'
I'm having this error in browsers in production after attempting to install the module django-sezikai. python version 3.7.9 ; django version 2.1.15 ; OS: CentOS I removed the module from settings.py -
How to add group choices in the Object Permissions form of the admin interface with django-guardian?
Using guardian in a django project, I want the admins to be able to assign object permissions over the admin interface. With guardian this is possible, but the Object permissions form in the admin interface, the Group field is a TextField. How do I make it a ChoiceField with all existing groups as choices? Is there a solution that only requires adding code in the admin.py file of the app or do we have to overwrite some guardian code? How can we do it without messing with the functionality of guardian? This is my admin.py file: from django.contrib import admin from .models import MyModel from guardian.admin import GuardedModelAdmin class MyModelAdmin(GuardedModelAdmin): pass admin.site.register(MyModel, MyModelAdmin) -
How to get to pylint part of settings.json in Visual Studio Code?
I wanted to set up Python linting and Django compatibility in Visual Studio Code (VSC). So I installed the Python and Djaneiro extensions. And pylint and pylint-django pip packages in my Django venv. I then went to look for the settings for the linting extensions via File->Preferences->Settings. But I couldn't see how to reach the section on pylint for the json settings file, it seems to have moved/changed recently in VSC. I just wanted to add: "python.linting.pylintEnabled": true, "python.linting.pylintArgs": [ "--load-plugins", "pylint_django" ] I'm guessing you can edit the file some other way rather than jumping to the section via the VSC interface. VSC version is 1.51.1, on Windows 10. -
ERROR: Django connect to PostgreSQL via Docker
My code is from settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } Dockerfile # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ docker-compose.yml version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 when docker-compose logs on cmd, I see an error db_1 | Error: Database is uninitialized and superuser password is not specified. db_1 | You must specify POSTGRES_PASSWORD to a non-empty value for the db_1 | superuser. For example, "-e POSTGRES_PASSWORD=password" on "docker run". db_1 | db_1 | You may also use "POSTGRES_HOST_AUTH_METHOD=trust" to allow all db_1 | connections without a password. This is *not* recommended. db_1 | db_1 | See PostgreSQL documentation about "trust": db_1 | https://www.postgresql.org/docs/current/auth-trust.html If I use basic settings.py with sqlite3 It works and connecting to the server So I am a new one on Docker, How to solve it? Thanks for you answer -
Bootstrap Navbar does not want to show dot separator between elements
I am making site with Django 3.1.2 and Bootstrap 4.5.3. I have some issues with navbar. I want to have these links on the right separated by middle dots. This piece of css does not run correctly - only padding works, dot is not visible: .navbar-nav .nav-item:not(:last-child) { content: "\00B7"; padding-right: 35px; } This is how this section looks like in the html: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item nav-link"> <a href="{% url 'blog:about' %}" class="menu">O Szkole</a> </li> <li class="nav-item nav-link"> <a href="{% url 'blog:teachers' %}" class="menu">Kadra</a> </li> <li class="nav-item nav-link"> <a href="#" class="menu">Kalendarz</a> </li> <li class="nav-item nav-link"> <a href="{% url 'blog:projects' %}" class="menu">Projekty</a> </li> <li class="nav-item nav-link"> <a href="{% url 'blog:contact' %}" class="menu">Kontakt</a> </li> </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item nav-link"> <a href="#" class="menu">Informacje dla uczniów</a> </li> <li class="nav-item nav-link"> <a href="#" class="menu">Informacje dla rodziców</a> </li> <li class="nav-item nav-link"> <a href="#" class="menu">Dokumenty</a> </li> {% if user.is_authenticated %} <a href="#">Nowy Post</a> <a href="#">Wyloguj się</a> <a>Witaj: user.username</a> {% endif %} </ul> </div> Any ideas what I am doing wrong? -
checkbox always send false value in Django form
I have a modelform and i want to save the checkbox value in my model but somehow it just saves unchecked even if i have selected the checkbox and here is my code: forms.py : class UserLocation_updated(forms.ModelForm): class Meta: model = get_user_model() fields = ['lat','lng','user_address','is_private'] checkbox field in models.py : is_private = models.BooleanField(default=True) and views.py : if request.method=="POST": print(request.POST) updatelocation_form = UserLocation_updated(request.POST or None, request.FILES or None,instance=request.user) if updatelocation_form.is_valid(): updatelocation_form.save() return redirect('userlocation_update') enter code here -
Hidden field in the template
I'm trying to update (using Django's UpdateView) a field of my Model. The problem is that this field doesn't appear on the template but it is there with: input type = 'hidden' setted. How is it possible? I've already used UpdateView for other models, and I haven't had any problems so far.