Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type
i am trying to connet my style.css in django template using the static files {% static 'assets/css/style.css' %} but i keep seeing this error Refused to apply style from 'http://127.0.0.1:8000/assets/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.. NOTE: when i copy my css and manually paste it in a style tag inside the section everything works fine, but my css have over 23,000 lines of code and it's too much to be sitting in the head section of my project. Please how do i go about fixing this error. index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Favicon --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;700&family=Roboto:wght@400;500;700&display=swap"> <!-- Plugins CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/font-awesome/css/all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/tiny-slider/tiny-slider.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/glightbox/css/glightbox.css' %}"> <!-- Theme CSS --> <link id="style-switch" rel="stylesheet" type="text/css" href="{% static '/assets/css/style.css' %}"> </head> tree ├───base │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───course │ ├───migrations │ │ └───__pycache__ │ ├───templatetags │ │ └───__pycache__ │ … -
Django: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type
i am trying to connet my style.css in django template using the static files {% static 'assets/css/style.css' %} but i keep seeing this error Refused to apply style from 'http://127.0.0.1:8000/assets/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.. NOTE: when i copy my css and manually paste it in a style tag inside the section everything works fine, but my css have over 23,000 lines of code and it's too much to be sitting in the head section of my project. Please how do i go about fixing this error. index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Favicon --> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;700&family=Roboto:wght@400;500;700&display=swap"> <!-- Plugins CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/font-awesome/css/all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/tiny-slider/tiny-slider.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/glightbox/css/glightbox.css' %}"> <!-- Theme CSS --> <link id="style-switch" rel="stylesheet" type="text/css" href="{% static '/assets/css/style.css' %}"> </head> tree ├───base │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───course │ ├───migrations │ │ └───__pycache__ │ ├───templatetags │ │ └───__pycache__ │ … -
Django filter is not working even after search filter is applied in the url path and also in drf UI
This is my code: models.py class StoreLists(models.Model): id = models.AutoField(primary_key=True) store_name_ = models.CharField(max_length=300,unique=True) brand = models.CharField(max_length=300) class Meta: managed = False db_table = 'stores' serializers.py class StoreListSerializer(serializers.ModelSerializer): class Meta: model = StoreLists fields = "__all__" views.py class StoreListView(generics.GenericAPIView): # even tried with viewsets and ListModelView serializer_class = StoreListSerializer queryset = StoreLists.objects.all() filter_backends = (DjangoFilterBackend,) filterset_fields = ("store_name", "brand") def get(self, request): sales = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) urls.py GET - http://127.0.0.1:8000/api/v1/store_list - getting all data GET - http://127.0.0.1:8000/api/v1/store_list?brand=samplebrand - getting all data (filter is not working, same with search filter) Even added django_filters in application and also tried in postman and drf UI but not able to filter.` -
python manage.py runserver answer Python
PS C:\Users\user\PycharmProjects\mysite\mysite> python manage.py runserver Python PS C:\Users\user\PycharmProjects\mysite\mysite> When I write a request "python manage.py runserver", I get "Python". Terminal Pycharm, Windows 10, Python 3.10, Django 4.0.3 Please, tell me, how to fix this? -
How to automatically translate to another language if msgid and msgstr of a word is not provided in .mo or .po file in django?
I'm using i18n for translating english to hindi language settings.py if LANG_ENABLE: LANGUAGES = [ ('en', 'English'), ('hi', 'Hindi'), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True urls.py urlpatterns += i18n_patterns( # Include urls for mamber path('members/', include('member.urls')), # Include urls for about us path('about-us/', include('about_us.urls')), ) i have run ```django-admin makemessage -l hi``` a folder locale/hi/LC_MESSAGES with ```django.mo``` and ```django.po``` has been created 1. there are few words which i have added in .po file under ```msgid``` and ```msgstr``` for translation 2. there are few words which {% trans %} convert to hindi by itself. (there translation are not added in ```.mo``` ```.po``` file 3. and other words are not getting translated( which i have not added in ```.mo``` ```.po``` file can i do something like if no translation provided in .mo and .po then it should automatically convert to other language(hindi language). It is working few few words but not for whole page. How can i achieve this. -
Changing front-end image based on back-end variable change without reloading page in django
I'm using Django framework to monitor garbage fill ratio. I' m getting the data via IOT device with Raspberry Pi. So when the sensor data change, I want to change the image on front-end without page reload. So I want to see real time data on front-end. I searched about Django channels but I can not figure it out how to change image. <body> <h1 class="title">Garbage Monitoring System</h1> <div class="trash-bin"> {% if binCapacity == 0 %} <img src="static/images/0.png" alt="zeroGarbage" /> <p>Fill Ratio: 0%</p> {% elif binCapacity == 25 %} <img src="static/images/25.png" alt="%25 Garbage" /> <p>Fill Ratio: 25%</p> {% elif binCapacity == 50 %} <img src="static/images/50.png" alt="%50 Garbage" /> <p>Fill Ratio: 50%</p> {% elif binCapacity == 75 %} <img src="static/images/75.png" alt="%75 Garbage" /> <p>Fill Ratio: 75%</p> {% elif binCapacity == 100 %} <img src="static/images/100.png" alt="%100 Garbage" /> <p>Fill Ratio: 100%</p> {% endif %} </div> </body> -
Is it possible to override a wagtail.hooks.register function with a custom function?
Is it possible to override a wagtail @hooks.register function with a custom function or to de-register a function all together? One example of what I would like to achieve is editing the register_styleguide_menu_item function in in wagtail/contrib/styleguide/wagtail_hooks.py so that the style guide is only shown to superusers. For example; I would like to override the current function: @hooks.register("register_settings_menu_item") def register_styleguide_menu_item(): return MenuItem( _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000 ) with this: @hooks.register("register_settings_menu_item") def register_styleguide_menu_item(): return AdminOnlyMenuItem( _("Styleguide"), reverse("wagtailstyleguide"), icon_name="image", order=1000 ) (note the change from MenuItem to AdminOnlyMenuItem on the third line) The docs for wagtail hooks are available at https://docs.wagtail.org/en/stable/reference/hooks.html but it doesn't cover this scenario. Is there a mechanism to achieve this? -
In views.py file ==> category_posts = Post.object.filter(category=cat) returns an empty query set. The 'Post' model has sample posts with categories
I am creating a blog application in django where i encountered this unusual issue. I am not being able to filter and display blog posts category wise. Please find my code below. Thanks in advance. I have spent two full days trying to figure this out and still got nothing. MODELS.py This is the model which i have created for a blog post. class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): #return reverse('article-detail', args=(str(self.id))) return reverse('homepage') VIEWS.py This is the view that i have created for a category wise blog posts. def CategoryView(request,cat): category_posts = Post.objects.filter(category=cat) return render(request,'categories.html',{'category_posts':category_posts}) URLS.py The urls.py file. path('category/<str:cat>/', CategoryView, name = 'category'), CATEGORIES.html This will be the final display page where the category_posts is displayed as an empty queryset. The for loop is unable to run because category_posts is an empty queryset. Single word categories are also empty(to rule out a slugify issue) {% extends 'base.html' %} {% load static %} {% block content %} <ul> {% for post in category_posts %} <li> <div class="category"> <a href="{% url 'category' post.category|slugify %}">{{ post.category … -
How to prevent a logged in user from posting a post using anothers user name in django rest framework
In my Django rest framework project I want to make sure that for example if testuser1 is logged in when posting a post cannot on the author part chose testuser2 and post the post with the author being testuser2. How I can I make sure only the logged in user creates a post? my models.py from turtle import title from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title my views.py from django.shortcuts import render from rest_framework import generics, permissions from .models import Post from .serializers import PostSerializer from .permissions import IsAuthorOrReadOnly class PostList(generics.ListCreateAPIView): #permission_classes = (permissions.IsAuthenticated,) queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer my serializers.py from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'author', 'title', 'body', 'created_at',) model = Post my permissions.py from re import T from tkinter.tix import Tree from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Read-only permissions are allowed for any request if request.method in permissions.SAFE_METHODS: return True # Write permissions … -
Advise on orm modelling in django
I am building a webapp in which users place orders with nested information. I am after some advice on best practice so I can do some more research. The idea is that a user either loads an existing order, or creates a new order. They then fill in the subsequent order fields, which can be on a one to many basis. My initial thought was to use a variable for order_id and use a foreign key to link the instances of the other classes. However, this seems overcomplicated. order_id would have to be unique and sequential. Is this the best approach to this issue? class Order(models.Model): order_id= xxxx created_by = xxxx class A(models.Model): order_id = models.ForeignKey(xxxxx) someclassafield = xxxx class B(models.Model): order_id = models.ForeignKey(xxxxx) someclassbfield = xxxx This would give the user the ability to create orders such as below: Order 1 (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_B, order_id, someclassbfield) Order 2 (Class_A, order_id, someclassafield) (Class_A, order_id, someclassafield) (Class_B, order_id, someclassbfield) (Class_B, order_id, someclassbfield) -
Multilanguage's Sitemap, get_absolute_url and location
Plz help me with the correct Sitemap generation. My multilanguage site on Django 2.2 with standard internationalization framework. Model.py with get_absolute_url class Data(models.Model): ... def get_absolute_url(self): from django.urls import reverse return reverse("data_detail", kwargs={"slug": str(self.id)}) Sitemap.py class DataSitemap (Sitemap): changefreq = "daily" priority = 0.5 i18n = True def items(self): return Data.objects.all() def location(self, obj): return '/news/data/%s/' % (obj.pk) url.py from django.contrib.sitemaps.views import sitemap from .sitemaps import DataSitemap sitemaps = { 'data' : DataSitemap } urlpatterns = i18n_patterns( path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name='django.contrib.sitemaps.views'), ) Now when I generate sitemap.xml I get no language prefix, <url> <loc>example.com/news/data/1/</loc> <lastmod>2022-03-24</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>example.com/news/data/1/</loc> <lastmod>2022-01-08</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> </url> For the other Model without with get_absolute_url but without harcoded location - everything works fine, language prefix added correctly. How can I fix my Sitemap code? -
'QuerySet' object has no attribute '_meta', Django with ajax
I am building a site for a tattoo shop. In my index view I first display all tattoos by every artist but I am trying to allow users to filter tattoos by artist and then update the page displaying tattoos by the selected artist using jquery/ajax. Artist and Tattoo models: class Artist(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) # etc class Tattoo(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=150) image = models.ImageField(upload_to='images/') date_created = models.DateTimeField(auto_now_add=True) forms.py: class FilterArtForm(ModelForm): class Meta: model = Tattoo fields = ['artist'] widgets = { 'artist': forms.Select(attrs={'id': 'filter_by_artist'}), } views.py: def index(request): tattoos = Tattoo.objects.order_by('-date_created') filter_art_form = FilterArtForm() artist_id = request.GET.get('artist') if artist_id: artist = Artist.objects.get(pk = artist_id) tattoos = tattoos.filter(artist=artist) # trying to return this as a JsonResponse is causing some kind of issue return JsonResponse({'tattoos': model_to_dict(tattoos)}, status=200) return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form}) I am new to working with ajax so I was just messing around with my view and if I try to return only the Artist object as such: def index(request): tattoos = Tattoo.objects.order_by('-date_created') filter_art_form = FilterArtForm() artist_id = request.GET.get('artist') if artist_id: artist = Artist.objects.get(pk = artist_id) return JsonResponse({'artist': model_to_dict(artist)}, status=200) return render(request, 'core/index.html', {'tattoos':tattoos, 'filter_art_form': filter_art_form}) this will work and I … -
Djanog login not persisting
Login and Log out is only working for admin panel , not for user panel , after loging in from user end , its not getting reflected in the home screen . The default login(request,user) is not setting user to request.user . Thats why after loging in when redirecting to home page there request.user in home page request.user is showing anonymous user instead of loged in user . How to solve this ? I am using custom user model . If it could be solved by Application Backend , then Show How . models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractBaseUser , PermissionsMixin from .UserManager import UserManager from datetime import datetime class User(AbstractBaseUser,PermissionsMixin): username = None FullName = models.CharField(max_length=50) Email = models.EmailField(unique=True) Uid = models.CharField(max_length=6,default="TD") SignUpTime = models.CharField(default=((datetime.today()).strftime("%H:%M >> %a %d-%b-%Y")),max_length=25) is_staff = models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) is_active=models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ["FullName"] UserManager.py from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.hashers import check_password class UserManager(BaseUserManager): use_in_migrations = True def create_user(self,Email,password,**extra_fields): if not Email: raise ValueError("Email is Required") email = self.normalize_email(Email) user = self.model(Email=email,**extra_fields) user.set_password(password) user.save() user = self.model.objects.get(Email=email) return user def create_superuser(self,Email,password,**extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') != True: raise ValueError("not a staff") … -
Python Django, API Call with user input
I’m currently building a little Django Project and I’ve got a question. I would like to make an API Call to an external API with a user input. How can I achieve that? Pretty new to Django sorry. Regards, -
Connecting a Neo4j graph database to a Django REST API app
I am trying to connect a remote Neo4j database to a Django app with a REST API. I am trying to specify the database in the settings.py file using the following code: DATABASES = { 'default': { 'NAME': 'papers.db', 'ENGINE': 'django.db.backends.sqlite3', 'USER': '', 'PASSWORD': '', 'PORT': '', }, } I would like to know: What python libraries need to be installed in order to do this? What is the 'ENGINE' that needs to be specified in the code above? The Neo4j database has a URI, but does not provide us with an IP address - am I able to use this URI? I am confident that I know what the other parameters need to be. Thanks in advance -
pip install django-jalali-date problm
Import "jalalienter image description here_date" could not be resolved After installation, I will make a mistake. Thank you for your help -
Can i use Django Admin for the user interface when there will only be 2-3 users?
i am working on a project where i am creating a project management webapp for a small team (4-5 users). They will use it mainly for data management (CRUD operations for projects, resources, work hours, budgets etc.) and creating reports. For the CRUD part of the application i want to use Django Admin. Only 2-3 users will apply CRUD operations on the data. So i want to call them "administrators" and use the built-in Admin app because it literally has all the functionalities i need. It will save a lot of time and costs which is very important for this project I read that Admin is only meant for site administrators and this is not recommended. My question is: With this use case for the application can i use a Django admin app as a part of the User interface? Thanks in advance -
convert ManyToManyField to ForeignKey in Django
I have 3 models: class Series(models.Model): . . . series_name = models.CharField(max_length=50, unique=True) class Lists(models.Model): . . name = models.CharField(max_length=50, unique=True) class Article(models.Model): . . . lists = models.ForeignKey(Lists, blank=True, null=True, related_name='article_has', on_delete=models.CASCADE, default=None) series = models.ManyToManyField(Series, related_name='series', blank=True) is_published = models.BooleanField(default=False) Initially I created some Articles without 'lists' field. Now i want to add the 'Lists' field to the Article model but I am running into errors after makemigrations and migrate. I did the following: python manage.py makemigrations blog python manage.py migrate python manage.py makemigrations --empty blog modified the new empty generated migration file as follows: # Generated by Django 4.0.3 on 2022-05-03 13:54 from django.db import migrations def migrate_m2m_to_fk(apps, schema_editor): Article = apps.get_model("blog", "Article") for article in Article.objects.all(): article.lists = None article.lists.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.RunPython(migrate_m2m_to_fk) ] python manage.py migrate and at the step 5 I get the following error due to Article.objects.all() : MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'blog_article.lists_id' in 'field list'") -
Django collectstatic to look for assets directory in every app in django project
Currently I have 6-7 apps present inside my Django project. In settings.py for STATICFILES_DIRS I need to specify assets directory full path present inside all my apps which is cumbersome in case when I increase my apps everytime I need to add the path here. Isn't there one setting with which I can specify just the assets folders and the collectstatic command will look for static files inside assets in all my apps? This is what I currently have: STATICFILES_DIRS = [ BASE_DIR / "app1/templates/assets", BASE_DIR / "app2/templates/assets", BASE_DIR / "app3/templates/assets", BASE_DIR / "app4/templates/assets", BASE_DIR / "app5/templates/assets", BASE_DIR / "app6/templates/assets", ] What I needed was something like this and the collectstatic would have gone to all my apps(1-6) looking for the assets directory. STATICFILES_DIRS = [ 'templates/assets', ] Is there any way to do the same? -
TypeError at / sequence item 0: expected str instance, _SpecialGenericAlias found in Django templates?
I am working on an application that can parse resume content and summarize it. This application is taking input in pdf format and when I upload the pdf file of resume it is showing this error on rendering the template. I am adding a code snippet for my template folder in which it is showing this error. Error during template rendering In template D:\all projects and programs\Machine Learning Projects\resume1\resume_Shortlisting\Application\ResumeParser\resume_parser\parser_app\templates\messages.html, error at line 4 {% if messages %} <div class="messages" style="margin-top: 2%;"> {% for message in messages %} <div {% if message.tags == 'error' %} class="alert alert-danger" {% else %} class="alert alert-{{ message.tags }} "{% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} </div> {% endfor %} </div> {% endif %} -
how to convert function base api views into class base api views?
In my project, I have the following 4 APIs (function base API view) save_user() login_user() get_user_info() update_user() I want to convert it into class base API view class UserApi(APIView): def post(): #save user def get(): #for get user info def put(): #for update user info so how to use login() in class base views. OR use function base view for login? to use a mixture of class based API view and function base API view in a single views.py file is good or bad? -
GET Error takes from 2 to 3 positional arguments but 12 were given in Djnago Rest Framework
Hi Everyone i am trying to create api using raw sql query, but when i hit url get getting error please help me out. as per me issue in dates parameter where i am using 7 days but something gets wrong, thats why getting error, i didn't know how to solve this, please help me. views.py # this is views file where i have executing my query. class CardailyReportViewset(viewsets.ModelViewSet): queryset=Car_dash_daily.objects.all() serializer_class=CarDashdailySerializer def retrieve(self, request, *args, **kwargs): params= kwargs params_list=params['pk'].split(',') dates=params_list[0] team_id=params_list[1] start_date=params_list[2] end_date=params_list[3] car_report= connection.cursor() car_report.execute(''' SELECT temp2.car_number,sum(temp2.trips)as total_trips, temp2.status, case when sum(temp2.day1_trips)=-10 then 'BD' when sum(temp2.day1_trips)=-20 then 'ND' when sum(temp2.day1_trips)=-30 then 'R' when sum(temp2.day1_trips)=-40 then 'I' when sum(temp2.day1_trips)=-50 then 'P' else sum(temp2.day1_trips) end AS day1_trips, case when sum(temp2.day2_trips)=-10 then 'BD' when sum(temp2.day2_trips)=-20 then 'ND' when sum(temp2.day2_trips)=-30 then 'R' when sum(temp2.day2_trips)=-40 then 'I' when sum(temp2.day2_trips)=-50 then 'P' else sum(temp2.day2_trips) end AS day2_trips, case when sum(temp2.day3_trips)=-10 then 'BD' when sum(temp2.day3_trips)=-20 then 'ND' when sum(temp2.day3_trips)=-30 then 'R' when sum(temp2.day3_trips)=-40 then 'I' when sum(temp2.day3_trips)=-50 then 'P' else sum(temp2.day3_trips) end AS day3_trips, case when sum(temp2.day4_trips)=-10 then 'BD' when sum(temp2.day4_trips)=-20 then 'ND' when sum(temp2.day4_trips)=-30 then 'R' when sum(temp2.day4_trips)=-40 then 'I' when sum(temp2.day4_trips)=-50 then 'P' else sum(temp2.day4_trips) end AS day4_trips, case when sum(temp2.day5_trips)=-10 then 'BD' when … -
ModuleNotFoundError: No module named 'scanner.wsgi'
2022-05-04T03:48:55.987895+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-04T03:48:55.987896+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2022-05-04T03:48:55.987896+00:00 app[web.1]: ModuleNotFoundError: No module named 'scanner.wsgi' 2022-05-04T03:48:55.988039+00:00 app[web.1]: [2022-05-04 03:48:55 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-05-04T03:48:56.025390+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Shutting down: Master 2022-05-04T03:48:56.025449+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-05-04T03:48:56.211911+00:00 heroku[web.1]: Process exited with status 3 2022-05-04T03:48:56.415253+00:00 heroku[web.1]: State changed from starting to crashed 2022-05-04T07:19:55.297563+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=eth-scan.herokuapp.com request_id=ebd93840-9d54-4797-ac0c-b095b1c69601 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https 2022-05-04T07:19:55.695154+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=eth-scan.herokuapp.com request_id=7a30fa28-053b-46f6-ab2e-3e3d9216c040 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https -
Django and Javascript Uploading Images with Progress Bar
Good day, I am trying to upload multiple images in django with a progress bar. Currently, I have a working solution for only one image but now I want to add more fields and I need to show progress bar for all the images I am uploading. Below is my working code and the commented out code in the forms.py are the new fields I want to add. models.py class ProductImage(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True) main_image = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_one = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_two = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_three = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_four = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_five = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) forms.py class StoreDashboardProductUpdateForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "main_image", # "img_one", # "img_two", # "img_three", # "img_four", # "img_five" ] views.py def store_dashboard_product_update_view(request, slug, product_slug, pk): product = get_object_or_404(Product, pk=pk) form = StoreDashboardProductUpdateForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.instance.product = product form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, "object": product } return render(request, 'store/dashboard/product_update.html', context) product_update.html {% extends 'store/dashboard/base/products-second.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <style> .not-visible { display: none; … -
Django user check_password returns False in tests
I've customized my User manager created create_user and create_superuser method and it's working fine but when I run test on it it fails because of user.check_password() it returns False. I found this post according to it Django unable to identify the correct hasher. This is my UserManager class class UserManager(BaseUserManager): def create_user(self, email, passowrd=None, **extra_fields): '''Creates and saves a new user''' phone = extra_fields.get('phone') if not email: raise ValueError("User must have an email address") if not phone: raise ValueError("User must have a phone number") user = self.model(email=self.normalize_email(email), **extra_fields) user.phone = phone user.set_password(passowrd) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): '''Creates and saves a new superuser''' user = self.create_user(email, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user and this my test method for testing user creation def test_create_user_with_email_and_phone(self): '''Test creating new user with an email and phone successfuly''' email = 'demo@gmail.com' password = 'demo@1234' phone = 1234567890 user = get_user_model().objects.create_user( email=email, password=password, phone=phone ) self.assertEqual(user.email, email) self.assertEqual(user.phone, phone) print(f'\n User Password : {user.password} \n') print(f'\n Check Password : {user.check_password(password)} \n') self.assertTrue(user.check_password(password)) this is output of print() function User Password : !dAqIjSVT6hpEhKj4JEjLLDAB3hAJt042Zaj8JS8R Check Password : False