Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax is not sending data to django views
My Html --- <div class="form-group row pt-3 d-flex justify-content-center"> <div class="col-sm-10 d-flex justify-content-center"> <button id="submit_pic" style="width: 70%;" type="" class="btn btn-primary">Combine</button> <script> $("#submit_pic").submit(function (e) { e.preventDefault(); var csrfToken = $("input[name='csrfmiddlewaretoken']"); console.log(`Error ye raha === ${response_send}`) $.ajax({ url: "{% url 'make_combine' %}", //url: "/make_combine", type: "POST", //-------here is problem------- dataType: "json", cache: true, headers: {'csrfmiddlewaretoken': csrfToken.val()}, data: {"for_combine": response_send }, //"success": function (result) { // console.log(data); //}, }); return false; }); </script> </div> </div> django views.py -- import json def make_combine(request): combine_data7 = request.POST.get("for_combine") I have tried a lot of tricks available on internet as well as on StackOverflow, but still getting this error.It tells that combine_data7 is NoneType ---- AttributeError at /make_combine 'NoneType' object has no attribute 'split' -
Save user data in UserProfile with Middleware and GeoIP
I have a small question to ask you. I use GEO IP to locate my users and I would like to record this information every time user log in to improve the user experience of the app. The problem is that it doesn't save absolutely nothing at each connection. UserProfile models is empty... Anyone has an idea about this? user/middleware.py from .models import UserProfile from django.contrib.gis.geoip2 import GeoIP2 from django.utils.deprecation import MiddlewareMixin class LastLoginInfo(MiddlewareMixin): def geolocalisation(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') device_type = "" browser_type = "" browser_version = "" os_type = "" os_version = "" if request.user_agent.is_mobile: device_type = "Mobile" if request.user_agent.is_tablet: device_type = "Tablet" if request.user_agent.is_pc: device_type = "PC" browser_type = request.user_agent.browser.family browser_version = request.user_agent.browser.version_string os_type = request.user_agent.os.family os_version = request.user_agent.os.version_string g = GeoIP2() location = g.city(ip) location_country = location["country_name"] location_city = location["city"] if request.user.is_authenticated(): UserProfile.objects.filter(user=request.user).update(ip_address_ua=ip, device_ua=device_type, browser_ua=browser_type, os_device_ua=os_version, city_ua=location_city, country_ua=location_country) main/settings.py MIDDLEWARE = [ ... 'user.middleware.LastLoginInfo', ... ] -
I want to create a College Management System [closed]
I am working on a College Management System in Django. Now my questions is how to groups users in the semester wise. and also how to promote it into next semester ? Like For example, if user signup they directly assigned to semester 1 and view the semester 1 data ? Anyone know how to do this in Django? -
Why does getting Django's CSRF token from a cookie fail on mobile Chrome browser?
I have a web application built in Django that uses React components. The application currently has been tested and works on desktop Google Chrome, Microsoft Edge, mobile Firefox and mobile Brave browsers. Unfortunately, it produces errors on Google Chrome on mobile. The React components do not seem to recognize that there is a user logged in. The CSRF token is transferred from Django to the React components using a cookie (similarly to the process suggested at: https://django.readthedocs.io/en/stable/ref/csrf.html). // Set what happens when the database is called by React // Define how to get a cookie (such as a CSRF token) export function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // Define generically what happens when the database is called by React export function backendLookup(method, endpoint, callback, data) { // Convert the data being sent to the database to JSON form let jsonData; if … -
Django + HTML highlight text in textarea on offset and lengths
Having a dictionary like this in my view, I need help in finding out how Insert the correction string directly after the error word Highlight the error strings red and the correction strings green. {'content': [{'offset': 6, 'length': 2, 'error': 'go', 'correction': 'goes'}, {'offset': 22, 'length': 8, 'error': 'everyday', 'correction': 'every day'}, {'offset': 58, 'length': 8, 'error': 'everyday', 'correction': 'every day'}, {'offset': 78, 'length': 9, 'error': 'favourite', 'correction': 'favorite'}, {'offset': 98, 'length': 2, 'error': 'Me', 'correction': 'I'}, {'offset': 173, 'length': 8, 'error': 'wensdays', 'correction': 'wens days'}]} Take the picture below as an example Example visuals -
Send data in Angular to backend Django for sending email
I have contact form in Angular which use httpclient for Post method to django which is sending email with all data information from Angular to my email adress. In PostMan everythink work fine. What is mean "10" and "14" after response 200? I got in console: Dave dave@gmail.com hi how are you?. [25/Oct/2020 12:10:47] "POST /send_email/ HTTP/1.1" 200 10 but when I try in my angular I got: None None None [25/Oct/2020 12:14:11] "POST /send_email/ HTTP/1.1" 200 14 So if PostMan works fine, the problem is somewhere in Angular, but I don't know what is wrong. django def: @csrf_exempt def send_email(request): name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') print(name, email, message) try: send_mail(f'{name} wysłał wiadomość z Zakuro', f'adres: {email}/// wiadomość: {message}', 'email@gmail.com', ['secondemail@gmail.com'], fail_silently=False) send_mail('Thanks for contact with Zakuro', 'Hi. I will response as soon as possible.', 'email@gmail.com', [f'{email}'], fail_silently=False) return HttpResponse('email sent') except: return HttpResponse('email not sent') angular component: import { Component, OnInit } from '@angular/core'; import { CookieService } from 'ngx-cookie-service'; import { Router } from '@angular/router'; import { ApiService } from '../api.service'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.sass'] }) export class ContactComponent implements OnInit { constructor( private cookieService: CookieService, private router: Router, private apiService: … -
Django messages not showing in template
stuck with messages don't show up cant figure whats wrong with my code def studentreg(request): if request.method == 'POST': form = StudentRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Student has been created! You can view in the list!') return redirect('dashboard') else: form = StudentRegisterForm() return render(request, 'studentregister.html', {'form': form}) In the base template {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} When i save the student it doesn't show the message but when i view page source on chrome the message is there .help please. </head> <div class="alert alert-success"> Student has been created! You can view in the list! </div> <body> -
How to get multiple columns from different tables in Django and that result should be downloaded to Excel format
Please help me. views.py Error: I'm getting empty excel file. -
Why are the error reporting emails not being sent (Django)?
Python version: 3.6.3 Django version: 3.0.8 I am trying to use enable Django's error reporting via email, but nothing seems to happen when I encounter a 500 error. Here is a copy of my settings file with some comments and sensitive information removed: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '' # The actual value has been omitted DEBUG = False ADMINS = [('', '')] # Omitted. The same email address is used for EMAIL_HOST_USER and SERVER_EMAIL MANAGERS = ADMINS ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]'] # ALLOWED_HOSTS = [] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = '' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PSSWORD = '' # Omitted SERVER_EMAIL = '' """ LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } """ INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'main.apps.MainConfig', 'register.apps.RegisterConfig' ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': … -
No module named django_river
I have an issue when running pip install -r requirements.txt and got no module named django_river. I tried installing the package pip install django_river but it gives error, package does not exist. Thanks -
Access forbidden to Django resource when accessing through Node.js frontend
I cloned a Django+Node.js open-source project, the goal of which is to upload and annotate text documents, and save the annotations in a Postgres db. This project has stack files for docker-compose, both for Django dev and production setups. Both these stack files work completely fine out of the box, with a Postgres database. Now I would like to upload this project to Google Cloud - as my first ever containerized application. As a first step, I simply want to move the persistent storage to Cloud SQL instead of the included Postgres image in the stack file. My stack-file (Django dev) looks as follows version: "3.7" services: backend: image: python:3.6 volumes: - .:/src - venv:/src/venv command: ["/src/app/tools/dev-django.sh", "0.0.0.0:8000"] environment: ADMIN_USERNAME: "admin" ADMIN_PASSWORD: "${DJANGO_ADMIN_PASSWORD}" ADMIN_EMAIL: "admin@example.com" # DATABASE_URL: "postgres://doccano:doccano@postgres:5432/doccano?sslmode=disable" DATABASE_URL: "postgres://${CLOUDSQL_USER}:${CLOUDSQL_PASSWORD}@sql_proxy:5432/postgres?sslmode=disable" ALLOW_SIGNUP: "False" DEBUG: "True" ports: - 8000:8000 depends_on: - sql_proxy networks: - network-overall frontend: image: node:13.7.0 command: ["/src/frontend/dev-nuxt.sh"] volumes: - .:/src - node_modules:/src/frontend/node_modules ports: - 3000:3000 depends_on: - backend networks: - network-overall sql_proxy: image: gcr.io/cloudsql-docker/gce-proxy:1.16 command: - "/cloud_sql_proxy" - "-dir=/cloudsql" - "-instances=${CLOUDSQL_CONNECTION_NAME}=tcp:0.0.0.0:5432" - "-credential_file=/root/keys/keyfile.json" volumes: - ${GCP_KEY_PATH}:/root/keys/keyfile.json:ro - cloudsql:/cloudsql networks: - network-overall volumes: node_modules: venv: cloudsql: networks: network-overall: I have a bunch of models, e.g. project in the Django backend, … -
Django, Ajax: creating comment in homepage from Listview
im trying to build comment section with ability to post new one below every post (like on Instagram or Facebook). At the moment I can like post, show or hide comment section with form below particular post but I cannot post comment, I don't know how to do this. I generate posts with ListView. I have separated view for comments with form. When i try to post comment console gives me jquery-3.5.1.min.js:2 POST http://127.0.0.1:8000/ 405 (Method Not Allowed) How to generate form like this? Below what I tried: views.py class PostListView(ListView): model = Post template_name = 'posts/homepage.html' def get_queryset(self): profiles = Follow.objects.filter(follow_by=self.request.user.profile).values_list('follow_to', flat=True) posts = Post.objects.filter(author_id__in=profiles).order_by('-date_of_create') return posts def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['form'] = CommentForm return context def post_comments(request, pk): post = Post.objects.get(pk=pk) profile = request.user.profile if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = profile comment.post = post comment.save() data = { 'content': form.cleaned_data['content'] } return HttpResponse(json.dumps(data)) form = CommentForm() context = { 'post': post, 'form': form, } return render(request, 'posts/comments.html', context=context) homepage.html {% block content %} {% for post in object_list %} <a href="{% url 'detail_post' post.id %}"><img src="{{ post.picture.url }}" alt="" class="img-thumbnail" style="width:200px; height: 200px;"></a> <h4>{{ post.description_hashtags|safe }}</h4> <small><a … -
ImproperlyConfigured: The SECRET_KEY sett ing must not be empty
I am forking a free Django project on git. The files have no Secret_Key- as you can appreciate. It has a env folder with files and env.md. The env.md request to enter all the Values: Kindly add below environment variables to your local development with appropriate key/value accordingly. Common keys DEBUG=True #false SECRET_KEY="(I have entered here, a python random generated 50 character as the Secret_key)" HTML_MINIFY=True/False ENV_TYPE="DEV" or "PROD" File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/init.py", line 401, in execute_from_command_line utility.execute() File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/base.py", line 371, in execute output = self.handle(*args, **options) File "/opt/miniconda3/lib/python3.7/site-packages/django/core/ management/commands/runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/opt/miniconda3/lib/python3.7/site-packages/django/conf/ init.py", line 83, in getattr self._setup(name) File "/opt/miniconda3/lib/python3.7/site-packages/django/conf/ init.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/opt/miniconda3/lib/python3.7/site-packages/django/conf/ init.py", line 196, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY sett ing must not be empty. I have created a ´random python´ Secret_key as I expect you don't leave your Secret:_key , debug and Database on the git. what i´ve done_: I found the env.md and entered … -
Django variable form
I'm trying to make a checkout form using Django where customer has to fill out the delivery address and choose date time. I want the choices in shippingDate to changed based on shippingAddress1, shippingCity. What could be the ways to implement it?. Here is the address form: class DeliveryForm(forms.Form): def __init__(self,date_list,*args,**kwargs): # call standard __init__ super().__init__(*args,**kwargs) #extend __init__ self.fields['shippingDate'] = forms.ChoiceField(choices=tuple([(date, f"{date.strftime('%d')} {months[date.strftime('%m')]}") for date in date_list]), required=True) shippingAddress1 = forms.CharField(max_length=250, help_text='ул. Бассейная 10',required=True, label='Адрес') shippingFlat = forms.CharField(max_length=250, help_text='кв.10', required=False, label='Квартира') shippingCity = forms.CharField(max_length=250, help_text='Киев',required=True, label='Город') shippingPostcode = forms.CharField(max_length=250, help_text='01011',required=True, label='Почтовый индекс') shippingDate = forms.DateField() Here is HTML code for the form (if needed): <div class="container my-auto pb-5 px-5"> {% if not form.is_valid %} <div class="row mt-5"> <div class="col-12 col-md-10 offset-md-1 col-xl-8 offset-xl-2 text-center"> <div class="text-center " > <h3 class="product_title">Доставка</h3> </div> <hr> <form id='deliveryForm'> {% csrf_token %} <p id="failure_message" style="color: red;">{{failure_message}}</p> <div class="container-fluid"> <div class="row"> <div class="col-9 form-group"> <div class="input-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span> </div> {% render_field form.shippingAddress1 class+="form-control" placeholder='*Адрес (Бассейная 10)' %} </div> </div> </div> <div class="col-3 form-group"> <div class="input-group"> <div class="input-group"> {% render_field form.shippingFlat class+="form-control" placeholder='кв.' %} </div> </div> </div> </div> <div class="row"> <div class="col-8 form-group"> <div class="input-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i … -
How can i migrate after restore database backup in django?
There is a backup database of postgresql,after i restored this database.i create model in on of app in Django project then i run makemigrations ..new table create in 0001 file in migrations beside app..but after run migrate new table do not create! -
Putting two different variables from two different models at the same line in Django templates
I need to get a Django Template like "First Blog Heading" ("number of Comments of first blog") "Second Blog Heading" ("number of Comments of second blog") What's the easiest way to do this? I tried to create a context in my views.py having both from Blog model and Comment model and put Since variables belong to different models. And then I needed to put both variables into for loop in my html but it turn out a nested loop. So I didn’t get the look I want. I open to every kind of solution not from back-end but also front-end Thank you {% for blog in blogs %} {% for comment in comments %} {{blog.name }} {{comment.number }} {% endfor %} {% endfor %} -
After nsq.run() my python script is not executing block of code in "pynsq" package
enter image description hereI am trying to use "pynsq" package (message broker service) to my django project. but when i run the Asynchronous consumer request using nsq.Reader() class by using nsq.run() command it takes my main thread and my code after this command is not executing . for eg:- as shown in the picture after nsq.run() i am trying to print("hello") but the print function is not calling when i run this .py script .i have tried my best to find solution for this. is it possible to use this package in my django project ? becauese when i run this script after nsq.run() my code of block is not executing. please can anyone suggest me the solution for this to use this package in my django project. -
Celery beat task received but doesn't invoke
I'm trying run beat tasks. But only one task executes. So, there is my project's structure: trading_platform: trading_platform: celery.py settings.py offers: tasks.py manage.py celery.py: import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trading_platform.settings') app = Celery('trading_platform') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, debug_task.s('HELLO'), name='add every 10') @app.task def debug_task(self): print(self) settings.py: # Celery Configuration Options CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'redis://redis:6379/0') CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'redis://redis:6379/0') # CELERY_ACCEPT_CONTENT = os.environ.get('CELERY_ACCEPT_CONTENT', 'application/json') CELERY_RESULT_SERIALIZER = os.environ.get('CELERY_RESULT_SERIALIZER', 'json') CELERY_TASK_SERIALIZER = os.environ.get('CELERY_TASK_SERIALIZER', 'json') CELERY_STORE_ERRORS_EVEN_IF_IGNORED = os.environ.get('CELERY_STORE_ERRORS_EVEN_IF_IGNORED', True) tasks.py: from trading_platform.celery import app @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, print_text.s('text'), name='add every 10 sec') @app.task(bind=True) def print_text(text): print(text) command to run: celery -A trading_platform worker -B -l info So, there is input: celery_1 | /usr/local/lib/python3.8/site-packages/celery/platforms.py:797: RuntimeWarning: You're running the worker with superuser privileges: this is celery_1 | absolutely not recommended! celery_1 | celery_1 | Please specify a different user using the --uid option. celery_1 | celery_1 | User information: uid=0 euid=0 gid=0 egid=0 celery_1 | celery_1 | warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( celery_1 | celery_1 | -------------- celery@953a7a853036 v5.0.1 (singularity) celery_1 | --- ***** ----- celery_1 | -- ******* ---- Linux-5.4.0-52-generic-x86_64-with-glibc2.2.5 2020-10-25 09:23:38 celery_1 | - *** --- * --- celery_1 | - ** ---------- [config] celery_1 … -
How can I call/refer to another property in the same models in django
I am creating a web app for creating a proposal/quotation for machines or equipment. I have a models for QuotationItem which has these properties: In my models.py: class QuotationItem(models.Model): product = models.Charfield(max_length=30) quantity = models.PositiveIntegerField(default=1) description = models.CharField(max_length=200, null=True) line_number = models.PositiveIntegerField() tagging = models.CharField(max_length=50) Now, I want the 2 properties (line_number and tagging) be connected. Example: line_number = 1, tagging = "Equipment - 1" line_number = 2, tagging = "Equipment - 2" In short, I want to set the tagging property with a default value of f"Equipment - {line_number}" How can this be done? I cannot seem to find this in documentation. Thank you -
How to print multiple object from table def __str__(self):return self.title
I created a article models below models.py class Article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) is_deleted = models.BooleanField(default=False) custom_id = models.UUIDField(blank=False,null=False, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, blank=False) text = models.TextField() created_on = models.DateTimeField("created on", auto_now_add=True) objects = models.Manager() def __str__(self): return self.title for print the title object I Used below lines def __str__(self): return self.title But I want to print the title object with user object.How will do? For Example Title Name -
Trying to display "RSS list" in django. However it gives a blank value on the page
I am completely newbee in django and trying to learn it. Values from list are not getting displayed. Code completely works in python Code in View.py from django.http import HttpResponse from django.shortcuts import render from .models import feed_entry import feedparser feedlist =['http://rss.cnn.com/rss/money_news_companies.rss','http://feeds.marketwatch.com/marketwatch/realtimeheadlines/','http://feeds.marketwatch.com/marketwatch/marketpulse/','https://www.cnbc.com/id/10001147/device/rss/rss.html'] serialnumber = 1 feeds = [] sortedfeed = [] for feedlisturl in feedlist: feeds.extend(feedparser.parse(feedlisturl).entries) for feed in feeds: article_title = feed.title article_link = feed.link article_published_at = feed.published # Unicode string article_published_at_parsed = feed.published_parsed # Time objectwhats content = feed.summary sortedfeed.append((article_title, article_link,article_published_at,article_published_at_parsed,content)) rssfeed = (sorted(sortedfeed, key=lambda sortedfeed: sortedfeed[3], reverse=True)) def feed(request): return render(request, 'index.html',{'feed_from':rssfeed}) - In index.html {% for feed_entry in rssfeed %} {{ feed_entry.1 }} {% endfor %} Question: When index.html renders it gives a blank page. Can anyone help, please -
python manage.py makemigrations : No changes detected
I am working on a project using django and i am using pycharm software. In my 'store' directory i have a python package called 'models' in which there are two python files :- init.py and product.py . The problem i am getting is that i cannot create table using the command even when i am importing the 'Product' class from product module in init.py file. Even both the modules are also in the same package. Here is the code of product.py file:- from django.db import models class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) description = models.CharField(max_length=200, default='') image = models.ImageField(upload_to='products/') And here is the code of init.py file:- from .product import Product But when i am running the command on terminal i am getting this error:- (venv) C:\Users\Admin\PycharmProjects\SMart>python manage.py makemigrations No changes detected -
Django: You don’t have permission to view or edit anything
I am trying to extend my normal navigation template in django admin but getting error as : You don’t have permission to view or edit anything. html file where I am trying to extend navigation template : {% extends 'base.html' %} {% block content %} {% include "admin/index.html" %} {{ block.super }} {% endblock content %} What I tried: I've added below codes in my project urls.py(didn't work): from django.contrib import admin admin.autodiscover() Replaced django.contrib.admin with django.contrib.admin.apps.SimpleAdminConfig and used(didn't work): from adminplus.sites import AdminSitePlus admin.site = AdminSitePlus() admin.autodiscover() My User Permissions: Can anyone help to to display full admin page with all access? -
Why isn't my website scrolling, but works well when resized?
hi guys i am new to programming and I'm trying to make a static webpage dynamic in Django and I've gotten the layout of the page okay, however the page wont seem to scroll.im guessing its a CSS or jQuery problem. i really would like some help on this. Link to my repository below. link to repo -
In Django, how can I unit test a modelformset_factory?
I wanted to have several instances of the same form, so I used a modelformset_factory. My model is as follows from django.db import models class Donation(models.Model): DONATE_CHOICES = [ ('aclu', 'American Civil Liberties Union'), ('blm', 'Black Lives Matter'), ('msf', 'Medecins Sans Frontieres (Doctors Without Borders)') ] charity = models.CharField( max_length=4, choices=DONATE_CHOICES, default='aclu' ) money_given = models.IntegerField(default=0) And my view: from django.shortcuts import render from django.http import HttpResponseRedirect from django.forms import modelformset_factory from .models import Donation def donate(request): donateformset = modelformset_factory(Donation, fields='__all__', extra=3) form = donateformset(queryset=Donation.objects.none()) if request.method == 'POST': form = donateformset(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('..') context = {'form': form} return render(request, 'Micro_Donations/donate.html', context)