Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django killed suddenly after runserver on M1
I have couple of project on Django and after hi runserver terminal shows : [1] 23857 killed python3 manage.py runserver I had update all library for working on Apple M1 and everything was good. after couple of day I tried to run and everything is crushed. my requirments.txt is : boto3==1.15.6 botocore==1.18.6 Django==3.1.1 django-cors-headers==3.5.0 django-debug-toolbar==3.1.1 django-storages==1.10.1 django-summernote==0.8.11.6 docutils==0.16 gunicorn==20.0.4 jmespath==0.10.0 Pillow==8.1.0 pipupgrade==1.7.4 psycopg2-binary==2.8.6 python-dateutil==2.8.1 pytz==2020.1 s3transfer==0.3.3 six==1.15.0 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 python3 version is 3.9.1 and when I run the code in PyCharm shows: /Users/username/python/myProject/.venv/bin/python3.9 /Users/username/python/myProject/myApp/manage.py runserver 8000 Process finished with exit code 137 (interrupted by signal 9: SIGKILL) I read maybe the problem of SIGKILL is about memory but half of my ram is free ~5GIG used 3GIG free -
Django returns NoReverseMatch instead of Updating the div with Ajax
Description I am creating a like button for a comment that was made on a post. When the user clicks on the like button, Django gives a NoReverseMatch and the page doesn't update automatically. After I refresh the page, it shows that the like was updated in the database, despite the NoReverseMatch error. What I tried? Initially, the issue was with the csrf_tokens. So, I added the csrf_exempt decorator, so it is definitely not the issue. I played a lot with the urls, and tried adding the comment id to the parameter, but it doesn't seem to help. Question How can I resolve the NoReverseMatch error and make it so that AJAX automatically changes the button from like to dislike. urls.py path('post/<int:pk>/like-comment', like_comment, name="like_comment") view.py @csrf_exempt def like_comment(request, pk): comment = get_object_or_404(Comment, id=request.POST.get('id')) liked = False if comment.likes.filter(id=request.user.id).exists(): comment.likes.remove(request.user) liked = False else: comment.likes.add(request.user) liked = True context = { 'comment': comment, 'is_liked': liked, 'total_likes': comment.likes.count() } if request.is_ajax(): html = render_to_string('blog/like_section_comment.html', context, request=request) return JsonResponse({'form': html}) main.js $(document).ready(function(event){ $(document).on('click', '#like-comment', function(event){ event.preventDefault(); var pk1 = $(this).attr('value'); // comment id var pk = $(this).attr('data-value'); // post id $.ajax({ type: 'POST', url: "like-comment", data: {'id': pk1, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: … -
duplicate key value violates unique constraint "photo_photo_user_id_key" DETAIL: Key (user_id)=(102) already exists
I receive the error above whenever users want to change their already existing profile. This is the views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db import transaction from .models import Photo from .forms import PhotoForm Create your views here. @login_required @transaction.atomic def upload(request, pk=None): instance = Photo.objects.get(pk=pk) if pk else None context = dict(save_pk=pk or "") if request.method == 'POST': # Only backend upload should be posting here context['backend_form'] = form = PhotoForm(request.POST, request.FILES, instance=instance) if form.is_valid(): # Uploads image and creates a model instance for it context['posted'] = form.save(commit=False) context['posted'].user = request.user context['posted'].save() instance = Photo.objects.get(pk=pk) if pk else None else: # Form demonstrating backend upload context['backend_form'] = PhotoForm(instance=instance) return render(request, 'photo/upload.html', context) from the stack trace, the problem is coming from this line context['posted'].save() How do I go about it? I want the users to be able to change their profiles without trying to create a new instance afresh. This is the HTML template <main class="mt-5 pt-5 container"> <!--A standard form for sending the image data to your server --> <div class="mt-5 pt-5 container bg-white"> <h3 class="text-center">Upload</h3> <div class="mb-3"> <div class="mb-auto p-2 bd-highlight"> <form action="{% url 'upload' %}" method="post" enctype="multipart/form-data" class="text-center mt-5 "> {% csrf_token … -
How to push single file in git
I want to push a single or few files to my website in git. I do it everytime by following way - git add (file) git commit -am "make it better" git push heroku master The problem is that git push heroku master also changes other things on my website by replacing it with old one, for example - "replacing admin objects with old one which is in django server". Is there any way to push it for only single file ? -
Celery is not loading tasks from one app out of five
I'm using autodiscover in my celery.py file for gathering tasks. Which up until a recently picked all of the app.tasks.py up, I'm not sure why but my config.tasks.py function are no longer being picked up, but all the other apps are. If I from "config.tasks import *" there are no errors and I can run the tasks manually through shell. ive tried using force=True on autodiscover which had no effect, and a number of other solutions, none of which seem to have any effect, does anyone have any ideas on what to check next? Thanks Structure: -config --apps.py --views.py --models.py --tasks.py -monitoring --apps.py --views.py --models.py --tasks.py -app --apps.py --settings.py --celery.py celery config from __future__ import absolute_import, unicode_literals import os, django from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') django.setup() # This is key app = Celery("app") app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() if __name__ == '__main__': app.start() settings.py CELERY_TIMEZONE = 'Europe/London' ENABLE_UTC = True CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_TIME_LIMIT = 540 INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'haystack', 'django_tables2', 'django_filters', 'django_celery_beat', 'config.apps.ConfigConfig', 'monitoring.apps.MonitoringConfig', 'storages', 'stdimage', 'simple_history', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', ) tasks.py from __future__ import absolute_import, unicode_literals … -
Faster query than distinct in django
I am using Django and PostgreSQL, and I have query like below model.objects.filter(field=str(field)).exclude(tr__in=['some','some1']).distinct( 'field1','field2') In my model, I have 1 milion rows. The query above is so slow (It takes around 5-6 secs to fetch). I need alternative and faster way to implement it. Any ideas how to do? -
UnicodeDecodeError while loading .sav file
Trying to open .sav file in views.py using pickle. But throws me an error. Views.py : def result_india(request): model = pickle.load(open('finalmodel.sav', 'rb'), encoding='latin1') ans = model.piechart() return render(request, 'result_india.html', {'ans': ans}) Urls.py : urlpatterns = [ path('admin/', admin.site.urls), path('',views.home ), path('result_india/', views.result_india, name = 'result_india') ] Also, I have a function in my original py file that I have tried accessing in my views.py. Function : def piechart(): vaccines = ['Pfizer', 'Moderna', 'Oxford/AstraZeneca', 'CNBG', 'Covaxin', 'Sinopharm', 'Sinovac', 'Sputnik V'] data = [sum_pfizer, sum_moderna, sum_oxford, sum_cnbg, sum_covaxin, sum_sinopharm, sum_sinovac, sum_sputnik] fig = plt.figure(figsize=(8, 8)) plt.pie(data, labels=vaccines, rotatelabels=90) piechart = plt.show() return piechart piechart() Full error : UnicodeDecodeError at /result_india/ 'utf-8' codec can't decode byte 0x81 in position 5: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/result_india/ Django Version: 3.1.5 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0x81 in position 5: invalid start byte Unicode error hint The string that could not be encoded/decoded was: ffff4�@ -
Form field defined in View does not appear in the returned `cleaned_data` dictionary
I am working on a reports page for a django app. This particular app (not written by me) has a reports page, where all report links appear with their forms. That is, if there is an updates timeline report page, it will appear here together with all of its form fields (time granularity, include security updates, etc) and a button that will take you to the updates timeline page to view the results (or chose different values). All other report links appear in this general page as well. Now to my problem: I want some specific, not required form fields to not appear in the general reports page, but instead only when the user accesses the actual report page. That is because they are ModelChoiceFields with thousands of entries, that slow down the rendering of the general reports page (there are many forms for different pages there, so it adds up). The way I do that is the following: I declare the fields as forms.HiddenInput in forms.py, and then inside my view, in the form_valid() function, I redefine the fields as ModelChoiceField. That way, the fields appear only when the user has submitted their first form (the one from the … -
How to save the choices in the save() in the model
I want to be able to save and retrieve the Choices , but depending on a certain value in the fields. For example, this is my model : class Business(TimeStampedModel): business_id = models.CharField( 'Business ID', max_length=64, unique=True, null=True, blank=True) legal_form = models.CharField( _('Legal form'), max_length=16, choices=LEGAL_CHOICES, blank=True) accordance = models.CharField( 'accordance', max_length=16, blank=True) def save(): radio_buttons = RADIO_BUTTON_SELECTIONS values = radio_buttons.get(self.legal_form) # What can I do here to ensure that wherever self.legal_form is different I save the value or I get the value saved Then my constants are as below : LEGAL_CHOICES = ( ('gbr', _('BGB-Society (GbR)')), ('ohg', _('Offene Handelsgesellschaft ')), ) RADIO_BUTTON_SELECTIONS = { 'gbr': (('yes', _('Yes')),), 'ohg': (('yes', _('YES')), ('no', _('NO'))), } As you can see the fields , I want to be able to change the Choices depending on the legal_form value, how can I do this in the save() method, or whats the best practice to achieve this ? -
Django 3: how to serve static images whose path is defined by a model attribute?
I'm trying to use images in Django 3 Debug mode as follows: on the admin side, get a list of the images contained in projects/static/img/ directory in the editing forms; on the front-end side, display the actual image of the class instance. Here's my code: settings.py STATIC_URL = '/static/' projects/models.py from django.db import models class Project(models.Model): img = models.FilePathField(path = 'img/') Images are located in the projects/static/img/ directory. When I create a new class instance with python manage.py shell: from projects.models import Project t = Project(img = 'img/test.jpg') t.save() The image gets displayed correctly on the front-end side. The problem is, I can't access the forms on the admin side. I get: FileNotFoundError at /admin/projects/project/add/ [Errno 2] No such file or directory: 'img/' I also tried python manage.py collectstatic that copies the projects/static/img/ folder into /static/img/ but nothings works, the admin side still gets the same error. Any suggestion on how to solve this? -
Pass from A app's model to B app's model in django
i have some questions! I'm making a post model, and I want to put the user created in the account model into the author object, but I do not know how to do it. This is my code account/models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, nickname, password=None): if not email: raise ValueError("이메일이 필요합니다.") email = self.normalize_email(email) user = self.model(email=email, nickname=nickname) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) nickname = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["nickname"] def get_nickname(self): return self.nickname def __str__(self): return self.email post/models.py: from django.db import models # from accounts.models import UserAccount class Post(models.Model): # author = UserAccount.nickname.get(user=request.user) # i think this is wrong answer title = models.TextField(blank=True, null=True) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) location = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.post any hint would be appreciated :) -
How to find out the type of field in mongoengine
I've been using blinker library to write signals in mongoengine. Where before writing the data to model I'm trying to pre-process the data on certain fieldType. How can I check the type of document field in mongoengine. @classmethod def pre_save(cls, sender, document, **kwargs): """ Pre Save signal """ fields = document._fields # If field is of TextField pre-process the data -
NGINX 502 upstream prematurely closed connection while reading response header from upstream
This is my configuration. I am getting 502 Bad Gateway with upstream prematurely closed connection while reading response header from upstream, client error. I have set client_max_body_size 0; and now I get 502 instead of 413. I have also checked the gunicorn configuration (increase the timeout), but it still does not work nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 500; types_hash_max_size 2048; # server_tokens off; client_max_body_size 0; fastcgi_read_timeout 900; proxy_read_timeout 900; # fastcgi_buffers 8 16M; # fastcgi_buffer_size 32k; # fastcgi_connect_timeout 90s; # fastcgi_send_timeout 90s; # fastcgi_read_timeout 90s; # proxy_read_timeout 90s; # server_names_hash_bucket_size 64; # server_name_in_redirect off; } vps.conf server { listen 8090; server_name dev.apps.gdceur.eecloud.dynamic.nsn-net.net; client_max_body_size 0; #location = /favicon.ico { access_log off; log_not_found off; } #location /static/ { # root /home/sammy/myproject; #} location / { include proxy_params; # proxy_read_timeout 300s; # proxy_connect_timeout 750s; proxy_read_timeout 1800; proxy_connect_timeout 1800; proxy_send_timeout 1800; send_timeout 1800; proxy_pass http://unix:/srv/app/djsr/djsr.sock; } } This is the latest error I am getting: upstream prematurely closed connection while reading response header from upstream, client: -
How to pass Sportsipy Python sports API through Django template
I have been trying to work with this Python sports data api, Sportsipy. It’s pretty simple to set up and I can print the dictionaries to the terminal but when I go to pass it through my Django template it says the object is not iterable. When I print the type() it just says the class name is sportsipy.ncaab.boxscore.Boxscores. I have tried converting it to json and a million different things to get it to work but it just wont happen. Im not sure how it is formatted or what the story with it is.screenshot of one of the endpoints in API docs -
Django-storages(or boto) and S3 bucket keep repeating head bucket operation and hangs 6-7 seconds
I use DRF for my API development. I have used this package for other 2 projects and had no problem. But this time I'm having trouble during s3 bucket head_object operation. The DEBUG message is follows, and I have no idea what went wrong. ... django | DEBUG 2021-02-09 22:06:43,065 factory 15 140241970775872 Loading s3:Object django | DEBUG 2021-02-09 22:06:43,068 action 15 140241970775872 Calling s3:head_object with {'Bucket': 'staging-2021020303212639920000000b', 'Key': 'media/images/users/profiles/profile_rVvDZa9Mk28f58ch2AXuNt.jpeg'} django | DEBUG 2021-02-09 22:06:43,084 retryhandler 15 140241970775872 No retry needed. django | DEBUG 2021-02-09 22:06:43,084 action 15 140241970775872 Response: {'ResponseMetadata': {'RequestId': '23A9B0689BB283FF', 'HostId': '1uaejTch2UdsR2NKw7uilynovbr0QPnefeg4HwMFmJdhBf1SK2SdwApkmEy1BteoVGR4I56ige0=', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': '1uaejTch2UdsR2NKw7uilynovbr0QPnefeg4HwMFmJdhBf1SK2SdwApkmEy1BteoVGR4I56ige0=', 'x-amz-request-id': '23A9B0689BB283FF', 'date': 'Tue, 09 Feb 2021 13:06:44 GMT', 'last-modified': 'Tue, 09 Feb 2021 12:28:36 GMT', 'etag': '"12aa400f79e5172a4ca388bce267e895"', 'x-amz-version-id': 'axFjXeb12wKkL8M.18OsAiyRx_1MneIn', 'accept-ranges': 'bytes', 'content-type': 'image/jpeg', 'content-length': '174111', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'AcceptRanges': 'bytes', 'LastModified': datetime.datetime(2021, 2, 9, 12, 28, 36, tzinfo=tzutc()), 'ContentLength': 174111, 'ETag': '"12aa400f79e5172a4ca388bce267e895"', 'VersionId': 'axFjXeb12wKkL8M.18OsAiyRx_1MneIn', 'ContentType': 'image/jpeg', 'Metadata': {}} django | DEBUG 2021-02-09 22:06:43,086 utils 15 140241970775872 Acquiring 0 django | DEBUG 2021-02-09 22:06:43,087 tasks 15 140241836529408 DownloadSubmissionTask(transfer_id=0, {'transfer_future': <s3transfer.futures.TransferFuture object at 0x7f8c9341a490>}) about to wait for the following futures [] django | DEBUG 2021-02-09 22:06:43,087 tasks 15 140241836529408 DownloadSubmissionTask(transfer_id=0, {'transfer_future': <s3transfer.futures.TransferFuture object at 0x7f8c9341a490>}) done waiting for dependent … -
uploading an image ml model to flask app but getting error
this is a flask application , i load the model and then read the file and then try to predict but facing this error , below is the code: import os import numpy as np from flask import Flask from flask import request import cv2 import imutils from flask import render_template import pickle app = Flask(__name__) import tensorflow as tf from keras.preprocessing.image import load_img from keras.models import Sequential, load_model from keras_preprocessing.image import ImageDataGenerator ,load_img,img_to_array classifier = tf.keras.models.load_model("ourModel.h5") UPLOAD_FOLDER = "./static" ALLOWED_EXTENSIONS = {'jpg','jpeg'} def allowed_files(file): return '.' in file and file.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS def predict(file): images = cv2.imread(file) images = imutils.resize(images,width=320) gray = cv2.cvtColor(images,cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) blackhat = cv2.morphologyEx(gray,cv2.MORPH_BLACKHAT,kernel) _,thresh = cv2.threshold(blackhat,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU) thresh = cv2.dilate(thresh,None) (cnts,_) = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) avgcntarea = np.mean([cv2.contourArea(k) for k in cnts]) digits = [] boxes = [] for (i,c) in enumerate(cnts): if cv2.contourArea(c)<avgcntarea/10: continue mask = np.zeros(gray.shape,dtype="uint8") (x,y,w,h) = cv2.boundingRect(c) hull = cv2.convexHull(c) cv2.drawContours(mask,[hull],-1,255,-1) mask = cv2.bitwise_and(thresh,thresh,mask=mask) digit = mask[y-8:y+h+8,x-8:x+w+8] digit = cv2.resize(digit,(28,28)) boxes.append((x,y,w,h)) digits.append(digit) lists = [] digits = np.array(digits) digits = digits.reshape(digits.shape[0],28,28,1) labels = classifier.predict_classes(digits) for (x,y,w,h),label in sorted(zip(boxes,labels)): cv2.rectangle(images,(x,y),(x+w,y+h),(0,0,255),1) cv2.putText(images,str(label),(x+2,y-5),cv2.FONT_HERSHEY_SIMPLEX,1.0,(0,255,0),2) lists.append(label) return lists @app.route("/",methods=["GET","POST"]) def upload_predict(): if request.method == "POST": image_file = request.files["image"] # if file is empty filename = image_file.filename if … -
Handling Long response in django App. Avoid 502 bad gateway error
Short description I have small E-mail scraping django App. App gets 'xlsx' file contains URLs to parse, from user and scrap the emails. During the scraping process csv files saved on local storage and can be downloaded any time using a separate button on html. The problem is, it takes many hours to complete the process and html front-end cannot wait for that long and give me error 502 bad gateway. my view.py file #view.py from django.shortcuts import render # from tp_scraper.models import Document from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.files.storage import default_storage from django.http import HttpResponse import os from tp_scraper.code.main_scraper import scraper_py,test_zip #from email_scraper.tp_scraper.code.main_scraper import scraper_py import csv # Create your views here. # def main_page(request): # return render(request,'page1.html',{}) def show_db(reqeust): context={} return render(reqeust,'page1.html',context) def scraper_main(reqeust): if reqeust.method == 'POST' and reqeust.FILES['myfile']: myfile = reqeust.FILES['myfile'] fs = FileSystemStorage() filename = fs.save('file_1.xlsx', myfile) uploaded_file_url = fs.url(filename) return render(reqeust, 'em_scrap.html', { 'uploaded_file_url': uploaded_file_url }) return render(reqeust, 'em_scrap.html') def output(request): res=scraper_py() #This is email scraping code does the scraping jon and take long time. msg='mesage' return render(request,'em_scrap.html',{'msg':msg}) def download_zip(request): res = test_zip() return (res) def how_to(reqeust): context={} return render(reqeust,'Howto.html',context) My URL file.py #urls.py from django.urls import path from tp_scraper … -
Access choices in serializer with a CharField
I have a CharField , which is empty, but I have added a method inside the models to get for me the choices, how can I attach the choices in the serializer field ? Below is my model : class Business(TimeStampedModel): business_id = models.CharField( 'Business ID', max_length=64, unique=True, null=True, blank=True) accordance = models.CharField( 'accordance', max_length=16, blank=True) def update_accordance(self): """ Update accordance field to return choices. """ radio_buttons = RADIO_BUTTON_SELECTIONS values = radio_buttons.get(self.legal_form) return values update_accordance, Just helps me to get the choices in this format : (('yes', _('YES')), ('no', _('NO'))) Then in my serializer : class BusinessDetailedSerializer(serializers.ModelSerializer): """Serializer for complete Business form""" accordance = serializers.CharField(source='update_accordance') class Meta: model = Business fields = '__all__' -
Django Queryset filter for ForeignKey elements
I have a problem with building a custom queryset inside one of my views. Here is a simplified version of my models. The idea is that I want to track the price of different products in different shops. A shop can have multiple products and a product can be present in multiple shops. Products can have set an is_special flag to highlight them. The following structure was choosen because it easily allows adding new products and shops later on: class Product(models.Model): product_id = models.CharField(max_length=255, primary_key=True) is_special = models.BooleanField(default=False) product_name = models.CharField(max_length=255, default='', blank=False, null=False) class ShopProductPrice(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) shop = models.ForeignKey("Shop", on_delete=models.CASCADE, related_name="shop_entry") price = models.FloatField(default=0.0, null=False) class Shop(models.Model): name = models.CharField(max_length=255, default='', blank=False, null=False) location = models.CharField(max_length=255, default='', blank=False, null=False) These are my serializers: class ShopProductPriceSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['product', 'price'] class ShopSerializer(serializers.ModelSerializer): shopProductPriceData = ShopProductPriceSerializer(many=True, source='shopProductPrice_set') class Meta: model = Shop fields = ['name', 'location', 'shopProductPriceData'] And finally, here is the corresponding view where I want to use a custom queryset: class ShopViewSet(viewsets.ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer def get_queryset(self): queryset = Shop.objects.filter(shopproductpricedata__product__is_special=False) return queryset The important point now is the get_queryset() function. This is what I'm actually working on and … -
PIP installation for Python(Django)
enter image description hereenter image description here After installing python 3.9 version, this is what I am facing in cmd. I am being able to see pip version but if I am commanding pip upgradation it works. How can I solve this PIP problem? -
Website working fine but error in testing
I am getting this error in testing while the website is working perfectly fine. Can someone suggests some changes to be done in the url or html line ERROR: test_index_url_is_resolved (control.tests.test_urls.TestUrls) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/bhavya/Website/control/tests/test_urls.py", line 7, in test_index_url_is_resolved url = reverse('index') File "/usr/lib/python3/dist-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/lib/python3/dist-packages/django/urls/resolvers.py", line 673, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. ---------------------------------------------------------------------- Ran 1 test in 0.003s This is url line url(r'^$',views.IndexView.as_view(),name='index'), This is used in html file "{% url 'control:index' %}" -
Javascript is not loaded in html in django
In my project,there is a register.html file . the file is given below: <!DOCTYPE html> {% load static %} <html> <head> <title>Page Title</title> </head> <body> <p>This is only for test.</p> </body> <script> src= "{% static 'js/register.js' %}" </script> </html> Here you can see the javascript part in the last section. This script should be load the register.js file which is exists in app_name/static/js/register.js . But the problem is that the register.js file is not loaded . The register.js file is given below: console.log(“this is working”); And you know the output should be this is working but when I run this , the console look as that picture which is given below: browser console screenshot Even If I give full path such as <script> src= "/home/name/python/django/python test/app_name/static/js/register.js" </script> then also the issue is still remain . But if I give direct code like <script> console.log("this is test"); </script> then it perfectly worked. How can I solve this issue? -
How To Stop All Site Associated User From appearing In Post Model ForeignKey During Post Creation
The post logic was to allow all users on my site to be able to create post and news which is a success but unfortunately when creating a post all the whole user in the database appears for the particular authenticated user to choose from and this are information i don't want the user to see when creating post and i do not not plan to remove the user foreign key from the post since it helps me implementing other site critical functions and the author. because the user will serve as author class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=250, unique=True, blank = True) def onlyselfuser(self, *args, **kwargs): self.user = self.request.user super().onlyselfuser(*args, **kwargs) #please take a look at my view.py files class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = __all__ def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) i will appreciate if someone can show me a way out where the login user( user=request.user) will only appear excluding other users on moder and i tried a OneToOneField still and it didnt work. i Don't want to see all site … -
Adding context to django admin changelist_view
I'm trying to add some context to a Django admin view when the change list is displayed. I have this class class LeadStatSummaryAdmin(admin.ModelAdmin): change_list_template = 'admin/stats/leadstatsummary/change_list.html' def get_queryset(self, request): qs = super().get_queryset(request) query=Q() if 'from_date' in request.GET: from_date = datetime.datetime.strptime(request.GET['from_date'], '%d/%m/%Y').strftime('%Y-%m-%d') to_date = datetime.datetime.strptime(request.GET['to_date'], '%d/%m/%Y').strftime('%Y-%m-%d') query = Q(date_of_lead__gte=from_date, date_of_lead__lte=to_date) return qs.filter(query) def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context,) qs = self.get_queryset(request) response.context_data['date_form'] = DateForm(request.GET or None) response.context_data['data'] = qs. \ values('type_of_lead', 'may_contact_provider', 'type_of_care_care_home', 'type_of_care_home_care', 'type_of_care_live_in_care', 'type_of_care_retirement_village') \ .order_by('type_of_lead', 'type_of_care_care_home', 'type_of_care_home_care', 'type_of_care_live_in_care', 'type_of_care_retirement_village','may_contact_provider') \ .annotate(count=Count('type_of_lead')) return response This provides a date form I can use to filter the queryset. This runs fine when called from the menu (so no date form) but when I enter dates and submit I get this error 'HttpResponseRedirect' object has no attribute 'context_data' It is referring to this line of code response.context_data['date_form'] = DateForm(request.GET or None) I do not understand why this should be causing an error and how to fix. Can you help please -
'Category' object is not iterable
I am new to programming I have different categoriries in my django website, I created the model, view. but when I try to go to the localhost/category/categoryname, I get the error: "Category object is not iterable" I appreciate your help in advance #url.py urlpatterns = [ path('', home, name='home'), path('article/<slug:slug>', detail, name='detail'), path('article', article, name='article'), path('category/<slug:slug>', category, name='category')] ############################################### #views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from .models import Article, Category # Create your views here. def home(request): context = { "articles": Article.objects.filter(status="Published") } return render(request, 'website/home.html', context) def detail(request, slug): context = { "article": get_object_or_404(Article, slug=slug, status="Published") } return render(request, 'website/detail.html', context) def article(request): context = { "articles": Article.objects.filter(status="Published"), "category": Category.objects.filter(status=True) } return render(request, 'website/article.html', context) def category(request, slug): context = { "category": get_object_or_404(Category, slug=slug, status=True) } return render(request, 'website/category.html', context) ############################### #models.py from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): title = models.CharField(max_length=300, verbose_name="Category Topic") slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address") status = models.BooleanField(default=True, verbose_name="Do you want to show?") position = models.IntegerField(verbose_name="position") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['position'] def __str__(self): return self.title class Article(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') …