Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Auth - Unhash the hashed password
I have two server and one is using Django. My auth flow is that Server A(using Django) if the user submit the right account & password Then Server A will pass the password to Server B update the password. So how can I unhash the password in Django DB and pass the raw password to the Server B? -
django - production/development migrations and databases mixed up
This is my first Django app deployment, a lot to learn. So this is my settings for DATABASES in settings.py if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': 'localhost', 'PORT': '', } } Problem: For fixing a bug, I updated some fields in models locally, git push, and git pull on server, make migrations on server like I normally would locally; the migrations were successful, however, they don't seem to have applied (if it's of any relevance, the bug fixing was some phone number field changed from IntegerField to CharField, preventing the error "Verify that this value is less than or equal to 2147483647"; But the weird thing is there wasn't any error for the cellphone IntegerField before deployment and running locally) Confusion: I remember that only one superuser was created on postgres database, or at least I thought it was, but I can log in with this superuser account in both production and development (that is no matter the DEBUG is set to True or False), how is that possible?? Same are the images uploaded only once, but … -
I am unable to install pillow file and currently using python 3.5.1, also having an error while coding, the error is NameError
Also while coding its not identifying models, even i have added apps file of models in settings. Also am unable to install pillow file and when i am checking django version its showing the command Found Exception, it was working till yesterday and now its not working stuck in between don't know why so? I have tried several things to resolve the same but nothing is happening and its so frustrating that i am unable to solve this error. File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined (myproject) D:\project\mysite\mysite>C:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py Traceback (most recent call last): File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined (myproject) D:\project\mysite\mysite>:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py (myproject) D:\project\mysite\mysite>C:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py Traceback (most recent call last): File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined -
why djnago save method not works? why it create new once?
I'm trying to build a to do app by django, inserting data works fine but when want to update it not updates, it create new once, here's my code. from django.urls import path, include from . import views urlpatterns = [ path('',views.index, name='list'), path('update/<str:pk>/', views.update, name='update') ] views code from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. #index function def index(request): tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context ={'tasks': tasks, 'form':form} return render(request,'index.html', context) #update function def update(request,pk): tasks = Task.objects.get(id=pk) form = TaskForm(instance=tasks) if request.method == 'POST': form = TaskForm(request.post, instance=tasks) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request,'update_task.html',context) update_task.html code is <body> <h3>Update</h3> <form method="POST" action="/"> {% csrf_token %} {{ form }} <input type="submit" name="submit"> </form> </body> when want to update it not updates, it creates new once. wheres my problem? help me please. Thanks -
Django Search Form Errors When Adding to_form_field
Whenever I try to add to_form_field to subject and membership form fields, I get the following errors: ValueError: invalid literal for int() with base 10: 'Programming' ValueError: invalid literal for int() with base 10: 'Free' Field 'id' expected a number but got 'Programming'. Field 'id' expected a number but got 'Free'. URL without to_form_name: http://127.0.0.1:8000/courses/?name=&min_views=&max_views=&min_date=&max_date=&expertise=&subject=1&membership=1 URL with to_form_name: http://127.0.0.1:8000/courses/?name=&min_views=&max_views=&min_date=&max_date=&expertise=&subject=Programming&membership=Free I would like to be able to pass the actual string rather than the number in the URL for SEO purposes. When I leave to_field_name out of forms.py, there is no error and my search form filtering works. But it puts numbers in the URL which is undesirable. Views.py: class CourseListView(ListView): model = Course def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): title_contains_query = self.request.GET.get('name') view_count_min = self.request.GET.get('min_views') view_count_max = self.request.GET.get('max_views') date_min = self.request.GET.get('min_date') date_max = self.request.GET.get('max_date') skill_level_query = self.request.GET.get('expertise') subject_query = self.request.GET.get('subject') membership_query = self.request.GET.get('membership') if title_contains_query: qs = qs.filter(title__icontains=title_contains_query) if view_count_min: qs = qs.filter(visited_times__gte=view_count_min) if view_count_max: qs = qs.filter(visited_times__lte=view_count_max) if date_min: qs = qs.filter(created_at__gte=date_min) if date_max: qs = qs.filter(created_at__lte=date_max) if skill_level_query: qs = qs.filter(skill_level=skill_level_query) if subject_query: qs = qs.filter(subject=subject_query) if membership_query: qs = qs.filter(allowed_memberships=membership_query) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = … -
Get all html templates in django
Is there a way to get the list of html name templates on a template folder in views? eg. app/templates ----> sample.html ----> sample2.html -
Django-import-export importing empty values always
Greetins im using Django-import-export with django 3, im trying to import a csv file but its always importing like there is no data in the file. i have followed the tutorial, and try diferent approach in the configuration of the resource, but nothing works, it always upload all the data empty like this: this is my model: class Product (Master): internal_id = models.IntegerField(verbose_name=_("internal id"), default=0) year = models.IntegerField(verbose_name=_("model year"), default=0) engine = models.CharField(verbose_name=_("engine type"), max_length=100, null=True, blank=True) fuel = models.CharField(verbose_name=_("fuel type"), max_length=100,null=True, blank=True) gearbox = models.CharField(verbose_name=_("gearbox type"), max_length=100, null=True, blank=True) traction = models.CharField(verbose_name=_("traction"), max_length=100, null=True, blank=True) color = models.CharField(verbose_name=_("Color"), max_length=100, null=True, blank=True) doors = models.IntegerField(verbose_name=_("doors number"), default=4, null=True, blank=True) seats = models.IntegerField(verbose_name=_("seats number"), default=5, null=True, blank=True) length = models.FloatField(verbose_name=_("length"), default=0, null=True, blank=True) height = models.FloatField(verbose_name=_("height"), default=0, null=True, blank=True) wide = models.FloatField(verbose_name=_("wide"), default=0, null=True, blank=True) mileage = models.FloatField(verbose_name=_("mileage"),default=0, null=True, blank=True) cylinders = models.IntegerField(verbose_name=_("cylinders"),default=0, null=True, blank=True) brand = models.CharField(verbose_name=_("brand"), max_length=100, null=True, blank=True) price = models.BigIntegerField(verbose_name=_("price"), default=0, null=True, blank=True) category = models.ForeignKey('products.Category', on_delete=models.CASCADE, blank=True, null=True, verbose_name=_("category")) url=models.SlugField(max_length=100, verbose_name=_("url")) class Meta: ordering = ["internal_id", "name", "updated"] verbose_name = _("product") verbose_name_plural = _("products") def save(self, *args, **kwargs): url=str(self.internal_id)+str(random.randrange(0,1000))+"-"+str(self.name) self.url = slugify(url) super(Product, self).save(*args, **kwargs) this is my resource: class ProductResource(resources.ModelResource): class Meta: model = Product … -
How to update extended user profile in Django with one-to-one link?
I am trying to figure out how to extend the User model using a One-to-One relationship in Django. I'm creating a user Profile to hold extra information about the User. However, I am new to Django and do not understand how I update this user Profile. I want to add a UserProfileSerializer to the serializers file to update the Profile, how do I do this? And how do I call this in my views file? The closest information I can find is: def update_profile(request, user_id): user = User.objects.get(pk=user_id) user.profile.bio = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...' user.save() However, I do not understand how I can reference the user_id through my serializer class, or how I can pass through user_id from a request. Below is the User model serializer and views, and the Profile model. The profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pin = models.CharField(null=True, max_length=4, blank=True) birth_date = models.DateField(null=True, blank=True) security_question_1 = models.CharField(null=True, max_length=100, blank=True) security_question_2 = models.CharField(null=True, max_length=100, blank=True) security_question_3 = models.CharField(null=True, max_length=100, blank=True) # post_save is the signal received when a save event occurs in the User model @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): … -
ModelForm save() method override not being called with UpdateView
I have a ModelForm .save() method override which is not functioning and I do not understand why. It is being used with a class-based UpdateView. ModelForm: class CompanyForm(forms.ModelForm): schema_name = forms.CharField() name = forms.CharField() address = forms.CharField() city = forms.CharField() state = forms.CharField() zipcode = forms.CharField() phone = forms.CharField(min_length=10) email = forms.CharField() x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Company fields = ['name', 'address', 'city', 'state', 'zipcode', 'phone', 'email', 'image', 'x', 'y', 'width', 'height',] widgets = { 'company_type': forms.HiddenInput(), 'image': forms.FileInput(attrs={'accept': 'image/*'}), } def save(self, commit=True): photo = super(CompanyForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') print(x, y, w, h) # <----------------------------------- this is not printing image = Image.open(photo.image) image = ImageOps.exif_transpose(image) if image.mode != 'RGB': image = image.convert('RGB') cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((400, 400), Image.ANTIALIAS) resized_image.save(photo.image.path) return photo UpdateView: class CompanyUpdateView( PermissionRequiredMixin, LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Company form_class = CompanyForm success_message = 'Company successfully updated!' success_url = reverse_lazy('accounts') permission_required = ('companies.change_company',) permission_denied_message = 'User does not have permissions to change company.' Sorry about including so much code but I have a feeling it is needed. … -
Overwrite Django model __init__ method
The Ingredient model of my Django project has an IntegerField which declares if this ingredient stock is managed by weight, units, or litters. Although the database has its integer value I have to display its name. And instead of looping over every ingredient and setting its value, I thought it was better to overwrite the __init__ method of the Python class, but I don't get how. models.py: class Ingredient(models.Model): def __init__(self): super(Ingredient, self).__init__() if self.cost_by == 1: self.cost_by = 'Units' elif self.cost_by == 2: self.cost_by = 'Kilograms' elif self.cost_by == 3: self.cost_by = 'Litters' #...etc... So far I tried with this, but I'm getting the following error: __init__() takes 1 positional argument but 0 were given Which argument should I pass? -
Yet another: URL resolves, but in a Django template URL NoReverseMatch(es)
I have a Python3.7, Django3.0 situation involving a URL that Exception Type: NoReverseMatch Exception Value: Reverse for 'create' not found. 'create' is not a valid view function or pattern name. Your assistance in this matter is appreciated. After reading a gobsmack of other questions similar to mine, I'm guessing there is a typo I just can't see. Maybe you can see it :D Many mahalos. library(app)/urls.py: from django.urls import path from . import views app_name = 'library' urlpatterns = [ path('', views.IndexView, name='index'), path('create/', views.CreateLibraryView, name='create'), ] mycastle(project)/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('library.urls')) ] The views are wholly unremarkable: def IndexView(request): library_list = Library.objects.all() return render(request, 'library/index.html', {'library_list': library_list}) def CreateLibraryView(request): library_list = Library.objects.all() return render(request, 'library/create.html', {'library_list': library_list}) and a base template that just wants to connect in a meaningful way: <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'create' %}" class="top-menu"> <i class="fa fa-rocket"></i> Create a new library! </a> {% endif %} If I take the {% url 'create' %} line out - all the URLs resolve properly and happiness abounds. -
Can you set the value of a third option URL path() dictionary with a URL template tag parameter in django?
I need to pass an extra param to a url, but don't want to add it to the url pattern. Reading the django docs, I came across this, which is a bit like: urlpatterns = [ path('blog/<pk>/', views.year_archive, {'foo': 'bar'}), ] Sounds like what I need, but is there a way to set the value of 'bar' with a url tag, something like: data-url="{% url 'name_of_view' pk=obj.id foo=obj.bar %}" or... data-url="{% url 'name_of_view' obj.id obj.bar %}" or... ??? Also tried things like: path('blog/<pk>/', views.year_archive, {'foo': <bar>}), path('blog/<pk>/', views.year_archive, {'foo': self.bar}), #don't know why I think that would work Of course none of that works. I can pass 'obj.bar' through its own url pattern which is easy enough, but this breaks some other dependent code. Looking for another way, and the third option url dictionary seems promising if I can get it to work but so far can't set the value from the template. -
Getting error TemplateDoesNotExist at / when loading home page template - Django + Bulma, Sass
I'm a Django beginner and have been trying many solutions to this with no luck. Trying to use Sass to customize the Bulma framework in a Django site. I think it has something to do with my project directory structure and I've been messing with it so long there has to be something I'm not seeing. I'm sure I have multiple of some files that I don't need, but not sure what to get rid of and what to keep or move. Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.3 Python Version: 3.8.2 Installed Applications: ['serappis.apps.SerappisConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_simple_bulma', 'sass_processor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/templates/index.html (Source does not exist) * django.template.loaders.filesystem.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/molly/Documents/Dev Projects/SerapisDjango/serapissite/serappis/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/contrib/admin/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/contrib/auth/templates/index.html (Source does not exist) Traceback (most recent call last): File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/molly/.pyenv/versions/3.8.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, … -
How do I upload a django project to github?
THis is likely the dumbest question of all time on stack overflow... but I have spent close to an hour attempting this, with no luck, and am considering signing up to BitBucket. 1) Dragging and dropping into github, does not upload entire folder, but 5 out of about 30 .py files, and does not include any of the html, css etc... and does not keep any heirarchal structure as it only includes .py files 2) Command line: having git commit my folder, I try to git push origin and am met with this error: git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I have no idea what this means... -
how to manipulate data models in django and render on frontend?
i wanna manipulate this data on models.py ''' from django.db import models class Binary(models.Model): binNum = models.PositiveIntegerField() @property def binDec(self): bin = self.binNum decimal, i, n = 0, 0, 0 while(bin != 0): dec = bin % 10 decimal = decimal + dec * pow(2, i) bin = bin//10 i += 1 return decimal ''' im doing this and is rendering just the binNum ''' return ( {this.state.data.map(contact => { return ( <li key={contact.id}> {contact.binNum} {contact.binNum.binDec} </li> ); })} ''' i wanna render the binDec on the frontend -
SQLDecodeError at /admin/auth/user/
An sql decode error is raised whenever I filter the groups in the admin module. I have made no modification to the admin interface or models regarding users or groups, except for a few 1-1 relationships. The error is as is: FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "auth_user"."id" AS Col1, "auth_user"."password" AS Col2, "auth_user"."last_login" AS Col3, "auth_user"."is_superuser" AS Col4, "auth_user"."username" AS Col5, "auth_user"."first_name" AS Col6, "auth_user"."last_name" AS Col7, "auth_user"."email" AS Col8, "auth_user"."is_staff" AS Col9, "auth_user"."is_active" AS Col10, "auth_user"."date_joined" AS Col11 FROM "auth_user" INNER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") WHERE "auth_user_groups"."group_id" = %(0)s) subquery -
Password authenticated failed + Docker + Django
Not my first time using Docker but obviously I am doing something wrong with my setup that I can't figure out. Here's my docker-compose.yml version: "3.1" services: db: image: postgres:9.6.9-alpine environment: POSTGRES_USER: rentalapp POSTGRES_PASSWORD: rentalapp POSTGRES_DB: rentalapp ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata: And here's my local.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "USER": "rentalapp", "PASSWORD": "rentalapp", "PORT": 5432, "NAME": "rentalapp", "HOST": "localhost", "ATOMIC_REQUESTS": True, } } Traceback: django.db.utils.OperationalError: FATAL: password authentication failed for user "rentalapp" -
getting nginx to serve static files (django, gunicorn)
When DEBUG = True, Django serves the static files and I can see my site, and the admin page, styled correctly and run the correct js. My intuition is I have misconfigured nginx, and I'm struggling to find the cause. Some background: sudo nginx -t && sudo systemctl restart nginx nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful cat sites-enabled/mysite server { listen 80; server_name IP_ADDR; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/mysite; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } which is symlinked to sites-available/mysite /var/log/nginx/error.log only has the line 2020/03/01 19:57:49 [notice] 20644#20644: signal process started, but the access log has a number of 404s. Upon trying to access the application URL, chrome dev console shows: Refused to apply style from 'IP_ADDR:8000/static/css/console.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. IP_ADDR/:9 GET IP_ADDR:8000/static/js/jquery.min.js net::ERR_ABORTED 404 (Not Found) IP_ADDR/:11 GET IP_ADDR:8000/static/js/console.js net::ERR_ABORTED 404 (Not Found) IP_ADDR/:10 GET IP_ADDR:8000/static/js/content.js net::ERR_ABORTED 404 (Not Found) IP_ADDR/:11 GET IP_ADDR:8000/static/js/console.js net::ERR_ABORTED 404 (Not Found) favicon.ico:1 GET IP_ADDR:8000/static/favicon.ico 404 (Not Found) I have include /etc/nginx/mime.types; in my nginx.conf, and … -
Chicken and Egg nightmare with Django mixin
I am upgrading a large Django-based app from Django 1.7 app to Django 2.2 and am having a lot of trouble with a permissions-related mixin. class PrincipalRoleRelation(models.Model): """A role given to a principal (user or group). If a content object is given this is a local role, i.e. the principal has this role only for this content object. Otherwise it is a global role, i.e. the principal has this role generally. user A user instance. Either a user xor a group needs to be given. group A group instance. Either a user xor a group needs to be given. role The role which is given to the principal for content. content The content object which gets the local role (optional). """ ::: user = models.ForeignKey(User, verbose_name=_(u"User"), blank=True, null=True, on_delete=models.SET_NULL) group = models.ForeignKey(Group, verbose_name=_(u"Group"), blank=True, null=True, on_delete=models.SET_NULL) role = models.ForeignKey(Role, verbose_name=_(u"Role"), on_delete=models.CASCADE) ::: However, this fails to load during app initialization because User, Group, and Role etc are also apps whose loading is in progress and "populate() is not re-entrant" (so Dango complains) I tried to work round this by amending the above code to create a sort of "skeleton" class which does not attempt to reference any other apps, e.g. … -
how can I create a signup that generate a different username to access to rdp or debian ssh?
I already have the signup done, and working, but I want to generate rdp users or ssh debian based linked to their web app, but not directly linked.the labs username it will be store it to know which user lab will x username holds example test_webapp , test , pwd , creds_labs test_webapp@debian -
Javascript engine looking in the wrong place for the leaflet-groupedcontrol so it will not load
I have a leaflet-based map running against a Django python server with Leaflet as an installed app. Even though I have manually downloaded the leaflet-groupedcontrol and copied its css and js files into my Django 'static' directory, the javascript engine keeps looking in a 'src/static' directory that doesn't exist. So, if I try to use L.control.groupedLayers, I get an 'unable to load content' error. My content looks like this: <head> <!-- Required meta tags for Bootstrap --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% leaflet_js %} {% leaflet_css %} <title>Home</title> <style media= "screen" type="text/css"> #map { width:100%; height:650px;} .dropdowns_container { text-align: center;} .info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; } </style> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-legendcontrol/leaflet-legend.css' %}"/> <!-- Include the multiselect plugin's CSS and JS: --> <script type="text/javascript" src="{% static 'bootstrap-multiselect-master/dist/js/bootstrap-multiselect.js' %}"></script> <link rel="stylesheet" href="{% static 'bootstrap-multiselect-master/dist/css/bootstrap-multiselect.css' … -
How to implement django-summernote in my blog project?
https://djangocentral.com/integrating-summernote-in-django/ I followed every steps in the link but to no avail..any help pls??? -
Not cloning correct repository from Heroku
Thanks for any help you can provide! I'm trying to clone my repository for my django app using 'heroku git:clone -a targetapp', but the repository that is downloaded is not my app. Instead I receive a folder with an example app, btc_donations.png and a few other files. I'm logged into Heroku and set the correct app as the remote. My app could be downloaded yesterday, but no luck today... Thanks. -
Django - Using forms.CheckboxSelectMultiple
I'm trying to create a multi-select list of checkboxes for names in a database. I thought I could do the below in the from, and do some kind of loop in the template to render each name, but noting I try works. Is this the correct approach, any clues on how to render this in the template? Thanks from django import forms from .models import Player class PlayerForm(forms.Form): team = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=[Player.objects.all()] ) from django.db import models class Player(models.Model): lname = models.CharField(max_length=10, verbose_name='Last Name') fname = models.CharField(max_length=10, verbose_name='First Name') wins = models.SmallIntegerField(default=0, null=True, blank=True) loss = models.SmallIntegerField(default=0, null=True, blank=True) def __str__(self): return "{}".format(self.lname) class Meta: ordering = ['lname'] -
How to return error message in decorator in Django?
I wrote my own decorator, which checks if the currently logged in user is a teacher. If not, the decorator redirects the user to the login page, but for the user it is a bit confusing, so I want to pass a message why the user was redirected to the login page, but I have no idea how to do it. # here is my decorator: def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): ''' Decorator for views that checks that the logged in user is a teacher, redirects to the log-in page if necessary. ''' actual_decorator = user_passes_test( lambda u: u.is_active and u.is_teacher, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator