Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker: Django + Mssql
Good morning everyone, I have a problem running Django + MSSQL on the docker outside the docker it runs normally, when I try to use it in the Docker the error occurs. ERROR DJANGO + MSSQL settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDB', 'USER': 'MyUser', 'PASSWORD': 'MyPass', 'HOST': 'MyHost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } My Docker File FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /Python WORKDIR /Python ADD requirements.txt /Python/ RUN pip install -r requirements.txt ADD . /Python/ My docker-compose version: '3' services: projeto-ouvidoria: build: ../images/ command: python3 Django/projetoOuvidoria/manage.py runserver 0.0.0.0:8000 container_name: PythonDjango volumes: - ../../Django:/Python/Django ports: - "8000:8000" - "3306:3306" extra_hosts: - "desenvDocker:192.168.99.2" My requeriments.txt django>=2.2,<3 djangorestframework>=3.11.0,<3.12.0 django-jet2 django-mssql -
Is there a way to customize authentication views that are included in URLConf?
In Django 3.0 documentation, it is said that the easiest way to implement authentication views is to just "include the provided URLconf in django.contrib.auth.urls in your own URLconf". Is there a way to modify some attributes of these class-based views without explicitly referencing them? For example, if I want to modify the extra_context attribute of the LoginView, is it obligatory to handle it as documented: from django.contrib.auth import views as auth_views from datetime import datetime urlpatterns = [ path('accounts/login', auth_views.LoginView.as_view(extra_context={'title':'Log In', 'year':datetime.now().year})), ] or is there a shortcut for modifying this view in the included URLConf? -
Display record from database to template
Hi i am building a project where there is a form which login user submits , so the user can submit the form multiple times i have used ForeignKey . Now i am struggling to display all the records associated with the user . for example : user 'abc' has fill form and he comes again and fill form so i want to show both the form details of user abc in my template , I am missing something as new to django views.py def PostTest(request): if request.method == 'POST': test = UserTest() test.user = request.user test.name = request.POST['name'] test.email = request.POST['email'] test.location = request.POST['location'] test.time = request.POST['time'] test.save() return render(request, 'posts/test.html') test.html {{ user.usertest.location }} models.py class UserTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() location = models.CharField(max_length=255) time = models.IntegerField() test_submitted = models.BooleanField() so i want to get the location filed in my template as user fill multiple times the form so i want all the location of that user in my django template , something looping may work but as newbie don't know how to use it. -
custom css switch does not run javascript function
I have a custom switch in CSS that I am using in a template for django. I am loading the javascript file properly but when I go to use the switch I don't get the expected result. The expected result is that the background would change colour this does not work using the switch. I added a button into the template to see if the button would work which it did, javascript file: function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); } HTML switch this does nothing: <div class="onoffswitch" style="position: fixed;left: 90%;top: 4%;" onclick="darkMode()"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="darkMode"> <label class="onoffswitch-label" for="myonoffswitch"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> HTML button that does do what is expected. <button onclick="darkMode()">Toggle dark mode</button> CCS if this is causing the problem: .onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; } .onoffswitch-checkbox { display: none; } .onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #000000; border-radius: 20px; } .onoffswitch-inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s; } .onoffswitch-inner:before, .onoffswitch-inner:after { display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px; font-size: 16px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; box-sizing: border-box; … -
Update the value of a model dynamically, by performing operations
I have 2 models, Order and Expense. The Expenses are based on Order ID. Whenever I add an expense, this should add to the total expense of the respective order. Models.py class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="order",blank=True,null=True) client_name = models.CharField(max_length=100) event_name = models.CharField(max_length=100) event_description = models.TextField(max_length=300,null=True,blank=True) expenses = models.PositiveIntegerField(default=0,null=True,blank=True) def __str__(self): return self.client_name class ProjectExpense(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="project_expense",null=True,blank=True) order_id = models.PositiveIntegerField(default='0',null=True,blank=True) exp = models.CharField(max_length=100) exp_desc = models.TextField(null=True,blank=True) amount = models.PositiveIntegerField(default='0') def __str__(self): return self.exp -
Django fail to use S3 for media storage
Good Day, I am trying to upload my media files to Amazon S3, I have created a bucket with public access, I have also created an IAM with full access of S3, and am using the keys. The site is developed, I wanted to try configuring S3 before moving it to server. I am able to upload files, but when I am trying to fetch files. I get the following error: The request signature we calculated does not match the signature you provided. Check your key and signing method. Here is my settings.py file: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = "/media/" LOGIN_REDIRECT_URL = 'books:home' LOGIN_URL = "users:login" AWS_ACCESS_KEY_ID = "" AWS_SECRET_ACCESS_KEY = "" AWS_STORAGE_BUCKET_NAME = "" AWS_S3_FILE_OVERWRITE =False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = "ap-south-1" Here is my pip freeze: asgiref==3.2.7 boto3==1.12.44 botocore==1.15.44 cachetools==4.1.0 certifi==2020.4.5.1 chardet==3.0.4 Django==3.0.5 django-bootstrap-form==3.4 django-crispy-forms==1.9.0 django-filter==2.2.0 django-filters==0.2.1 django-mailgun==0.9.1 django-storages==1.9.1 docutils==0.15.2 google-api-core==1.17.0 google-auth==1.14.1 google-cloud-core==1.3.0 google-cloud-storage==1.28.0 google-resumable-media==0.5.0 googleapis-common-protos==1.51.0 idna==2.9 jmespath==0.9.5 numpy==1.18.3 pandas==1.0.3 Pillow==7.1.1 protobuf==3.11.3 pyasn1==0.4.8 pyasn1-modules==0.2.8 python-dateutil==2.8.1 pytz==2019.3 requests==2.23.0 rsa==4.0 s3transfer==0.3.3 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.9 xlrd==1.2.0 Attached is the screenshot of the error -
Inheritance from an AbstractUser based Model in django 2.7
I have a Custom User Model extending the AbstractUser and it works fine. But now i want to create another Model that is extending my Custom User Model like this in models.py: class CustomUser(AbstractUser): phone = models.CharField(max_length=10, null=False, unique=True) town = models.CharField(max_length=25, null=False) class DeleveryPerson(CustomUser): code = models.CharField(max_length=10, null=False, unique=True) The problem is that the table DeleveryPerson is created with just the field "code" when I expected it to also have fields coming from the CustomUser model. So how can i achieve that kind of inheretane between CustomUser and DeleveryPerson. Thk! -
Can i make retrieve request in django from model parameter?
I am using Django rest framework for my api. In my views.py file i am using Viewset.ModelViewset. class SchemaViewSet(viewsets.ModelViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer My URL for this is : http://127.0.0.1:7000/api/schema/ THis is giving me GET and POST option. The response is something like this: { "id": 1, "name": "yatharth", "version": "1.1" }, To Delete/Put/Patch i have to pass id which is 1 like this: http://127.0.0.1:7000/api/schema/1/. Can i do this by name like this: http://127.0.0.1:7000/api/schema/yatharth/ instead of id. My model.py (I can Set name to unique = True) class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() def __str__(self): return self.name -
I want to reformate drf viewset url that uses @action decorator
how to reformat URL from http://localhost:8000/articles/{id}/comments/ to http://localhost:8000/articles/comments/{id}/ class ArticlesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet ): queryset = Articles.objects.order_by("-created") serializer_class = ArticlesSerializer @action(methods=["delete"], detail=True) def comments(self, request, *args, **kwargs): comment = Articles.objects.filter(comment=id).first() .......... how to make url as described above? -
Django "ljust" built-in template tags not working
I'm trying to use Django's ljust template tag but cannot get it to work. What am I doing wrong? <p class="card-text">{{article.excerpt|ljust:"400"}}</p> -
Django Model unittest
Good Morning!, I'm trying to write a tests for my app, but unfortunately something all the time is breaking up. Despite I create instance of the Post model, i'm still getting the same error. error ERROR: setUpClass (blog.tests.test_models.PostModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\db\models\base.py", line 456, in __init__ rel_obj = kwargs.pop(field.name) KeyError: 'author' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\db\models\base.py", line 461, in __init__ val = kwargs.pop(field.attname) KeyError: 'author_id' model def get_default_user(): return User.objects.get(is_superuser=True) class Post(models.Model): field = models.TextField(choices=TOPIC, default='N/A') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False) author = models.ForeignKey(User, on_delete= models.CASCADE, default=get_default_user) content = RichTextUploadingField() img = ResizedImageField(size=[1600, 1200], upload_to='post_pics', default='default.jpg') created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) tests from django.test import TestCase from blog.models import Post class PostModelTest(TestCase): @classmethod def setUpTestData(cls): Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) def setUp(self): self.post = Post.objects.get(title='Pierwszy post') def test_author(self): self.assertEqual(self.post.author == 'adam') -
How to query the database in Django forms?
I have a model: class Registration(models.Model): student_name = models.CharField(max_length=50) season = models.OneToOneField(Season) subject = models.OneToOneField(Subject) address = models.TextField() class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) I want to create a form for this model where the user will be given the option to select the subject based on the season that they selected. I have models for them as well: class Subject(models.Model): subject_name = models.CharField(max_length=50) ... class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) ... I dont know how to query the Form. Should It be a ModelForm or a regular Form? How to query the database in the form? -
Chart js in Django not showing when sent variable from views.py
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} (code of item) and {{top5TotalSales}} (sale amount). The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> -
Django: adding items to cart automatically by scanning its barcode
I am building a salle application for store. The idea is the same an online shopping. Rather than selecting the product, choose the order quantity, and then add to cart, I would like to add items to the cart by scanning the item barcode. Now, now by clicking on the product name, I am able to add items to my cart. How can I do it please. Here is the view of adding items to the cart def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') This is the template {% extends "shop/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="product-detail"> <h1>{{ product.name }}</h1> <h2><a href="{{ product.category.get_absolute_url }}">{{product.category }}</a></h2> <p class="price">{{ product.price }} MKF</p> <form action="{% url "cart:cart_add" product.id %}" method="post"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Ajouter au panier"> </form> {{ product.description|linebreaks }} </div> {% endblock %} Please assist me -
Issue on Extend the Django Custom Admin Site
I have create a custom admin site and added the custom button to specific model page by extend 'change_list.html'. The following is my issue. Missed the link of "WELCOME, ADMIN. VIEW SITE / CHANGE PASSWORD / LOG OUT" on top right of the header. How to extend the custom admin site? the current setting is extend default admin site. Default Admin Site Custom Admin Site New Page that Extend Admin Site mysite\urls.py from django.contrib import admin from django.urls import include, path from polls.admin import polls_admin_site urlpatterns = [ path('polls-admin/', polls_admin_site.urls, name='polls'), path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('polls-admin/polls/question/show', views.show, name='show'), ... ] polls\admin.py from django.contrib import admin from django.contrib.admin import AdminSite from .models import Question class PollsAdminSite(AdminSite): change_list_template = 'polls/templates/admin/polls/change_list.html' site_header = "Polls Admin" site_title = "Polls Admin Portal" index_title = "Welcome to Polls Portal" polls_admin_site = PollsAdminSite(name='polls_admin') class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'pub_date') list_display_links = ('question_text', 'pub_date') polls_admin_site.register(Question, QuestionAdmin) polls\views.py from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.template import loader from .models import Question, Choice ... def show(request): template = loader.get_template('polls/show.html') context = { 'text': 'Hello!', … -
Django:Problems related creating custom user
I'm trying to creating a custom user in django with AbstractUser class. code of models.py where i defined my custom_user. from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): country=models.CharField(max_length=20) i want only country as a extra field with users.That's why i defined only country filed. i have already mention my custom user model in settings.py. AUTH_USER_MODEL = 'new_user.MyUser' when i run migration command it run successfully but when i run migrate it giving me error.like this. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 90, in handle executor.loader.check_consistent_history(connection) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\loader.py", line 299, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency new_user.0001_initial on database 'default'. i have no idea what is this.Can anyone help with this. NOTE: I'm trying create custom user after creating my SuperUser and i have already migrate all migrations that comes when we first create our … -
Filenotfounderror while getting video length in django
Cannot get media file while calculating the video length in django after upload In my .views file ''' video_object = Video.objects.create( name = video_name, chapter = chapter, subject = subject, vfile = video_file, video_schedule = video_schedule, streaming_end_time = stream_end_time, quiz_count = quiz_count ) video_object.save() video_path = video_object.vfile.url video_length = get_length(video_path) video_object.video_duration = video_length return redirect('/admin_dashboard/') ''' get_length function ''' def get_length(filename): result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return float(result.stdout) ''' This is the video_path I'm getting at the error page, I have also added the media directory in the url file ''' video_path = '/media/media/video_zFnfdLY.mp4' ''' -
Django:Send email after redirect
Is there a way to send an email just after 'return redirect'? views.py Option 1: Placing 'send_mail' before 'redirect' if request.method == 'POST': formset = TestFormSet(request.POST,request.FILES,instance=project) if formset.is_valid(): subject = 'Notifications' html_message = "Testing notifications" recipient = ["testingemail@gmail.com"] send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False) formset.save() return redirect("home") With Option 1, the email is sent successfully but on the front-end the page has to wait until the email is sent before the redirection takes place. Option 2: Placing 'send_mail' after redirect if request.method == 'POST': formset = TestFormSet(request.POST,request.FILES,instance=project) if formset.is_valid(): formset.save() return redirect("home") subject = 'Notifications' html_message = "Testing notifications" recipient = ["testingemail@gmail.com"] send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False) With Option 2, formset is saved but email is not sent. Is there a way to send the email after the redirection so that the user doesn't wait for the email processing before the page is redirected? Thanks. -
How to display values in numbers instead of precentages in Plotly Pie chart?
Is there a way to display the actual values instead of percentage on the plotly pie chart? Below is the sample code which is a part of views.py file. The graph variable is then passed to HTML file to display the interactive image generated from plotly. import plotly.express as px import pandas as pd def my_view(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) a=os.path.join(BASE_DIR, 'db.sqlite3') con = sqlite3.connect(a) cur = con.cursor() df = pd.read_sql_query("SELECT * from POL", con) esd = df.groupby('ProjectStatus', as_index=False).agg({"ProjectID": "count"}) fig = px.pie(esd, values=Tasks, names=my_labels, color_discrete_sequence=px.colors.sequential.Blugrn) graph = fig.to_html(full_html=False, default_height=350, default_width=500) context = {'graph': graph} response = render(request, 'Home.html', context) The above would generate the attached pie chart. The values mentioned on hover should be displayed inside pie chart or on tooltip. Pie chart generated from above code -
join a image in mi view in django
Actually the original image is save on my downloads but I need the image to be stored in the database, not in my downloads, with the "nombre" of my model "programas" My model: class programas(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField('Nombres',max_length=50, blank= True) horas = models.CharField('Horas',max_length=50, blank= True) creditos = models.CharField('Creditos',max_length=50, blank= True) imagen = models.ImageField(blank=True, null=True) My view: def registroPrograma(request): if request.method == 'POST': form = ProgramaForms(request.POST, request.FILES) if form.is_valid(): programas = form.save(commit=False) programas.creditos= request.user imagen = qrcode.make('Hola Iver!') img = Image.open(programas.imagen) img = img.resize((2500, 2500), Image.ANTIALIAS) img = img.convert('JPG') img.paste(imagen, (0, 0)) x = img.save("/Downloads/hola.jpg") programas.imagen = img.paste(imagen, (0, 0)) form.save() return redirect('principio') else: form = ProgramaForms() return render(request,'registrar_programa.html', {'form':form}) -
How can i import my data frame from pandas in my template , i work with django, in order to display some éléments to user
I started a projet in django and i have some question. I have in my computer 100 files tab extension, and each one contains between 20,000 and 50,000 rows and 53 columns. That is an very big quantity of data. I implemented a template which will display to the user the name of the different columns, and so the user will check the name of the columns he wants to keep. After having selected these columns, on the server side, I have to recover these columns in each of the 100 files. Next, consider that each file corresponds to a vector, and that the elements of the vector correspond to different columns. Thus, When the user has selected the columns he wanted, this vector will correspond to an entry in a machine learning algorithm (for the moment, the choice of the algorithm does not interest me). What is the best way (in terms of complexity) to use my data (the 100 files), read it, merge columns, and more ..., in my django project? What I have done so far: _I have recovered my files in the form of dataframe using the pandas library. In this form and thanks to this … -
I want to run a new project in django and I get this error :ModuleNotFoundError: No module named 'C:\\Python39\\Lib\\site-packages\\django\\conf'
I created a project in virtualenv on windows and then tried to run it and this error occurred: Traceback (most recent call last): File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\\Python39\\Lib\\site-packages\\django\\conf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Windows\System32\django\django_project\manage.py", line 21, in <module> main() File "C:\Windows\System32\django\django_project\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Windows\System32\django\.venv\lib\site-packages\django\db\utils.py", line 225, in close_all for alias in self: File "C:\Windows\System32\django\.venv\lib\site-packages\django\db\utils.py", line 219, in __iter__ return iter(self.databases) File "C:\Windows\System32\django\.venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
Is Django Make Indexes for ManyToMany field?
i ask if Django make database indexes for ManyToMany Field ... and if yes is it do this for the model i provide in through ? i just want to make sure that database will go fast when it have a lot of data -
how to paginate and sort multiple querysets in same page?
I am using two query sets in one page and I want to have different paginations for each one this is my class based view: class MainListView(ListView): queryset = Post.objects.all() template_name = 'main.html' context_object_name = 'posts' def get_context_data(self, **kwargs): context = super(MainListView, self).get_context_data(**kwargs) context['news'] = EventsPost.objects.all() context['posts'] = self.queryset return context I want the Post model to be paginated by 3 and EventsPost by 6 Thanks for your responses -
Ideal way to check authentication token django x react
Im very new to React.js so i apologize if im asking a bad question. Right now i have just finished doing the authentication , however there are some issues that im facing and would like to know the best way of authenticating a get request / post request. I am using redux to store the authentication states . Logging in Upon completion of the form , i will enter the onFinish method which will call the dispatcher for logging the user in . Once the task of loggin in is successful , i will recieve a token of which i will check for this token within my render method (Im not sure if this is also the best way of doing things? seems highly likely to break): class Demo extends React.Component { formRef = React.createRef(); onFinish = values => { this.props.onAuth(values.username, values.password) } onFinishFailed = errorInfo => { console.log('Failed:', errorInfo); }; render() { let errorMessage = null; if (this.props.error) { errorMessage = ( <p>{this.props.error.message}</p> ); } if (this.props.token) { #<------- where i do the redirection , i will check for a token first. return <Redirect to="/" />; } return ( <div> {errorMessage} { this.props.loading ? <Spin size="large" /> : <Form …