Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store product and pricing history in a Django product database?
I have a single product table DB containing various fields in a Django project, including the product mspr and current_price fields. For each product in the database, the current_price field is auto-updated periodically to detect changes. My problem is that I want to also store the historical price data of each product every time it is changed, but I am not sure how to restructure this current single table product DB below. class Product(models.Model): name = models.CharField(max_length=250) manufacturer = models.CharField(max_length=250) msrp = models.DecimalField(null=True, max_digits=10, decimal_places=2) current_price = models.DecimalField(null=True, max_digits=10, decimal_places=2) # and other product data fields I am certain that I have to create a second table so there will be two tables in the DB as shown below. But other than a DB class I took years back in college, I don't have much experience with creating databases, so please briefly explain how the primary/foreign key relationship for this use case only will work using the example below. It should be a one (product) to many (production historical price changes) correct?: class Product(models.Model): name = models.CharField(max_length=250) manufacturer = models.CharField(max_length=250) # and other product data fields class ProductPrice(models.Model): msrp = models.DecimalField(null=True, max_digits=10, decimal_places=2) current_price = models.DecimalField(null=True, max_digits=10, decimal_places=2) price_change_date = … -
Import channels for a WebSocket connection in Django not accessed
I am trying to add a WebSocket to my project. I have installed channels and read through the documentation online on how to properly configure everything. For some reason, any dependency I am trying to make that is related to channels library is not recognised in my project. I have uninstalled and installed the channels library many times, but with no luck. Me and my project partner have googled and asked around, but have found nothing useful yet. Does anyone know what could be the issue? This is what I get when I reinstall channels(So after it's uninstalled first with pip uninstall channels): Requirement already satisfied: Django>=3.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from channels) (4.1.3) Requirement already satisfied: asgiref<4,>=3.5.0 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from channels) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from Django>=3.2->channels) (0.4.3) Installing collected packages: channels Successfully installed channels-4.0.0 Versions: Django 4.1.3 Python: 3.11.0 I am also using corsheaders and rest framework libraries. -
How to change a ModelChoiceField's query set before sending the form to user in a view?
I have this form: class CategoryForm(forms.Form): category = forms.ModelChoiceField(queryset=Category.objects.filter(parent=None)) And a view: def category_select(request, pk): if request.method == "POST": # ... else: form = CategoryForm() # I want to change category field's queryset here. return render( request, "ads/select-category.html", { "form": form, }, ) In this view, I want to change queryset of category field in form (based on pk which it gets from the url as a parameter). -
Python django filter get all records modified within Last 10 Minutes
Using django I attempting to get All records that are modified based on modificationtime field in last 10 minutes class Status(models.Model): . . . modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, ) setttings.py consists of following entries TIME_ZONE = 'UTC' USE_TZ = True ten_minutes_ago = datetime.now() - timedelta(minutes=10) changedstatuslist = Status.objects.filter(Q(modificationtime__lte=ten_minutes_ago)) but changedstatuslist does not appears to be showing correct data. what modification/correction is needed above code so as to get all status objects records that are modified in last 10 minutes. -
Django send json formatted logs to logstash
I am trying to send logs to logstash with python-logstash package and i need logs to be in json format. I wrote custom json formatter for my logstash handler. My settings logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'main_formatter': { '()': CustomJsonFormatter, }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, "debug.log"), }, 'info_logger_file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, "development.log"), 'formatter': 'main_formatter', }, 'logstash': { 'level': 'INFO', 'class': 'logstash.UDPLogstashHandler', 'host': 'logstash.example.com', 'port': 8080, 'version': 1, 'message_type': 'logstash', 'fqdn': False, 'tags': ['app'], 'formatter': 'main_formatter', } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'info_logger': { 'handlers': ['info_logger_file', 'logstash'], 'level': 'INFO', 'propagate': True, }, }, } my CustomJsonFormatter: from pythonjsonlogger import jsonlogger class CustomJsonFormatter(jsonlogger.JsonFormatter): def add_fields(self, log_record, record, message_dict): super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict) if not log_record.get('timestamp'): # this doesn't use record.created, so it is slightly off now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') log_record['timestamp'] = now if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname log_record['application'] = 'production' But when i'm trying to log something, it throws exception: import logging log = logging.getLogger('info_logger') log.info("test") -
How to setup django-q in a IIS server for async views?
I have a Django app that runs i a IIS server and now i need to use django-q package on it, how can i setup IIS to do this since i can't run python manage.py qcluster? [Q] INFO Enqueued 8 Async view don't run without python manage.py qcluster. -
Pass additional data in DetailView Django
I have FBV where I am calculating time delta (td) and passing it in my context: def update_moc(request, pk): moc = get_object_or_404(Moc, pk=pk) today = datetime.date.today() time = moc.initiation_date time_delta = today - time td=str(time_delta) initiator = moc.initiator status = moc.moc_status coordinator = moc.coordinators.filter(coordinator_name=request.user) if request.user.is_superuser or (initiator == request.user or coordinator) and status == 'draft': form = MocUpdateForm(request.POST or None, instance=moc) today = datetime.date.today() time = moc.initiation_date time_delta = today - time td=str(time_delta) if form.is_valid(): moc.initiator = request.user form.save() return HttpResponseRedirect(reverse('moc_content_detail', kwargs={'pk': pk})) else: return render(request, 'moc/moc_content.html', context={'moc':moc, 'form':form, 'td': td}) else: raise Http404() However for DetailView I am having CBV and want to pass same time_delta (td) as additional context, but failing how I can do it... I tried few approaches to pass class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_context_data(self, *args, **kwargs): context = super(MocDetailView, self).get_context_data(*args, **kwargs) context['td'] = # This is where I need help def get_object(self, queryset=None): obj = super(MocDetailView, self).get_object(queryset=queryset) confidential = obj.confidential initiator = obj.initiator ..... if self.request.user.is_superuser or initiator == self.request.user or verifier or coordinator or reviewer or approver or preimplement or authorizer or postimplement or closer and confidential == True: return obj elif not confidential: return obj else: … -
location of source code of django.contrib.admin module
I want to figure out how the value for Django's admin.site.urls is generated. Where can I find the source code for django.contrib.admin module? $ find . -name "admin.py" ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/rest_framework/authtoken/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/sites/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/redirects/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/auth/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/flatpages/admin.py ./opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/contrib/contenttypes/admin.py -
Creating a hypertable with timescaleDB and django fails
I am running a django project and I am trying to integrate timescaleDB. Unfortunately this is not plug and play since django does not support timescaleDB officially. What needs to be done is some manual migrations. I tried two ways, but both ways are not working for me. Both are not working because my manually written SQL is not working: Adjusting migration manually (Problem: Unique restraint is not removed) I am following this tutorial (https://blog.ashtonhudson.com/adding-timescale-to-django.html) which is exactly my use case. I first create my models with timestamp as pk from django.db import models from django.db.models.fields import DateTimeField class Metric(models.Model): drinks = models.CharField(max_length=200) class TimeData(models.Model): # NOTE: We have removed the primary key (unique constraint) manually, since # we don't want an id column. timestamp = DateTimeField(primary_key=True) metric = models.ForeignKey(Parameter, on_delete=models.RESTRICT) value = models.FloatField(null=False) I then run the migrations and manually add two SQL statements to remove the unique constraint from the timestamp primary key: class Migration(migrations.Migration): operations = [ ... migrations.CreateModel( name="TimeData", fields=[ ("timestamp", models.DateTimeField(primary_key=True, serialize=False)), ("value", models.FloatField()), ( "metric", models.ForeignKey( on_delete=django.db.models.deletion.RESTRICT, to="myapp.drinks", ), ), ], ), migrations.RunSQL( "ALTER TABLE myapp_timedata DROP CONSTRAINT myapp_timedata_pkey;" ), migrations.RunSQL( "SELECT create_hypertable('myapp_timedata', 'timestamp', chunk_time_interval => INTERVAL '5 days');" ), ] This creates a … -
Selenium not working with Vite, possibly due to HMR
I am trying to use Selenium with a Django backend using Vite for JS stuff but for some reason the JS stuff isn't running when, for example, I tell Selenium to click a button. I think it has to do with Vite's HMR, because when I build the JS and link the bundled file in my Django templates it works fine. How can I get Selenium to work properly without having to use the bundled file? -
When should I use class based view and function based view in django?
Django views can be written in both class as well as function approach. In which situation we should use class based view and In which situation we should opt for function based views. -
How a loggedin user can view other user profile using django
I am working on a django project. When a user logs in, the user will be redirected to the profile page where he can view his username, email, profile picture, and list of blogpost created by him. This is the user profile page - blog/researcher-profile.html {% extends 'users/base.html' %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile_pic.url }}" width="125" height="125"> <div class="media-body"> <h2 class="account-heading" style="margin-left: 30px">{{ user.username }}</h2> <p class="text-secondary" style="margin-left: 30px">{{ user.email }}</p> <a href="{% url 'user-update' %}" class="btn btn-secondary btn-sm" style="margin-left: 30px;"> Edit Profile </a> </div> </div> <!-- FORM HERE --> </div> {% for post in posts %} {% if post.approved %} <div class="card mb-3"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title|truncatechars:70 }}</h5> <p class="card-text">{{ post.content|truncatechars:200|safe }}</p> <a href="{% url 'post-detail' post.aid %}" class="btn btn-primary"> See Details </a> </div> <div class="card-footer text-secondary"> <a class="mr-2" href="{% url 'researcher-profile' %}">{{ post.author }}</a>|| {{ post.created|date:"F d, Y" }} </div> </div> {% endif %} {% endfor %} {% endblock content %} urls.py from django.contrib import admin from django.urls import path from users import views as user_views from django.contrib.auth import views as auth_views from blog.views import UserPostListView from django.conf import settings from … -
Why is Django giving did you forget to register or load this tag error?
I have a working Django app that has started giving me a template block error on my Windows 11 development PC: Invalid block tag on line 17: 'endblock', expected 'endblock' or 'endblock stylesheets'. Did you forget to register or load this tag? I looked at this stackoverflow article: Invalid block tag : 'endblock'. Did you forget to register or load this tag?, but I don't have the typo that that article discusses. It is in a base.html template: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="{% static 'assets/img/orange-img.png' %}" type="image/x-icon"> <title> Clever - {% block title %}{% endblock %} </title> <!-- Specific Page CSS goes HERE --> <link rel="stylesheet" href="{% static 'assets/css/blue_theme.css' %}"> {% block stylesheets %} {% endblock stylesheets %} </head> <body class="hold-transition {% block body_class %}{% endblock body_class %}; w3-theme-l4"> {% block content %}{% endblock content %} <div style="text-align: center"> {% include 'includes/footer.html' %} </div> <!-- Specific Page JS goes HERE --> {% block javascripts %} {% endblock javascripts %} {% include 'session_security/all.html' %} </body> </html> The error gets generated on line 17: {% endblock stylesheets %}. I have tried putting the block and endblock on the same … -
Render PostgreSQL cannot translate hostname to address in Django
With Render, I would like to use their free PostgreSQL plan to host my database. I am using Django and I got confused what to use as a HOST. The dashboard on Render provides me with an external database url postgres://{given_username_by_render}:******-a.oregon-postgres.render.com/{database_name} if i use this link as a HOST in the databases settings as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'name', 'USER': 'username', 'HOST' : 'postgres://{given_username_by_render}:******-a.oregon-postgres.render.com/{database_name}', 'PASSWORD': env('PSGS'), } } I get this error while making migrations. I had used elephantsql before and they give me a simple host url like tiny.db.elephantsql.com which is plugged in HOST name and it worked but not in this case of using Render RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres://USER:PASSWORD@EXTERNAL_HOST:PORT/DATABASE" to address: Unknown server error My main question is, What do i use as the HOST name in database settings in django? Or am I doing this all wrong? If you do not have experience with Render then can you recommend me places where i can learn about things like these? -
Serving static files with NGINX and DJANGO
I'm new to programming and I've managed to build my father a website where he can showcase his photography, I recently had to switch from shared hosting to my own VPS that uses ubuntu to give me more control and access to latest pips. I've had everything working on local server regarding static files, everything uploads where it is meant to(for me it was static/media). In production I've got my website running perfectly other than any css working for my templates or even admin panel and images not showing. I have ran the following commands to get where I am, I will so share some code and screenshots of current configuration also. Image folders are also been created rather than images going into media folder. Images in browser have extensions image/image/test4 also. DEBUG = False sudo chown -R www-data:www-data /home/dave/mhprints/static sudo chmod -R 777 /home/dave/mhprints/static sudo chown -R www-data:www-data /home/dave/mhprints/staticfiles sudo chmod -R 777 /home/dave/mhprints/staticfiles sudo chmod -R 777 /var/www/staticfiles sudo chmod -R 777 /var/www/staticfiles I have ImageField set with upload_to='media' Current mapping of my project Mapping of VAR folder ROOTS AND URLS in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS … -
Recommend API SMS notification that will send to certain user from sqlite using Python and Django: AdminLTE
I have a management system, and I really need good SMS notifications. I'm using Python and Django's AdminLTE to embed and utilize sms notifications for a specific user from SQlite. I have tried to install twilio but it doesn't select or get from sqlite. -
django wizard form not working with bootstrap
I have a page that use bootstrap css for styling which is working fine, but when I add a django wizard form to this html page, all the bootstrap css disappear but other normal css file still working fine. html form {% load i18n %} {% load crispy_forms_tags %} {% load static %} {{ wizard.form.media }} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %} </button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %} </button> {% endif %} <input type="submit" value="{% trans " submit" %}"/> </form> views.py class indexForm(SessionWizardView): template_name = "main/indexform.html" form_list = [FormStepOne, FormStepTwo] def done(self, form_list, **kwargs): data_for_step1 = self.get_cleaned_data_for_step('0') data_for_step2 = self.get_cleaned_data_for_step('1') print(data_for_step1) print(data_for_step2) return render(self.request, 'main/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py path('indexform/', indexForm.as_view(), name='indexform'), I am not sure why my bootstrap css are not loading when others css file are loading correctly when adding the wizzard form -
AttributeError: 'Doctor' object has no attribute 'comments'
I'm working on this project but I got the following error comm = doctor_detail.comments.filter(active=True) AttributeError: 'Doctor' object has no attribute 'comments' however I think that everything is alright this is my models.py class Comments(models.Model): co_name = models.CharField(max_length=50, verbose_name="الاسم ") co_email = models.EmailField( max_length=50, verbose_name="البريد الالكتروني") co_body = models.TextField(max_length=400, verbose_name='التعليق') created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) post = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') def __str__(self): return 'علق {} على {}'.format(self.co_name, self.post) this is my views.py def doctor_detail(request, slug): # استدعاء جميع البينات اللي في البروفايل doctor_detail = get_object_or_404(Doctor, slug=slug) comm = doctor_detail.comments.filter(active=True) form = Commentair() if request.method == 'POST': form = Commentair(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = doctor_detail new_comment.save() form = Commentair() else: form = Commentair() return render(request, 'user/doctor_detail.html', {'doctor_detail': doctor_detail, 'comm': comm,'form': form }) I really don't know why I'm facing this error because the related name is available and I think everything is okay .please if there is an answer to this write it and explain it to me. thank you -
how to render values from multiple methods in table format in template django
I have a django app. And I have two methods: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] And I try to render them as table. so this is the views.py: def test(request): values1 = filter_text.total_cost_fruit() values2 = filter_text.total_cost_fruit2() context = { "values1": values1, "values2": values2, "all_values": list(chain(values1, values2)), } return render(request, "main/test.html", context) and template: <div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> </tr> {% for value in all_values %} <tr> <td>{{value.0}}</td> <td>{{value.1}}</td> </tr> {% endfor %} </table> </div> But nothing is displayed -
Perform post request using Django rest framework
I've got a Django rest framework APIView: class MyAPIView(views.APIView): def post(self, request): field = request.POST.get("field") print(field) return Response({"field": field}, status=200) I want to call it from separate process using Django API. I do it like this: request = HttpRequest() request.method = "POST" request.POST = QueryDict(mutable=True) request.POST["field"] = "5" response = MyAPIView.as_view()(request=request) But when field is being printed in MyAPIView it's always None. How to call post method using Django? -
Django - file upload not working on mysql and postgres but working on sqlite
I have a strange problem in my Django application. I have a front end file upload form in which user has to login and upload Excel file which will communicate with select box. The problem is that the file uploading is working on sqlite on local server and apache server on my vps. But its not working if I change my database to Postgres or Mysql. Sentry.io showing me this error (check image). MY code : ` <main class="bg-white container mb-3 mt-3 pb-3 pt-2 rounded rounded-2 text-dark"> <div class=" row justify-content-center"> <div class="medium-4 columns"> <h3 class="fw-bold m-5 text-danger text-center">Application Upload Form</h3> </div> <div class="col-md-7 columns medium-4 ms-5"> <div class="mb-3 rounded rounded-1"> <label for="formFile" class="form-label fw-bold">Generated Lot Number</label> <div id="lotnumberhashdiv" style="display:none">{{lot_hash}}</div> <p id="lotnumberdiv" class="bg-secondary p-4 rounded rounded-1 text-light">{{lotnumber}}</p> </div> <form id="upload-data-form" method="post"> {% csrf_token %} <div class="card rounded-1"> <div class="card-body"> <div class="mb-3"> <label for="fileSelect" class="form-label fw-bold">Choose File (only Excel/Csv)</label> <input class="form-control" name="file" id="excelfileinput" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" required> </div> <div class="mb-3"> <label for="formFile" class="form-label fw-bold">Choose Template</label> <select id="selecttemmplatetype" name="template" class="form-select" aria-label="Default select example" required> {% for template in template_types %} <option>{{template.template_name}}</option> {% endfor %} </select> </div> <button type="button" class="btn btn-lg btn-primary w-100" onclick="upload_data()" id="submitbutton">Submit Form</button> </div> </div> </form> </div> <!-- <div … -
dockerfile for selenium. 255 driver initialization error
There is a part of django that sends information via an API to be processed by selenium. There are problems with building docker under selenium. 255 selenium error in logs. I've already broken my head. Please tell me what could be the problem. latest version of geckodriver dockerfile FROM python:3.9 LABEL autor="LOADER" LABEL description="APP" WORKDIR /usr/src/html_loader/ COPY . /usr/src/html_loader/ RUN apt-get update RUN echo "Y" | apt-get install alien RUN echo "Y" | apt-get install gunicorn RUN echo "Y" | apt-get install memcached RUN echo "Y" | apt-get install unixodbc RUN echo "Y" | apt-get install unixodbc-dev RUN echo "Y" | apt-get install cifs-utils RUN echo "Y" | apt-get install libgtk-3-dev RUN echo "Y" | apt-get install libgtk-3-0 RUN echo "Y" | apt-get install libdbus-glib-1-2 RUN echo "Y" | apt-get install xvfb RUN apt-get install libaio1 RUN echo "deb http://deb.debian.org/debian/ unstable main contrib non-free" >> /etc/apt/sources.list.d/debian.list RUN apt-get update RUN echo "Y" | apt-get install -y --no-install-recommends firefox RUN apt-get update && apt-get install -y wget bzip2 libxtst6 libgtk-3-0 libx11-xcb-dev libdbus-glib-1-2 libxt6 libpci-dev && rm -rf /var/lib/apt/lists/* ENV pip=pip3 ENV python=python3 ENV DJANGO_HOST="http://crawlerdjango:4333" RUN pip install --upgrade pip COPY requirements.txt . RUN pip3 install -r requirements.txt RUN apt-get update --allow-releaseinfo-change … -
401 Client Error: Unauthorized for url [mozilla-django-oidc - Keycloack]
I'm trying to integrate Django and Keycloack using mozilla-django-oidc, but unfortunately I'm not having much success as I keep getting 401 Client Error: Unauthorized for url... I created a docker compose that runs Keycloack / KeycloackDB / Django app, like the following docker-compose.yaml version: '3' volumes: postgres_data: driver: local services: postgres: image: postgres volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: keycloak POSTGRES_USER: keycloak POSTGRES_PASSWORD: password networks: - local-keycloak keycloak: image: quay.io/keycloak/keycloak:latest environment: DB_VENDOR: POSTGRES DB_ADDR: postgres DB_DATABASE: keycloak DB_USER: keycloak DB_SCHEMA: public DB_PASSWORD: password KEYCLOAK_ADMIN: admin KEYCLOAK_ADMIN_PASSWORD: Pa55w0rd ports: - "8080:8080" depends_on: - postgres command: - "start-dev" networks: - local-keycloak volumes: - .local/keycloak/:/opt/keycloak/data web: build: context: . ports: - "8000:8000" depends_on: - postgres - keycloak volumes: - .:/app networks: - local-keycloak networks: local-keycloak: I setup my Django project as described in https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html#quick-start settings.py .... AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "mozilla_django_oidc.auth.OIDCAuthenticationBackend", ) BASE_URL = "http://localhost:8080" KEYCLOACK_IP = "http://192.168.192.3:8080" OIDC_RP_SIGN_ALGO = "RS256" OIDC_OP_JWKS_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/certs" OIDC_RP_CLIENT_ID = os.environ['OIDC_RP_CLIENT_ID'] OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = f"{BASE_URL}/realms/demo/protocol/openid-connect/auth" OIDC_OP_TOKEN_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/token" OIDC_OP_USER_ENDPOINT = f"{KEYCLOACK_IP}/realms/demo/protocol/openid-connect/userinfo" LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" views.py from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.template import loader def index(request): template = loader.get_template('index.html') return HttpResponse(template.render({}, request)) index.html {% if user.is_authenticated %} <p>Current user: {{ … -
Is django data migration immediately applied?
I read the following text on docs: """ Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active. See below for details. """ and I'm running the following data migration: def fill_query(apps, schema_editor): Result = apps.get_model('monitoring', 'Result') for r in Result.objects.all(): r.query = r.monitored_search.query r.user_id = r.monitored_search.user_id r.save() class Migration(migrations.Migration): dependencies = [ ('monitoring', '0006_searchresult_user_id'), ] operations = [ migrations.RunPython(fill_query), ] But when I try to find objects from Result I found that all still have query and user_id as null. And my data migration keep running (more than 2 millions registers on database) maybe the changes will be applied when data migration stop running or my data migration is not working? -
Creating date counter using javascript in django
Actually, I have a running counter, but when I pull the data with for, a few data comes in and while it should work in each of them, this counter works in only one of them, what should I change, here are my codes:enter image description here