Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resize and convert mime image Django
I try resize and convert mime before save a image models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to=upload_to_path, null=True, blank=True, default='magickhat-profile.jpg' ) def save(self, *args, **kwargs): #on update image delete old file try: this = ProductImages.objects.get(id=self.id) if this.image_file != self.image_file: this.image_file.delete(save=False) except: pass super().save(*args, **kwargs) image_manipulation(self) The function upload_to_path and image_manipulation is imported from utils.utils import upload_to_path, image_manipulation utils/utils.py from PIL import Image from pathlib import Path def upload_to_path(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"."+ext return 'user_{0}/{1}/{2}'.format(instance.product.user.id, instance.product.id, filename) def image_manipulation(self): pathx = self.image_file.path self.image_file = Image.open(pathx) img_x = self.image_file.resize((200,300)) img_x.save(pathx) With this code work, but I'm not getting implement this code to convert to png too... When i try something like: def image_manipulation(self): pathx = self.image_file.path self.image_file = Image.open(pathx) img_x = self.image_file.resize((200,300)) img_rgb = img_x.convert('RGB') img_split_ext = Path(pathx).stem img_rgb.save(img_split_ext+".png") When i made this change, the file is uploaded, but not resize and note convert to png. If possible, im appreciate if could i little explanation, about the flow of this process, between a callable upload_to that, receive 2 parameters (instance, filename) the method save() itself, becouse from my pov upload_to is about the record in database, and save() is about filesystem storage... … -
How to make two manytomany fields in a model hold different values
I have Two simplified models as bellow: class Courses: name = models.CharField(_("Course name"), max_length=256) class School: main_courses = models.ManyToManyField(_("Main Courses"), to="course.Courses", related_name="maincourses", blank=True) enhancement_courses = models.ManyToManyField(_("Enhancement Courses"), to="course.Courses" related_name="enhancementcourses", blank=True) main_courses and enhancement_courses are going to hold a list of Courses. But I need to make sure their values wont be equal. For example if in school_1, main_courses are math, physics then enhancement_courses can't be these values. What is the simplest way in django to do this? -
Error with OpenCV live stream webcam in Django project
So I have a template were I render a view that has a live stream webcam in Django. When I run the server for the first time the camera works fine, but if I go back and then enter again I get this error: cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:976: error: (-215:Assertion failed) !image.empty() in function 'imencode' I have searched for this issue but I haven't found the exact solution. views.py: @gzip.gzip_page def live(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, "live.html") class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('live/', views.live, name='live'), ] live.html: <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <img src="{% url 'live' %}" /> </body> </html> help is much appreciated -
django.db.utils.ProgrammingError: relation "administration_parks" does not exist
I had a problem, and I really struggled to figure out what was wrong. I made an application with the Django framework. Everything worked fine on my local machine, including the DB. Only, when I put my application on the server, I wanted to migrate the database, but I had this error : Traceback (most recent call last): File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "administration_parks" does not exist LINE 1: ...name", "administration_parks"."availability" FROM "administr... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check … -
Why do certain querysets take longer to serialize in my serializer
I have an API built using Django and Django REST Framework that returns a paginated response to the front-end. By default the page_size is 25, but depending what instances of objects are being passed to the serializer it could either respond fairly quickly or very slowly. The user can select a variety of parameters to make a search on. These parameters are then passed to the backend where the queryset is filtered. This queryset is then paginated, serialized, and returned to the front-end. I understand that the filtering and pagination would take a variable amount of time depending on the parameters that are being filtered on, and the size of the queryset. I'm wondering why it is that the serializer has significantly different performance for different paginated querysets (anywhere from .5 seconds to 20 seconds). My serializer class draws data from a lot of different parts of the database. I've used select_related, and prefetch_related in parts that were applicable, this improved the serializer performance across the board. There are a few SerializerMethodFields that still make queries resulting in N+1 issues, this doesn't seem to be the major issue however. From close inspection the query that takes the longest to run … -
Django Admin raise Integrity Error when I set UniqueConstraint on model
I am developing Library management system and I want to avoid duplicate records, I have the following book model: class Book(models.Model): isbn = models.CharField(max_length=13, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) preview = models.ImageField(upload_to='books/') author = models.ForeignKey(Author, on_delete=models.CASCADE) stock = models.PositiveIntegerField(default=0) assigned = models.PositiveIntegerField(default=0) class Meta: constraints = [ models.UniqueConstraint(Lower('title'), 'author', name="unique_book_with_author" ) ] def __str__(self) -> str: return self.title I want to make sure that a book with same incasesensitive title and author exists only once, Now I want that if user tries to add duplicate record, he get nice error message, this book already exists, but admin raises Integrity error as Follow: My admin class is as follow: @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'category', 'assigned', 'is_available' ] search_fields = [ 'title', 'author__name__startswith' ] @admin.display(ordering='is_available', boolean=True) def is_available(self, book): return book.stock > book.assigned def get_search_results(self, request, queryset, search_term: str): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset = get_int_search_result(queryset, self.model, search_term, 'isbn') return queryset, use_distinct Docs are not helping me, please guide what I do? because when I use unique_together in Meta class (which will be deprecated soon as mentioned by docs), everything works fine and django admin give nice error message, but when I am using … -
How to set-up dynamic select fields in Django admin with Ajax?
I'm using Ajax to create dynamic select fields in my template views, but I now need to set it up to work also in my Admin. I've researched multiple alternatives, one being django-smart-select which I couldn't get to work for some reason. So I'm putting my trust in Ajax and hoping to get this to work in some way. I'm currently overriding the change_form.html which Django uses when a user is changing a form, but when trying to retrieve the response from the request I do when one select field is changed, I get a full HTML document full of irrelevant Django-admin data. Anyone who can help me out with this or suggest another way that I can get it to work? My template.html where things work as expected {% extends '_base.html' %} {% load static %} {% block content %} <body onload="hide_area_field()"> {% block form_title %} <h2>Ny annons - Kontorshund erbjudes</h2> {% endblock form_title %} <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Publicera annons</button> </form> </body> {% endblock content %} {% block footer %} {% comment %} Imports for managing Django Autocomplete Light in … -
ValueError: invalid literal for int() with base 10: b'20 07:01:33.203614' In Django 3.0 and python 3.7
After upgrading from Django 1.8 to Django 3.0 Here in Django 1.8 for the same code __unicode__() worked fine and when comes to in Django 3.0 i am getting error Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/crm/views.py", line 19569, in autocomplete_items for c in products: File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1170, in execute_sql return list(result) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1569, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1569, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/usr/lib/python3.7/sqlite3/dbapi2.py", line 64, in convert_date return datetime.date(*map(int, val.split(b"-"))) ValueError: invalid literal for int() with base 10: b'20 07:01:33.203614' Let us consider my views.py as def autocomplete_items(request, flag=None): client = request.user.client q = request.GET.get('term') category = request.GET.get('category', '') job_items = JobItems.objects.filter(client_id=client) if category: job_items = job_items.filter(category_id=category) if flag: job_items = job_items.filter(stock='Variety Master') … -
Using Twilio Verify API with Mailgun
I'm using Twilio verify API to use OTP verification in my project. I have implemented SMS verification with Twilio. but for email Twilio is using Sendgrid and for some reason I can not use Sndgrid. I am already using Mailgun. So is there any way I can just send the Twilio Verify OTP Mail with mailgun. here is my twilio verify function - def verifications_email(email, via): msg = client.verify \ .services(settings.TWILIO_VERIFICATION_SID) \ .verifications \ .create(to=email, channel=via) def verification_checks(email, token): return client.verify \ .services(settings.TWILIO_VERIFICATION_SID) \ .verification_checks \ .create(to=email, code=token) so can anyone please give me a suggestion what should do to solve my problem? Thank You! -
AH00364 - Apache24 wont start service
i'm doing a project for college. were building a website and after restarting my amazon EC2 instance apache wont longer start. this is from the httpdconfig file for apache # Define SRVROOT "/Apache24" ServerRoot "${SRVROOT}" Alias /static/ /SCE_Proj/Server/static/ <Directory /SCE_Proj/Server/static> Require all granted </Directory> # # Mutex: Allows you to set the mutex mechanism and mutex file directory # #Listen 172.31.32.214:8080 Listen 8080 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # #LoadModule access_compat_module modules/mod_access_compat.so LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so #LoadModule auth_digest_module modules/mod_auth_digest.so #LoadModule auth_form_module modules/mod_auth_form.so #LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_core_module modules/mod_authn_core.so #LoadModule authn_dbd_module modules/mod_authn_dbd.so #LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_file_module modules/mod_authn_file.so #LoadModule authn_socache_module modules/mod_authn_socache.so #LoadModule authnz_fcgi_module modules/mod_authnz_fcgi.so #LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule authz_core_module modules/mod_authz_core.so #LoadModule authz_dbd_module modules/mod_authz_dbd.so #LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module … -
Accessing the data of a Parent model from a sub Model using the foreign key in Django
I am quite new to API and Django, please pardon me, if this is a silly question, but I cannot seem to get my head around it. I have 2 models (ProductOrder and Product). The ProductOrder model has a foreign key from Product. Here are the 2 models. class Product(models.Model): name = models.CharField(max_length = 100) price = models.IntegerField(default = 1) def __str__(self) -> str: return f'{self.name} Price => {self.price}' class ProductOrder(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE) order_dis = models.FloatField() price = ** Need to get the price of the product using the product id ** order_date = models.DateField() dis_price = price - order_dis def __str__(self) -> str: return f'{self.order_date} {self.dis_price}' I intend to create an API and I wish to enter only the product_id and want to access the product price which would thereby aid in calc. some other fields. Is that possible? -
Nginx shows only Welcome page after changing server_name from IP adress to domain
I use Nginx as Reverse Proxy for a Django project with Gunicorn. After following this tutorial from Digital Ocean How To Set Up an ASGI Django App I was able to visit my project through the server IP adress in a browser with http. In the next step I followed the How To Secure Nginx with Let's Encrypt tutorial from Digital Ocean. Now the site was available with http:// and https:// in front of the IP adress. To redirect the user automatically to https I used code from this tutorial.5 Steps to deploy Django The outcome is the following file in /etc/nginx/sites-available: # Force http to https server { listen 80; server_name EXAMPLE_IP_ADRESS; return 301 https://EXAMPLE_IP_ADRESS$request_uri; } server { listen 80; # manged by Certbot server_name EXAMPLE_IP_ADRESS; # serve static files location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } The redirect to https is working fine, so I assume the changes I made according to the last tutorial are okay. After the tests with the EXAMPLE_IP_ADRESS as server_name went well I have changed … -
Nodejs + Express vs Django: Choosing the best suitable backend component for given requirements
I'm trying to build a software architecture for my web development. The main requirements of the website are as follows: visualize real-time data carry out machine learning analysis Report visualization information via Email or SMS The concept for such an web application consists of a database, a backend and a frontend component. I have already selected a time series database. Despite my research, I cannot determine which backend component best meets the requirements: Nodejs + Expressjs or Django. My programming knowledge in Javascript and Python is on the same level. Why Node: its Single Threaded Event Loop Model for real-time web applications same programming language for selecting a javascript framework on the frontend-side (but python for machine learning analysis) More flexibility than Django due to its MTV pattern (usually) less execution time than python-Code Why Django: Django Channels for real-time web applications python language in backend, frontend and for data analysis quicker development process because of the language simplicity more secure due to its build-in security tools Question: Are there any other technical arguments why I should consider choosing Nodejs or Django or any arguments for not choosing one of them? -
how to convert relationship OneToOne to OneToMany keeping the existing data in django
I had created these models in the past but I need to change the relationship between the User model and Profile from oneToOne to OneToMany so that the User can have multiple profiles. since the database already exists if I run the classic modification the data will disappear class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField( _('phone number'), max_length=50, unique=True, blank=True, null=True, default=None,) email = models.EmailField( _('email address') ,unique = True, blank=True, null=True, default=None,) #email and phone defaults are set to None to avoid duplicated key errors because empty charfields are stored as #empty strings email_confirmed = models.BooleanField( _('email is confirmed'), default=False ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) profile = models.OneToOneField("OrdinaryProfile", on_delete=models.CASCADE, blank=True, null=True) # roles = models.ManyToManyField(Role, through='UserRole') objects = UserManager() USERNAME_FIELD = 'id' class Profile(models.Model): first_name = models.CharField(max_length=30, ) last_name = models.CharField(max_length=30) picture = models.ImageField(upload_to="profiles", null=True, blank=True, ) created_by = models.ForeignKey("Profile", on_delete=models.CASCADE, null=True, related_name='creator', default=None) # address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=100, blank=True, null=True) location = … -
How to Search Comma Separated Strings or List in Django
I have a column in a Django Model Where the text is separated by Commas or the list of user ids. I used this column to search the number of occurrences this user's id is linked in newly registered users. [17, 3, 1] in DB it is saved like this separated by commas. When I used the MyModel.objects.filter(column__contains="7".count() when tried with other options like iregex, iexact, icontains or exact nothing shows. It includes the 7 from 17 and fetches the result. Is there any efficient solution for this problem? -
Deny to access to id of user in Foreignkey model
--WHY I CANT TO ACCESS TO ID OF USER AND PRODUCT WITH user__id and product__id? i have error: (The view store.views.submit_review didn't return an HttpResponse object. It returned None instead). <pre><code> i define some code for rating post for any user user --#views def submit_review(request, product_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id,Product__id=product_id) #my problem is here form = Reviewform(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you!your review has been updated.') return redirect(url) except ReviewRating.DoesNotExist: form = Reviewform(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get['REMOTE_ADDR'] data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted') return redirect(url) </code></pre> this section i define model.I checked this part it work correctly define model for views in my app #models class ReviewRating(models.Model): Product = models.ForeignKey(product, on_delete=models.CASCADE) user = models.ForeignKey(Account, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject this part i define url #urls define path for html and views urlpatterns = [ path('submit_review/int:product_id/',views.submit_review,name='submit_review') ] -
Mapbox Add a default marker to a web map - django
context Using Add a default marker to a web map, I want to add a number of points as markers. Within views.py under 'marker format' I use the marker format const marker6 = new mapboxgl.Marker() .setLngLat([12.554729, 55.70651]) .addTo(map); as a template for each iteration of the loop. Problem The p tag with id 'test' results in below const marker0 = new mapboxgl.Marker().setLngLat([-2.97,53.43890841]).addTo(map); const marker1 = new mapboxgl.Marker().setLngLat([-2.29,53.46303566]).addTo(map); However using the same code "{{context.vf|join:""}}" that produces above, which is the same format as the working markers, doesn't result in markers appearing. Ask Is it possible to do so in a more efficient way? Views.py from django.shortcuts import render from django.views.generic import TemplateView import requests from datetime import date from datetime import timedelta from .models import Regions class HomePageView(TemplateView): # template_name = 'home.html' def get(self,request): # current date is start date start_date = date.today() # end date end_date = start_date #+ timedelta(days=3) # footbal api url = "http://api.football-data.org/v2/matches" querystring = {"dateFrom": start_date, "dateTo": end_date} headers = {'X-Auth-Token': "", } response = requests.request( "GET", url, headers=headers, params=querystring).json() #### extract data # count of returned fixtures count = response['count'] # count of premier league games plist = [] for i in range(0, count): if … -
Serialise an extended User Model in Django
I'm extending a django auth user model in a Profile model: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) activity = models.IntegerField(default=500) def _str_(self): return self in my views I'm getting the current auth user and I get the associated profile: @api_view(['GET']) @permission_classes([IsAuthenticated]) def getUserProfile(request): profile = Profile.objects.get(user = request.user) serializer = profileSerializer(profile, many=False) return Response(serializer.data) Here is my serializers code: from rest_framework import serializers from .models import Profile class profileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('first_name', 'activity') The error I'm getting that Profie object has not a first_name attribute, but when I replace 'first_name' with 'user' I get only the id of the user, so I want to show the first_name as well. Thank you -
django, INFO:waitress:Serving on http://0.0.0.0:8000 , its showing me error Plese help me?
While I use the url http://0.0.0.0:8000 in browser, it says "The site cannot be reached." How to solve this problem. Any one help me, please! my django project name is: testtodo and I use command -> waitress-serve --port=8000 testtodo.wsgi:application when i click on this link on my browser http://0.0.0.0:8000 then it's showing me error, this site can't be reached, and also this error The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID -
Django Admin, how to hide change password?
Some users of my Django application come from a LDAP server. These users must not be able to change their django-admin password. The best, if they don't even have one. That's why I subclassed django_auth_ldap.backend.LDAPBackend like this: from django_auth_ldap.backend import LDAPBackend from django.contrib.auth import get_user_model class CustomLDAPBackend(LDAPBackend) def authenticate_ldap_user(self, ldap_user, password): user = ldap_user.authenticate(password) print("BEFORE set_unusable_password(): ", user.has_usable_password()) user.set_unusable_password() user.save() print("AFTER set_unusable_password(): ", user.has_usable_password()) return user By user.set_unusable_password() I try to hide the password, because I read it in several places (here in SO as well as in the docs). But all I can achieve is having no password set: Furthermore if I login multiple times, the result of print("BEFORE set_unusable_password(): ", user.has_usable_password()) is always True, despite calling user.set_unusable_password() and saving the user. As if a new user object is getting created every time. This question does not solve my problem because user.set_unusable_password() apparently does not hide the password-changing area. So what am I missing? How can I hide the 'change password' area? Below is the LDAP-relevant part of the settings.py: import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType,PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://localhost' AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com' AUTH_LDAP_BIND_PASSWORD = 'secret' AUTH_LDAP_USER_SEARCH = LDAPSearch('dc=example,dc=com',ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('dc=example,dc=com',ldap.SCOPE_SUBTREE, '(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = … -
TypeError: CheckNewsDateStatus() takes no arguments
I'm trying to update a django/mezzanine application from python 2.7 to python 3.7. Can you help me in fixing the error below (CheckNewsDateStatus() takes no arguments)? Seems that this class is not used at all; if I grep through all code only the attached settings.py and middleware.py match. Is it something partly implemented in django/mezzanine or it it so that the whole class can be removed as unnecessary ? I don't know how the code was planned to work and I don't know is the feature has been used at all... (python-3.7) miettinj@ramen:~/pika> python manage.py runserver BASE_DIR /srv/work/miettinj/pika PROJECT_ROOT /srv/work/miettinj/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html zone_name = tzlocal.get_localzone().zone /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE setting is not set, using closest match: %s" % tz) BASE_DIR /srv/work/miettinj/pika PROJECT_ROOT /srv/work/miettinj/pika/pika /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/timezone.py:13: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html zone_name = tzlocal.get_localzone().zone /srv/work/miettinj/python-3.7/lib/python3.7/site-packages/mezzanine/utils/conf.py:67: UserWarning: TIME_ZONE setting is not set, using closest match: Europe/Helsinki warn("TIME_ZONE … -
render() got an unexpected keyword argument 'context_instance' in Django 3.0
I had updated my project from Django 1.8 to Django 3.0 Let us consider my views.py as: class StockPricingView(View): def get(self, request, pk): data1 = OtherOrder.objects.get(id=pk) data = PricingModule.objects.filter(item__other_order_id=pk) charges = OtherOrderAdditionalCharges.objects.filter(order_id=pk) if charges.exists(): total_charges = charges.aggregate(Sum('amount')).get('amount__sum') or 0.00 order_total = data1.otherorderitem_set.all().aggregate(Sum('total_cost')).get('total_cost__sum') or 0.00 per_charges = (total_charges/order_total)*100 return render_to_response( 'stock/otherorders/stock_pricing_view.html', locals(), context_instance=RequestContext(request)) Please help me solve this isssue -
How to categorize WhiteNoise?
I am writing scientifically about a Django application. The application returns static files via WhiteNoise and I would like to learn more about it to be able to write precise. How is WhiteNoise classified? Is it correct to speak of a middleware? How is the request processed until WhiteNoise comes into play? Is WhiteNoise responsible for providing the correct reference to the static file in the Django template or does it do more? Does the behavior change if the static files are hosted on a CDN? I highly appreciate any input or reference to helpful articles! Thanks in advance. -
How to add multiple reviews or products using for loop in Django? (fetching data)
I need to add multiple reviews using "for loop". I made the model, and then through the admin panel (of Django)added a review. Now within the same code, I need to add another review. I'm pretty new at this and have to follow the instructions and can't do it any other way. This is how I have looped one review: {% for display in Review %} <i><img src="{{display.image}}"/><span>{{display.name}}</span></i> <p>{{display.desc}}</p> {% endfor %} This is the model: class Review(models.Model): image = models.ImageField(upload_to="static/images") name = models.CharField(max_length=20) desc = models.TextField() -
Certbot Authenticator Plugin error for Nginx
I'm trying to issue an SSL certificate using Cerbot. The command that I'm using is as follows. sudo certbot --nginx -d example.com -d '*.example.com' But every time I run this command, I'm getting the following error. Plugins selected: Authenticator nginx, Installer nginx Obtaining a new certificate Performing the following challenges: Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA. You may need to use an authenticator plugin that can do challenges over DNS. Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA. You may need to use an authenticator plugin that can do challenges over DNS. Now, I don't understand how to fix this issue. Please help. I'm following this guide from DigitalOcean to issue an SSL certificate for Nginx using Cerbot. Thank You.