Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up SASS to work with Django and AWS S3
I'm trying to set up my Django project to use SASS, unsuccessfully so far. I've installed libsass, django-compressor, and django-sass-processor. My settings.py includes these lines: INSTALLED_APPS = [ 'sass_processor', .... [my other apps here] ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(PROJECT_ROOT, 'static/css') AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'myproj-debug' if IS_DEBUG else 'myproj' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'myproj.storage_backends.MediaStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) My base.html includes these lines: {% load sass_tags %} <link href="{% sass_src 'app.scss' %}" rel="stylesheet" type="text/css"> When I run my debug Django server with ./manage.py run server, the processor seems to find my app.scss file okay, because when I move it to a different location I get an error. But where is the compiled app.css file being placed? I see in my page source that the {% sass_src line becomes <link href="https://myproj-debug.s3.amazonaws.com/static/app.css" rel="stylesheet" type="text/css"> but no file shows up there. (I'd actually like to have it placed at https://myproj-debug.s3.amazonaws.com/static/css/app.css but that's another matter.) How do I get app.css to compile and show up in my AWS S3 bucket like it should? -
Django queryset order by latest value in related field
Consider the following Models in Django: class Item(models.Model): name = models.CharField(max_length = 100) class Item_Price(models.Model): created_on = models.DateTimeField(default = timezone.now) item = models.ForeignKey('Item', related_name = 'prices') price = models.DecimalField(decimal_places = 2, max_digits = 15) The price of an item can vary throughout time so I want to keep a price history. My goal is to have a single query using the Django ORM to get a list of Items with their latest prices and sort the results by this price in ascending order. What would be the best way to achieve this? -
ERROR 404 after submitting a form with POST request
http://127.0.0.1:8000/tasks works fine but when when I add a task and submit it, I get a 404 thrown at me, ERROR: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ polls/ newyear/ tasks/ [name='index'] tasks/ add [name='add'] The current path, tasks/{ % url 'add' % }, didn't match any of these mysite\tasks\urls.py from django.urls import path,include from . import views urlpatterns = [ path("", views.index, name='index'), path("add", views.add, name='add')] mysite\mysite\urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')), path('newyear/', include('newyear.urls')), path('tasks/', include('tasks.urls'))] mysite\tasks\views.py from django.shortcuts import render tasks = ["foo", "bar", "baz"] def index(request): return render(request, "tasks/index.html", { "tasks": tasks }) def add(request): return render(request, "tasks/add.html") ) mysite\tasks\templates\tasks\index.html {% extends "tasks/layout.html" %} {% block body %} <h1> Tasks </h1> <ul> {%for task in tasks%} <li> {{task}}</li> {%endfor%} </ul> <a href="{% url 'add' %}">Add a New Task</a> {% endblock %} mysite\tasks\templates\tasks\add.html {% extends "tasks/layout.html" %} {% block body %} <h1> Add Task </h1> <form action= "{ % url 'add' % }" method="post"> <input type="text" name="task"> <input type="submit"> </form> <a href= "{% url 'index' %}">View Tasks</a> {% endblock %} -
How to register several models in one admin page?
I need an admin page which will contain several model lists. Each model has own register and settings so I need to use this admin classes to group them in one page. To be clear, example: models.py class Student(models.Model): name = models.CharField(max_length=60) age = models.PositiveSmallIntegerField() class Teacher(models.Model): name = models.CharField(max_length=60) subject = models.CharField(max_length=60) admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): # settings @admin.register(models.Teacher) class TeacherAdmin(admin.ModelAdmin): # settings # need them together like this: class TwoModelsAdmin(admin.ModelAdminGroup) admin_panels = (StudentAdmin, TeacherAdmin,) Is there any way to do that? -
Nested models in django
I have an django app with a model called Folder, user can create a Folder with a name field. what i want is to make this Folder model nested, so that user will be able to create Folders inside a folder. For example user created a folder called ABC and got inside the DetailView of that folder and created another folder DEF and then got into DEF and created another folder called GHI and so on. I am pretty new to django, i tied searching the web but got nothing. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.core.validators import MinValueValidator from django.core.exceptions import PermissionDenied # The Folders Model. class Folder(models.Model): name = models.CharField(max_length = 250) cr_date = models.DateTimeField(auto_now_add = True) def __str__(self): return "%s" % self.name views.py import requests from django.shortcuts import render from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from ahmed_drive.models import Folder from . import models from django.views.generic.detail import DetailView from django.db.models import Q from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.http.response import HttpResponseRedirect #### Normal Pages Related Views #### class HomeView(TemplateView): template_name = "ahmed_drive/home.html" #### Pages Related Folder Model #### @method_decorator(login_required, … -
Django static files 404 using nginx
I'm aware this has been asked a few others times, but none of those solutions seem to be working for me. This was my first time deploying a Django project, so for reference, I followed this tutorial: https://linuxhint.com/create_django_app_ubuntu/ For that reason, it is entirely possible that something flew over my head completely. nginx config (I've tried alias instead of root, with and without trailing slash, made sure the static file aren't owned by root, etc.): upstream django { server 127.0.0.1:8000; } server { listen 80; location /static/ { root /home/bryan/Projects/portfolio; try_files $uri =404; } location / { try_files $uri @send_to_django; } location @send_to_django { proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } } settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Note: django.contrib.staticfiles is installed python manage.py collectstatic appears to be working I do believe I am referencing the static files correctly in my templates: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/css/index.css' %}"> My file structure: portfolio (django project root) home (django app) static (project static files) home (static files for home app) css Other than the static files, the site works flawlessly with this setup. -
Comments input form (HTML, DJANGO)
Help me how to display the form for entering comments under the article, so that the form is under the article on the barbers.html page. When I write the form in barbers.html it is not displayed. I think everything else is correct, but just in case I also publish urls.py urlpatterns = [ path('',views.HomePage.as_view(),name='index'), path('barbers/',views.BarbersPage.as_view(), name='barbers'), path('post_detail/<int:post_id>/', views.post_new, name='post_detail'), ] views.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('name', 'body') models.py class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30, null=True, blank=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) post_detail.html <h1>New comment</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> barbers.html {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3> {{ post.name_barber}} </h3> <p>{{ post.description}}</p> <h3> … -
How can I do a dynamic url that doesn't raise a 404 error if I click twice on the navbar the same button?
I am currently working on my first web design and I'm experiencing some trouble with my url. What I'm trying to do is a navbar that when you click on the button, redirects you to a page. However, if I click twice on the navbar button, it raises a problem because the program is still reading the other url. Here's some photos so you can understand. [When I click on the translator button, the url adds translator. Now If I click another time in the translator button, it raises a 404 error. Now If I click on the home button, I still have the translator/ in the url, so it raises another 404 error. My question is, how can I do a dynamic url so that when I click on another button, it doesn't appear a 404 error and redirects me to that page. Here's the code of the navbar <nav class="navbar fixed-top navbar-expand-lg navbar-light" style='background-color: snow;'> <div class = 'container'> <a class="navbar-brand" href="#"> <img src="{% static ''%}" width="70" height="30" class="d-inline-block align-top" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mx-auto"> <li class="nav-item active"> <a class="nav-link" href='home'>Home <span … -
How do I get pagination to work with django_filters to work in Django 3?
In my html, I can either do {% for i in filter.qs %}, which has my sorted model or {% for i in page_obj %}, which has my paginated model. Is there a way to paginate the sorted model? -
Django signals for Comment notification
I am working on django project and I have written a post_save signal to notify post author when commented. Now, I want to add a post_save signal to notify post author/ comment user that a comment (reply) is made. Below are my model and signal code. Can someone assist please? I am new on django and have just started learning django signals. class Comment(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) post = models.ForeignKey('forum.Post',related_name='comments', on_delete=models.CASCADE) reply = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) text = models.TextField(max_length=250, blank=True) @receiver(post_save, sender=Comment) def user_comment_post(sender, instance, created, **kwargs): if created: comment = instance post = comment.post #reply = comment.reply text_preview = comment.text[:90] sender = comment.user notify = Notification.objects.create(post=post, sender=sender, comment=comment, user=post.author, text_preview=text_preview, notification_type=2) notify.save() -
api jsonresponse containing multiple fields from multiple tables
I need to create an api which will contain data from below two models. class User(models.Model): u_id = models.CharField(max_length=9,default=None,unique=True) real_name = models.CharField(max_length=200) tz = models.CharField(max_length=200) def __str__(self): return self.u_id class Activity(models.Model): u_id = models.CharField(max_length=9,default=None) start_time = models.DateTimeField() end_time = models.DateTimeField() def __float__(self): return self.start_time User class contains user detail and it's user id is unique. Activity class can contain multiple start and end time for same user id. We need an api which will contain multiple start and end time entries for the same user. I tried querying both models into one querylist and passing that as jsonresponse but it doesnt work. views.py def user_activity(): base_url_user = 'http://127.0.0.1:8000/users/' base_url_activity = 'http://127.0.0.1:8000/activity/' res_user = requests.get(base_url_user).json() res_activity = requests.get(base_url_activity).json() u = {} a = {} for i in range(len(res_user)): u[i + 1] = res_user[i] for i in range(len(res_activity)): a[i + 1] = res_activity[i] for u[i]["u_id"] in a[i]: querylist = [ {'queryset': User.objects.all()}, {'queryset': Activity.objects.all()} ] return JsonResponse(querylist) serializers.py from rest_framework import serializers from .models import * class Userserializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class Activityserializer(serializers.ModelSerializer): class Meta: model = Activity fields = '__all__' urls.py from django.urls import include, path from rest_framework import routers from . import views router = … -
Django Form Update Failing with a NULL not allowed
I have a customer instance that I am trying to update only a FEW fields in using a form, as the rest is 'behind the scenes' info. I am receiving this error: Cannot insert the value NULL into column 'iddef_cst', table 'EasyTrade20.dbo.app_customer_cst'; column does not allow nulls. UPDATE fails Even though that record was already populated and already has that value included. views.py: def edit_customer(request, id): customer_obj = get_object_or_404(AppCustomerCst, id_cst=id) form = CustomerMaintForm(request.POST, instance=customer_obj) if form.is_valid: form.save() forms.py class CustomerForm(forms.ModelForm): class Meta: model = AppCustomerCst fields = ('id_cst', 'is_active_cst', 'name_cst', 'address_1_cst', 'address_2_cst', 'address_3_cst', 'city_cst', 'state_cst', 'zip_cst', 'country_cst', 'salesrep_cst', 'type_cst', 'is_allowed_flat_cst', 'balance_notify_cst', 'receive_emails_cst', 'contact_domain_cst' I have tried to create an instance of the form with form.save(commit=False) and use the fields from customer_obj to pass the current values to the form for update, but it seems the final form.save() creates a new object. Is there any clean way to use a ModelForm to update only a handful of fields in a model instance? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e2d62f0>
This is my first question. I'll try to get it right. After having no problems running Django on my dev environment (on macOS 10.14.6) for over a year, I tried to start the server today and got this message: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e2d62f0> With this traceback: Traceback (most recent call last): File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 25, in <module> import MySQLdb as Database File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Users/mtd83/_Dev/env/lib/python3.4/site-packages/_mysql.so, 2): Library not loaded: /usr/local/opt/mysql-connector-c/lib/libmysqlclient.18.dylib Referenced from: /Users/mtd83/_Dev/env/lib/python3.4/site-packages/_mysql.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/mtd83/_Dev/env/lib/python3.4/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Users/mtd83/_Dev/env/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, … -
How to fix CSRF error on logging in using REST API in Django Rest Framework?
I am beginner to Django, following this tutorial to implement register, login and logout using DRF. The register is working fine, but I am not able to login using postman, it is showing CSRF error. Already tried using @csrf_exempt decorator, but then it is showing AttributeError on LoginAPI.asView() AttributeError: 'function' object has no attribute 'as_view' <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please … -
How i can convert list value in String in Django?
I have some values store in my database in this format ["Same Drive","Test Drive","Safe Drive"], and same values are displaying on my HTML page, I want to display these values in this format Same, Test, Safe Drive, Please let me know how I can display these values in this formant. here is my HTML file code.. <p>{{datas.types}}</p> and this is displaying data in this format ["Same Drive","Test Drive","Safe Drive"] -
Django template variable not set
The title says everything. Two days ago the following code worked fine but now journeys is not set or empty or ... def map(request, jid): journeys = None if request.user.is_authenticated: journeys = Journey.objects.filter(user_id=request.user.id) #some stuff context = { 'jc': len(journeys), #only for testing 'journeys': journeys } return render(request, 'JourneyMap/map.html', context) map.html extends base.html Inside base.html: <div class="dropdown-menu" aria-labelledby="dropdown05"> <p>{{ jc }}</p> <-- only for testing {% for journey in journeys %} {% if journey.user_id == user.user_id %} {% if forloop.counter < 4 %} <a class="dropdown-item" href="{% url 'JourneyMap_journey' jid=journey.id %}">{{ journey.title }}</a> {% endif %} {% endif %} {% endfor %} </div> Result: -
Django: what is the best way to prevent multiple click on a button?
I have a Django form with a popup confrimation before form validation. When validated, I save form data in a table, update 2 other tables, send an email and user is redirected to another confirmation page. It works but it may be slow in some situation. And in these situation, I have experienced the case a user click another time. Doing that, form data are sent again but form validation failed (normal behavior to prevent duplicate) but user is never redirected to the confirmation page and that is problematic. To fix this issue, I would like : to prevent user to be able to click 2 times the popup button (disable after first click) improve data process in my view improve my logic For the first point, I must use JS, right? For the second point, as 2 table are update, I think using update would be better For the third, ? thanks for advice def randomisation_edit(request): if request.method == "POST": form = RandomisationForm(request, data=request.POST or None) if form.is_valid(): randomisation = form.save() pays = randomisation.ran_num[0:3].upper() centre = randomisation.ran_num[4:6].upper() status = randomisation.ran_vih severity = randomisation.ran_sta rand = Randomiser(pays, centre, status, severity) # Mise à jour de la base de données -> … -
How to run an async function without blocking the execution in Django channels
I have an AsyncWebsocketConsumer running django channels for an online turn-based game. There is need to verify that the player associated to the current turn is online, and if they aren't, the turn should be updated and passed onto the next player. At the end of the function that sends the new state to connected players, you have these two lines: await self.send_new_state_to_all_players(event_specifics) await self.check_current_player_online(game_id) # routine to handle the case where current player isn't online The method check_current_player_online() does this: async def check_current_player_online(self, game_id): current_turn_player_number = await self.get_current_turn(game_id) if await self.is_online(await self.get_player_id_from_number(game_id, current_turn_player_number)): # if current player is online, resume normal game flow return await asyncio.sleep(5) if not await self.is_online(await self.get_player_id_from_number(game_id, current_turn_player_number)): # if player hasn't come back, increment turn await self.increment_turn(game_id) await self.send_new_state_to_all_players({ 'type': 'pass_turn', }) Expected behavior: when the turn of a player who isn't online comes, every player should receive the new state sent by send_new_state_to_all_players, and be informed it's xyz's turn (the offline player), then after 5 seconds, if xyz hasn't come back online, the socket should send a new state message after updating the turn. This intended behavior takes place for everyone but the last player who sent a message to the socket, which … -
TemplateDoesNotExist at / while deployment
I developed a webapp using Django framwork, it's running fine in my localhost server but when I try to deploy it on any server like Heroku or PythonAnywhere I am getting this error I am not getting how to resolve it I tried changing paths and directories then also I am getting the same error can anyone please help me to resolve this error. Here is the error its showing me on the server:- Environment: Request Method: GET Request URL: http://alfeed21.pythonanywhere.com/ Django Version: 3.1.1 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /home/Alfeed21/Webapp3.0/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/contrib/admin/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/contrib/auth/templates/index.html (Source does not exist) Traceback (most recent call last): File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Alfeed21/Webapp3.0/credit/views.py", line 6, in home re turn render(request, 'index.html ') File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/Alfeed21/.virtualenvs/task3/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) … -
psycopg2.OperationalError: FATAL: password authentication failed for user "test"
I get the above FATAL error when running the containers dictated in the below files. It's a Django project being deployed to docker containers. The issue is I'm trying to get Postgresql to work in the docker setting but for some reason I can't get the login to work! Appreciate the help docker-compose.yml version: '3' services: web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" container_name: mu_chat_clone volumes: - .:/mu_chat_clone ports: - "8000:8000" env_file: - ./.env depends_on: - db redis: image: redis:latest expose: - "6379" db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=password - POSTGRES_DB=mu_chat_clone volumes: postgres_data: .env SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=mu_chat_clone SQL_USER=test SQL_PASSWORD=password SQL_HOST=db SQL_PORT=5432 settings.py DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } -
Django CharField unique argument in new Django version
In my forms.py file I am using CharField. I read about unique argument of CharField in the book: it says if the unique argument = True, then that model's CharField cannot repeat. In the book Django 2.1 version is presented. As for now, the argumen's name has been changed. I think so because Django shows an error sign TypeError: __init__() got an unexpected keyword argument 'unique' -
How can I create a form for making an appointment to a specialist?
Is it possible in Django to create a form for making an appointment to a specialist (doctor, hairdresser, auto repair shop), with the condition that if the first client signed up for a certain time, this time will not be available for the next one? If so, where can I read about it or see a sample? -
I'm looking for a library that will allow Django users to OAuth authenticate to an API and Django to access their data
I've done some Googling but I can't find the right Django library to use. Here's the scenario: My Django website has muiltiple users who register and log in using the built in Django user management features. I now want the website to access these users data from a third party site via that site's REST API. The third party site API requires the users authenticate via OAuth2. User registers on my website and logs in User follows link on my site, to give my site access their data stored on third party website, via REST API User is forwarded to the third party website where they agree to give my website access and are sent back as per OAuth pattern. My website should then be able to access the users data on the third party site, which it will access once per day, at night, to download the latest data. Access needs to be maintained indefinitely (token needs to refresh?), so that their data is accessible to my site, until the user chooses to disable the feature. -
Using same database tables for different projects in django postgresql
I am new to using Django framework. I want to use the same database(PostgreSQL) tables for 2 different projects. I was able to access the same database from two different projects. But how to access the tables? Firstly, I have models in project1 class employees(models.Model): employeeID = models.IntegerFiled() employeeName = models.CharField(max_length=100) This would create a project1_employees table in the database. I want to access this table in project2. If I have the same model in the project2 and migrate it creates a new table project2_employees in the same database. These are two entirely different projects. -
How to build an admin page from the record edit pages of several models?
For example I have three models: class Person(models.Model): nick = models.CharField(max_length=60, unique=True) name = models.CharField(max_length=60) age = models.PositiveIntegerField() class CurrentPersonPair(models.Model): person_1 = models.ForeignKey(Person, on_delete=models.CASCADE) person_2 = models.ForeignKey(Person, on_delete=models.CASCADE) class CurrentRegionPair(models.Model): region_1 = models.CharField(max_length=60) region_2 = models.CharField(max_length=60) CurrentPersonPair relations on Person and CurrentRegionPair just by it self. CurrentPersonPair and CurrentRegionPair have limit of one record. I need them to look like this: CurrentPersonPair and CurrentRegionPair gives their first records since they have only one and the Save button saves changes in both models (with all validations, errors etc). And Person works the same if it was a page just for this model. So is there a way to do that? I know about inlines but they work on record edit page but here I need to use something like that on the list page.