Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Css and Javascript failing to load in html
Trying to add a slider to an html page in my django project, but css and javascript is not loading. Because of this instead of the slider being an actual slider ie. images sliding across, I get a vertical line of pictures. These are the errors i am getting in my browser console Failed to load resource: the server responded with a status of 404 (Not Found) slider.js:1 Uncaught ReferenceError: $ is not defined at slider.js:1 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) countdown.js:26 Uncaught TypeError: Cannot set property 'innerHTML' of null at updateClock (countdown.js:26) at initializeClock (countdown.js:36) at countdown.js:41 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) slider.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) This is the structure of my static folder static -->second ---->css >app slider.css ---->js >app slider.css my html {% load static %} <link rel="stylesheet" href="{% static 'second/css/app/slider.css' %}"> <script src="{% static 'second/js/app/slider.js' %}"></script> <div class="container"> <h3>Our Partners</h3> <section class="customer-logos slider"> <div class="slide"><img src="https://image.freepik.com/free-vector/luxury-letter-e-logo-design_1017-8903.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/3d-box-logo_1103-876.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/blue-tech-logo_1103-822.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/colors-curl-logo-template_23-2147536125.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/abstract-cross-logo_23-2147536124.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/football-logo-background_1195-244.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/background-of-spots-halftone_1035-3847.jpg"></div> <div … -
How to assign custom color in google column chart based on value (Django)
I have values : m=72 n=34 z=59 I got the fowlloing google column chart : <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Apple", {{m}}, "green"], ["Orange", {{n}}, "red"], ["Grape", {{z}}, "orange"],); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = {title: "Fruits",width: 1000, height: 400, bar: {groupWidth: "95%"},}; var chart = new google.visualization.ColumnChart(document.getElementById ("columnchart_values"));chart.draw(view, options);} </script> <div id="columnchart_values" style="width: 900px; height: 300px;"></div> i want to color values m,n or z in the following way: if value (m,n or z) more than 70 color green if value (m,n or z) more than 50 but less than 70 color orange if value (m,n or z) less than 50 color red Any help is appreciated. -
Djnago, is it possible to create multiple status choice with a model?
This is my actually models.py, that give me the possibility to create the status for a multiple choice: class Status(models.Model): slug = models.SlugField(unique=True) category = models.TextField() class Example(models.Model): category= models.ForeignKey(Status) I want to have the possibility to add a sub category. In other words, if I create a new category "Product" in my status model, I want to have the possibility to create the sub category choice, dipendet from the category, and selectable in my Example model in a new field called sub_category. -
TemplateDoesNotExist at /login/ registration/login.html
While I am creating login and logout using built-in login() and logout() views the following error occured. The templates login.html, logout.html are present in 'djangobin/templates/djangobin/login.html', 'djangobin/templates/djangobin/logout.html' TemplateDoesNotExist at /login/ registration/login.html Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Reference website: Overiq.com Reference website Link: https://overiq.com/django-1-11/django-logging-users-in-and-out/#using-built-in-login-and-logout-views Python version: 3.8.2 Django version: 3.0.5 OS: Windows 8.1 (32-bit) In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'djangobin', ] 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', 'django.middleware.common.BrokenLinkEmailsMiddleware' ] ROOT_URLCONF = 'django_project.urls' In urls.py: from django.contrib.auth.views import LoginView, LogoutView url(r'^login/$', LoginView.as_view(), {'templates_name': 'djangobin/login.html'}, name='login'), url(r'^logout/$', LogoutView.as_view(), {'templates_name': 'djangobin/logout.html'}, name='logout'), In login.html: {% extends "djangobin/base.html" %} {% block title %} Login - {{ block.super }} {% endblock %} {% block main %} <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Login</h4> <hr> {% if messages %} {% for message in messages %} <p class="alert alert-info">{{ message }}</p> {% endfor %} {% endif %} <form method="post"> {% csrf_token %} <table class="table"> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><button type="submit" class="btn btn-primary">Submit</button></td> </tr> </table> </form> </div> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Related Links</h4> <p> <a href="/password-reset/">Forgot Password?</a> <br> <a href="/register/">Create new account.</a> <br> <a href="#">Feedback</a> </p> </div> </div> {% endblock %} -
Is there a left join in django.extra() which can help me to join tables without any relationship in django
class Ordman(models.Model): pcod = models.CharField(db_column="PCOD", max_length=6) class Meta: managed = False db_table = "ORDMAN" class Shademst(models.Model): code = models.CharField(db_column="CODE", primary_key=True, max_length=6) class Meta: managed = False db_table = "SHADEMST" These both are connected without any relationship and I need to fire a left join query with the help of extra() in ORM in django but the join I can apply is inner join so can anyone help me to figure out how to apply left join in it. The database is a legacy database so can't do changes on it -
Django: Import models.py in other views.py
Basically a user can login, once the user is logged in she/he can takes a quiz, after have taken the quiz, on user_profile.html page she/he can sees the score. If the score is > x then can see the progress bar and some jobs applications. I created all to the point of "if score > x shows the progress bar" I can't print the {{ job.posizione }} I created on the "jobs" app. The idea was to import the jobs/models.py on the core/views.py but then I get stuck on a nested for loop on the user_profile.html template core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView # Create your views here. from quiz.models import Questions def homepage(request): return render(request, 'core/homepage.html') def userProfileView(request, username): user= get_object_or_404(User, username=username) categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= request.user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores) } return render(request, 'core/user_profile.html' , context) class UserList(LoginRequiredMixin, ListView): model = User template_name = 'core/users.html' core/user_profile.html {% extends 'base.html'%} {% block content %} <br> <div class="card-header"> <h3> {% if request.user == user %} Il tuo {% endif %} Profilo … -
django: OperationalError: no such column: child.parent_ptr_id
I am currently working on a django project where I want to make a model that inherits from another model: from django.db import models import uuid . . . class Asset(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) act_life_cycle_stage = models.CharField(max_length=255, default="Undefined Yet") act_hierarchy_level = models.CharField(max_length=255, default='Undefined Yet') class Test(Asset): name = models.CharField(max_length=5) But when I am in the admin window and I want to make a new Test-entry I get following error: django.db.utils.OperationalError: no such column: injectionmolding_test.asset_ptr_id Which I don't understand since I did python manage.py makemigrations beforehand and I also have a normal looking migration file: from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('injectionmolding', '0005_auto_20200419_1821'), ] operations = [ migrations.CreateModel( name='Asset', fields=[ ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('act_life_cycle_stage', models.CharField(default='Undefined Yet', max_length=255)), ('act_hierarchy_level', models.CharField(default='Undefined Yet', max_length=255)), ], ), migrations.CreateModel( name='Test', fields=[ ('asset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='injectionmolding.Asset')), ('name', models.CharField(max_length=5)), ], bases=('injectionmolding.asset',), ), ] What am I doing wrong? -
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.