Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django local host connection aborted
I am having new issue when running Django localhost 127.0.0.1:8000 as connection getting aborted ,this is new for me as I am working with Django from 3 month and cant find solution for it. below is the Exception i got: Exception happened during processing of request from ('127.0.0.1', 50501) Traceback (most recent call last): File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Yazan Bader\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine any help pls? -
How to extract the text from a image in python?
I am trying to extract text from an image without using pytesseract. Is it possible to do that? -
upload a slenium screenshot to amazon S3
I need to upload a screenshot made with selenium to an amazon s3 bucket. In my djang project, I did: if not instance.picture: chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = settings.GOOGLE_CHROME_BIN chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(executable_path=settings.CHROMEDRIVER_PATH, chrome_options=chrome_options) driver.get('http://%s' % instance.domain) driver.save_screenshot(slugify(instance.display_name)) instance.picture = "media/websites/%s.png" % slugify(instance.display_name) instance.save() driver.close() My picture is defined in my Model: picture = models.ImageField(upload_to='websites', blank=True, null=True) But unfortunately, this file is never created into the bucket :-( Do someone know how to upload a screenshot ? -
Create Object with Foreign key with Serializer
So I want to create a feedback object with serializer: class Location(models.Model): name = models.CharField(max_length=256) img_small = models.CharField(max_length=1024, blank=True, null=True) img_large = models.CharField(max_length=1024, blank=True, null=True) class Meta: managed = True db_table = 'location' class Schedules(models.Model): user = models.ForeignKey(Users, models.DO_NOTHING, default=None) name = models.CharField(max_length=512, blank=True, null=True) location = models.ForeignKey(Location, models.DO_NOTHING, default=None) detail = models.TextField(blank=True, null=True) start = models.DateField() end = models.DateField() created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'schedules' class Feedbacks(models.Model): location = models.ForeignKey(Location, models.DO_NOTHING) schedule = models.ForeignKey(Schedules, models.DO_NOTHING) start = models.IntegerField(blank=True, null=True) end = models.IntegerField(blank=True, null=True) created = models.DateTimeField(blank=True, null=True) modified = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'feedbacks' and the serializer class: class FeedbackSerializer(serializers.ModelSerializer): location_id = serializers.PrimaryKeyRelatedField(queryset=Location.objects.all()) schedule_id = serializers.PrimaryKeyRelatedField(queryset=Schedules.objects.all()) class Meta: model = Feedbacks fields = ('location_id', 'schedule_id', 'start', 'end') # read_only_fields = ('location_id', 'schedule_id') My data is {"location_id" : 2, "schedule_id" : 2, "start" : "1", "end" : 2} The problem is that after validation my validated_data contain Location and Schedule object, not the id so I cannot insert and get this error int() argument must be a string, a bytes-like object or a number, not 'Location' -
Show excel file in django template
In my django application I am showing the uploaded files like this: {% extends 'base.html' %} {% block content %} {% for i in images %} <embed src="{{ i.document.url }}" width="1600" height="700" type="application/pdf"/> <a href="{% url 'employee:delete_product_file' pk=pk %}" class="btn btn-outline-secondary" role="button" >Delete</a> {% endfor %} {% endblock %} Views.py def view_product(request,pk): print("function called with pk ",pk) images = Uploaded_products.objects.filter(products_connected = pk) print("images ",images) return render(request, "packsapp/employee/productspdf.html", {'images': images, 'pk': pk}) It's working fine when I upload a PDF file but when there is any other format like .docx or any excel file it juts simply downloads the file. How do I show all the file types in the django template? I am assuming it has something to do with the type="application/pdf -
Blank Screen after adding CSS file
so i am following python django tutorial from https://simpleisbetterthancomplex.com/series/2017/09/11/a-complete-beginners-guide-to-django-part-2.html#figure-5 Downloaded Bootstrap Compiled CSS & JS version (Bootstrap v4.0.0). But when i run it on cmd. it shows blank screen only, but when i remove the css file, it shows basic HTML page. I reckon there is some problem in linking my css file. the directory looks like myproject/ |-- myproject/ | |-- boards/ | |-- myproject/ | |-- templates/ | |-- static/ | | +-- css/ | | +-- bootstrap.min.css.map <-- here | +-- manage.py +-- venv/ DEBUG is true, django.contrib.staticfiles is installed My settings.py file code looks like STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), Home.html file looks like {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Boards</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <!-- body suppressed for brevity ... --> </body> </html> Please help! -
Viewing users in django admin
I extended my user model to create two profile types, a mentor profile and a student profile. However I am noticing that I cannot view any of my users in django.admin. I only see groups under authentication. Here is my admin.py file from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import TeacherSignUpForm, StudentSignUpForm from .models import Student, Mentor class CustomerUserAdmin(UserAdmin): add_mentor_form = TeacherSignUpForm add_student_form = StudentSignUpForm mentor_model = Mentor student_model = Student admin.site.register(Mentor, Student, CustomerUserAdmin) models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_activated = models.BooleanField(default=False) ... class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return "Profile of user{}".format(self.user.username) class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='mentor') linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True, blank=True, upload_to='media', default='default.jpg') address = models.CharField(max_length=500, null=True, blank=True) billing_name = models.CharField(max_length=200, null=False, blank=False) account_num = models.IntegerField(default=1234) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(default=1234) def __str__(self): return "Profile of user {}".format(self.user.username) ... forms.py class TeacherSignUpForm(UserCreationForm): email = forms.EmailField(max_length=100) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) linkedin = forms.URLField(max_length=200) address = forms.CharField(max_length=500) billing_name = forms.CharField(max_length=200) account_num = forms.IntegerField() bank_name = forms.CharField(max_length=50) branch_code = forms.IntegerField() ... class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(max_length=100) Currently when I try and run makemigrations … -
Django customer timezone middleware error
i trying to solve the issue of dynamically rendering the UTC dates based on the requestor's timezone. Upon further research , it seems there is no built in way of obtaining this information from the client side and converting the utc time based on that information. It seems like the solution to this is to store the timezone information based on user's input , and dynamically changing the timezone settings in the django project. I have tried to implement this but have faced with some error. Here is my code. My settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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', 'rnd.middleware.TimezoneMiddleware', ] This is my custom time zone middleware: import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(request) tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) This is my view : @login_required def set_timezone(request): if request.method == 'POST': request.session['django_timezone'] = request.POST['timezone'] return redirect('/') else: return render(request, 'template.html', {'timezones': pytz.common_timezones}) class ProfileSettings(LoginRequiredMixin,CreateView): model = SalesExtra template_name = 'rnd/salessettings.html' fields = ['contact' , 'outlook_id','outlook_pw','outlook_address','timezone'] exclude = ['comment_id'] def get_context_data(self, **kwargs): pk = self.kwargs['pk'] context = '' return context This is the URLs: path('settings-timezone/', views.set_timezone , name … -
can't receive form data from request At Django
forms.py is on leftside. views.py is on rightside. result log is on downside. the form data by request is all correct. you can see it by log No.2 the form is bound correctly. you can see it by log No.3 but the result of form data is abnormal. you can see it by log No.4 at log No.4, it failed to print form data. and skip to log No.7 what's the reason? and How can I fix the error? Where can I find the information about it? -
'Country' object has no attribute 'all' django
whenever I try to access my model from django admin, it shows me this error. How can I solve this? Cannot find a way. It says My model Youtube doesn't have a filed getCountry in the error. My model : class Youtube(models.Model): link = models.CharField(max_length=2000) scrap_interval_hour = models.IntegerField(default=8) last_scrapped_datetime = models.DateTimeField(blank=True, null=True) is_feed = models.BooleanField(default=False) # When the video is added to fpn server created_date = models.DateField( auto_now_add=True, help_text="When the trending/channel/playlist is added to fpn server") # Foriegn Key country = models.ForeignKey(Country, on_delete=models.CASCADE, help_text="The country where admin wants to show his given trending/channel/playlist") class Meta: ordering = ('created_date', ) admin from django.contrib import admin from fpn.models import Youtube from datetime import timedelta class YoutubeAdmin(admin.ModelAdmin): def get_fields(self, request, youtube=None): fields = super(YoutubeAdmin, self).get_fields(request, youtube) fields.remove('last_scrapped_datetime') if youtube: fields.remove('country') return fields model = Youtube list_per_page = 10 list_display = ('link', 'is_feed', 'getCountry', 'last_scrapped_datetime') list_filter = ('country', 'is_feed', ) def getCountry(self, obj): return "\n".join([coun.name for coun in obj.country.all()]) -
password isn't hashed on custom user model using rest api
I was trying to create a custom user model and create a rest-api but when I send post request it creates a user model but the password isn't hashed I am using set password in my user_create method and it works fine for comand line based superuser but when I use other user created by the api it don't I am using set password method but it don't work either Here is my usermodel class UserProfile(AbstractBaseUser, PermissionsMixin): """custom user model""" email = models.EmailField(max_length=250, unique=True) name = models.CharField(max_length=250) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # django required and django user field declaration USERNAME_FIELD = 'email' objects = UserProfileManager() REQUIRED_FIELDS = ['name'] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email my profile manager class UserProfileManager(BaseUserManager): """User manager for our custom user model""" def create_user(self, name, email, password=None): if not email: raise ValueError('User Must have an email') email = self.normalize_email(email) user = self.model(name=name, email=email) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, email, password=None): user = self.create_user( name=name, email=email, password=password) user.is_staff = True user.is_superuser = True user.save(using=self._db) my serializer class UserProfileSerializer(serializers.ModelSerializer): """Serializes our custom django user model UwU (nice serializer desu ka)""" class Meta: model = models.UserProfile fields = ('id','name','email','password') … -
How to implement periodic tasks in celery by triggering from a Django?
I have a Django Model which has a published_at field. I want to execute a function every 24 hrs after the published_at everyday. So if, publish_at = '5 Feb 2020 12AM' At 6 Feb 2020 12AM , a set of methods will be implemented At 7 Feb 2020 12AM , a set of methods will be implemented for x days I have limited knowledge about Celery so I don't know how to execute this, so I have no code to show :) -
How to print the full / absolute URL(with domain) of each article using django template tags?
I want to print out the full / absolute URL(with domain) of each article through django template tags and use django-qr-code 1.1.0 to generate a QR code for scanning and sharing? How to do it? django version2.1 -
Add success message for built-in LoginView of Django
I am using built-in LoginView from django.contrib.auth.views.LoginView and I don't know how to send a success message upon a successful login of user. Here is how urls.py looks like: from django.contrib.auth.views import LoginView urlpatterns = [ path('login/', LoginView.as_view(), name='login'), ... ] well, you know every other thing is abstract away and works magically as expected. How do I override this LoginView to add success_message? -
Sort items by one of related model in Django (not filter)
I have project, where I can create a bunch of custom fields for each Article in Folder. So, I want to give to user ability to select Article's Custom Field and sort (sort, not to filter!) data by it's field_value. How can I do that in a proper way? Model structure: class Folder(models.Model): title = models.CharField(max_length=100) class FolderCustomField(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) class ArticleField(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) field = models.ForeignKey(FolderCustomField, on_delete=models.CASCADE) field_value = models.CharField(max_length=100) When you create a Folder fields, add them to Articles and serialize, you will get structure like that: { "articles": [ { "id":1, "title": "Article 01" "fields": [ { "field": { "id": 1, "title": "CustomField 01" }, "field_value": "345" } ] }, { "id":2, "title": "Article 02" "fields": [ { "field": { "id": 1, "title": "CustomField 01" }, "field_value": "123" }, { "field": { "id": 2, "title": "CustomField 02" }, "field_value": "qaz" } ] }, { "id":3, "title": "Article 03" "fields": [] } ] } So, let's say, I want to sort Articles by field_value of CustomField 01. It means, at the end I need got ALL tasks (with ability to offset:limit queryset), but sorted by that … -
Problem in adding Offset to Views in django
I want to add limit and offset to my url. views.py def get(self, request, *args, **kwargs): limit = request.GET.get('limit') offset = request.GET.get('offset') res = Question.objects.all() if limit: if offset: res = res.filter()[int(offset):int(limit)] else: res = res.filter()[:int(limit)] paginator = Paginator(res, 10) page = request.GET.get('page') try: a = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. a = paginator.page(1) serializer = QuestionSerializers(a, many=True) return Response({"Section": serializer.data}) Here, offset is not working other than that every thing is working, what am i doing wrong here ? -
Why django uses hmac during session_auth_hash instead of hashlib.pbkdf2_hmac
I was trying to understand hashing and was studying the password hash and session_auth_hash The following are the code from Django which shows hmac is being used while calculating session_auth_hash FROM: django/contrib/auth/init.py def login(request, user, backend=None): session_auth_hash = user.get_session_auth_hash() .... request.session[HASH_SESSION_KEY] = session_auth_hash ... and FROM: django/contrib/auth/base_user.py def get_session_auth_hash(self): """ Return an HMAC of the password field. """ key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" return salted_hmac(key_salt, self.password).hexdigest() FROM: django/utils/crypto.py def salted_hmac(key_salt, value, secret=None): """ Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function and # SHA1 works nicely. key = hashlib.sha1(key_salt + secret).digest() # If len(key_salt + secret) > sha_constructor().block_size, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that … -
How do we set default update (as default = _datetime.now) for timestamp (unix epoch) in django python?
I wish to get an automatic Unix epoch timestamp via Django models in Python. I am trying to store Unix timestamp when the record is entered in the database. -
Strange symbols instead of Cyrillic Django
I'm trying to add data to DB by external script. In this script, I first create a list of Model elements, and then add them to DB by bulk_create method. from shop.models import SpeciesOfWood species_of_wood = [ SpeciesOfWood(title="Ель"), SpeciesOfWood(title="Кедр"), SpeciesOfWood(title="Пихта"), SpeciesOfWood(title="Лиственница") ] SpeciesOfWood.objects.bulk_create(species_of_wood) This code works well in terms of adding data to DB, but idk what happens with values I wanted to add, here is screenshot: I already tried to add: # -*- coding: utf-8 -*- u prefix to title values But it didn't change anything. -
Saving file with ':' in filename into Django FileField
I am currently trying to save a file with name 'test:sample.pdf' into Django FileField. However, the file is saved into the database with name 'testsample.pdf'. May I know if there is a way to retain its original name and prevent django from altering the name? Any help is appreciated. Thank you. Below are some of my code: models.py class SentAttachments(models.Model): attachment = models.FileField(upload_to="sentattachments/") how i save my attachment: savecompose = SentAttachments(attachment=compose_attachments[i]) savecompose.save() -
Deploy Vue JS Django app with Elastic Beanstalk
I've got an app I've built locally and I'm ready to deploy it but using Vue as a frontend and Django as the backend is something new to me. My current folder structure looks like: -Backend -Frontend -Env The backend folder is a traditional Django project with sqlite as a DB and frontend is your normal looking Vue project while env is the virtual environment I don't even know how to go about this or what questions to ask but I've come to see that people deploy SPAs with AWS Elastic Beanstalk. What is the most straightforward way to deploy an app like this? -
How to get the context of one view to another view in Django
I want to add context in my create_form view but I get error rebounded local assignment 'range' and the context of create_form view should get in create_test_bills. from django.shortcuts import render, redirect from .forms import TestForm from .models import Test from django.template.loader import get_template from django.http import HttpResponse from project.utils import render_to_pdf def create_form(request): if request.method == 'POST': range = request.POST.get('range') results = request.POST.get('results') unit = request.POST.get('unit') print(range,results,unit) return redirect('test_bills') return render(request,'form.html',{}) def create_test_bills(request,*args, **kwargs): if request.method == 'POST': range = request.GET.get('range') results = request.GET.get('results') unit = request.GET.get('unit') pdf = render_to_pdf('invoice.html',{'range':range,'results':results,'unit':unit,}) return HttpResponse(pdf, content_type='application/pdf') my template for form.html . I have included some fields required . <form method="POST"> {% csrf_token %} <div class="container"> <input type="text" placeholder="Range" name="range" required> <input type="text" placeholder="Results" name="results" required> <input type="text" placeholder="Unit" name="unit" required> <button type="submit" class="registerbtn">Register</button> </div> </form> </body> </html> -
When should I use ParseError versus ValidationError in Django Rest Framework serializer?
With Django Rest Framework, when should I be raising a ParseError versus a serializers.ValidationError when validating form data in a serializer? My code looks something like this: class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): if 'username' not in validated_data: raise ParseError({'username': ['A username is required.']}) if 'password' not in validated_data: raise ParseError({'password': ['A password is required.']}) if 'email' not in validated_data or len(validated_data['email']) == 0: raise ParseError({'email': ['An email is required.']}) if UserModel.objects.filter(email=validated_data['email']): raise ParseError({'email': ['A user with that email already exists.']}) # (...) Which of these, if any, should be serializers.ValidationError instead? And what rule should I follow in the future to determine which to use? -
CSRF Token Verification Failed
I see this question has been asked many times - but I cannot determine what specifically I am doing wrong. Could anyone help me identify what is wrong? I have the CSRF token there but I feel I must be doing something wrong in the view? views.py if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) auth_login(request, user) return render('test.html') else: form = RegistrationForm() return render(request, 'register.html', {'form': form}) register.html <form method="POST" class="border border-light p-5"> {% csrf_token %} <p class="h4 mb-4 text-center">Registration</p> {{form.username}} {{form.email}} {{form.password}} <button type="submit" class="btn btn-default btn-block my-4" type="submit">Register</button> </form> -
How can I apply {% static %} to all static files in my django project or just let django navigate through all my files?
I added a Minecraft Overviewer render to my django site and stored all of the png, js, and css files in the static folder. The render contains tens of thousands of these files and I don't want to manually do {% static 'render/name.js' %} 40,000 times through various file paths. Is there a way to just let django navigate through all of these files?