Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incorporating my existing code as a Django Model?
I have built a program that uses a webscraper and geopy to extract venue name at Latitude/Longitude with the aim of putting the venues onto a map on a website. I am currently using Django and need to begin creating my database for the website. Is it possible to incorporate my pre-existing program code as a Django model and have the website draw from a database I have already written the code to create? Here is the code I have written for that webscrapes, geocodes and puts into database, can it be integrated into my django code as a model? What would I need to change to make it function well?: #cafeNames def scrapecafes(city, area): #url = 'https://www.broadsheet.com.au/melbourne/guides/best-cafes-thornbury' #go to the website url = f"https://www.broadsheet.com.au/{city}/guides/best-cafes-{area}" response = requests.get(url, timeout=5) soup_cafe_names = BeautifulSoup(response.content, "html.parser") type(soup_cafe_names) cafeNames = soup_cafe_names.findAll('h2', attrs={"class":"venue-title", }) #scrape the elements cafeNamesClean = [cafe.text.strip() for cafe in cafeNames] #clean the elements #cafeNameTuple = [(cafe,) for cafe in cafeNamesCleans #print(cafeNamesClean) #addresses soup_cafe_addresses = BeautifulSoup(response.content, "html.parser") type(soup_cafe_addresses) cafeAddresses = soup_cafe_addresses.findAll( attrs={"class":"address-content" }) cafeAddressesClean = [address.text for address in cafeAddresses] #cafeAddressesTuple = [(address,) for address in cafeAddressesClean] #print(cafeAddressesClean) ##geocode addresses locator = Nominatim(user_agent="myGeocoder") geocode = RateLimiter(locator.geocode, min_delay_seconds=1) lat = [] long = … -
Inline edit using ng change angular js
I have a editable table and I reproduce the sum of column values below the table. Now I want to change the column values and the sum of column values below should change automatically? -
Django "TypeError: 'MultiSelectField' object is not iterable" while overriding MultiSelectField choices
I need to create a Django model 'CitiesVisited' with a MultiSelectField that will contain all cities for a given country taken from a JSON file. The saved objects need to look like this: So that for each country ('CitiesVisitedCountry' model), each user can save the cities they visited. Models.py class CitiesVisitedCountry(models.Model): """ Every user can have multiple countries visited. Each instance of this class will save oen country """ user = models.ForeignKey(User, on_delete=models.CASCADE) country_name = models.CharField(max_length=50) def __str__(self): return f"{self.country_name}" class Meta: """ define nemes to be displayed on admin page """ verbose_name = "Country visited" verbose_name_plural = "Countries visited" class CitiesVisited(models.Model): """ For each country visited, save selection of cities visited """ user = models.ForeignKey(User, on_delete=models.CASCADE) country = models.ForeignKey(CitiesVisitedCountry, on_delete=models.CASCADE) cities = MultiSelectField(choices=select_cities_options("Austria"), null=True, blank=True) def __str__(self): return f"visited cities for country {self.country} checkbox" class Meta: """ define nemes to be displayed on admin page """ verbose_name_plural = "Cities visited checkbox multiple selections" The problem is that I am forced to use a default list to populate choices (I use Austria for example) and I am not able to override this list on object creation. select_cities_options("Austria") def select_cities_options(country_in): """ country_in = 'United States' Returns a list with tuple of … -
Django - Class based to Function based
There is the code in classed based.Someone please convert in function based view. class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category= self.kwargs['category'] movies = Movie.objects.filter(category = self.category) return movies def get_context_data(self,**kwargs): context = super(MovieCategory,self).get_context_data(**kwargs) context['movie_category'] = self.category return context LANGUAGE_CHOICES = ( ('en','ENGLISH'), ('gr','GERMAN'), ) class Movie(models.Model): title = models.CharField(max_length=100) discription = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') category = models.CharField(choices=CATEGORY_CHOICES , max_length=20) language = models.CharField(choices=LANGUAGE_CHOICES , max_length=20) -
How to display a form's help_text when rendering django forms' fields manually?
So, in my Forms.py i have this: class CustomerForm(forms.Form): name = forms.CharField(max_length=255,required=True,validators=[alphaonly],help_text="Enter your name") And i'm trying to render it into a HTML like this: <div class="form-row"> {{ form.name.errors }} <div class="form-label"> <label class="p-small" for="{{ form.name.id_for_label }}">Name</label> </div> <div class="form-input"> {{ form.name }} </div> </div> The problem is the help_text being displayed is the generic 'Please fill out this field' instead of the designated help_text i made. How can i solve this? -
Docker + Django on Elastic Beanstalk
I have a Django project. I am considering adding Docker to it before deploying to Elastic Beanstalk. I am very new to Django and Docker and want to know what are the benefits of using Docker when deploying a Django app to Elastic Beanstalk. Thanks! -
How to get a specific item from django database with that specific pk value?
I am trying to make an automated mailing app that will mail it to all the users that have signed in to the app. I have made a model that takes the subject and the text of the mail. models.py from django.db import models from django.urls import reverse # Create your models here. class Mail(models.Model): subject = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(auto_now=True) # email = models.EmailField() def __str__(self): return str(self.created_on) def get_absolute_url(self): return reverse("home") I have also created a form which stores the subject and the text in the database and this is the CreateView views.py from django.shortcuts import render from . import forms,models from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.core.mail import send_mail # Create your views here. class CreateMailView(generic.CreateView,LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'index.html' form_class = forms.MailForm model = models.Mail Now I want to get the subject and the text of that specific pk like 1 or 3 from the database this is views.py class SendMailView(generic.views): # Take all the email ids from the User model emails = User.objects.filter(is_active=True).values_list('email', flat=True) subject = models.Mail.objects.filter......... text = models.Mail.objects.filter..... #This is used to send email imported from (from django.core.mail import send_mail) send_mail(subject,text,'djangospare@gmail.com',emails,fail_silently=False) So how to fetch … -
How to Allow Superusers to access Django Admin Panels
# UserManager is for Custom User Model to override Django's Default Model class UserManager(BaseUserManager): def _create_user(self, email, password, is_superuser, **extra_fields): if not email or not password: raise ValueError("The given username or password must not be null") user = self.model( email=email, password=password, is_superuser=is_superuser, last_login=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): return self._create_user(email, password, True, **extra_fields) class Users(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at_utc = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['password'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return self.is_admin def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class Meta: db_table = "users" I have the above code for Users, and following Code for Admin Panel to create and update User's Can anyone help me out me with a Solution to restrict Access to Admin Site for Super Users … -
How do I make available gpu powered application to the web?
I have an application which uses GPU to perform its job (as an example face_detection application which is detecting faces from images using Nvidia GPUs). My current setup is as: Server on ubuntu system exposes both HTTP/REST and GRPC endpoints based on KFServing standard inference protocols that have been proposed by the KFServing project. Server implements a number HTTP/REST and GRPC extensions to the KFServing inference protocol. I have a GRPC and HTTP/REST client which can communicate to local server and get the results. Now my question is how to make this available to web means: A: user can upload the picture via website interface B: user request come to application C: the application talks to server to collect the results D: highlight the faces in image E: application sends back the modified image (with faces) for the user to download At the moment only C and D are happening. This has a lot of additional concerns e.g. security/protection of my hardware/software server, identity and access management, subscription plan, and online payment processing etc.? I am aware the if I go the Amazon Cloud services, I'll get the infrastructure which will provide everything but then they will charge me for … -
why my search bar is not working in Django?
created a simple search in the Django blog but it's not working. why search bar is not working in a blog web app ? its nothing to search in the search bar when searching something in the search box. - urls.py urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('search', views.search, name='search'), ] - views.py def search(request): query = request.GET['query'] allPosts = Post.objects.filter(title__icontains=query) params = {'allPosts': allPosts} return render(request,'home/search.html', params) - search.html {% extends 'base.html' %} {% block title %} Search Results {% endblock title %} {% block blogactive %}active{% endblock blogactive %} {% block body %} <div class="container my-3"> <h2>Search Results</h2> {% for post in allposts %} <div class="row no-gutters border rounded overflow-hidden flex-md-row my-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">Article by {{post.author}}</strong> <h3 class="mb-0">{{post.title}}</h3> <div class="mb-1 text-muted">{{post.datetime}}</div> <p class="card-text mb-auto">{{post.content | truncatechars:500}}</p> <div class='my-2'> <a href="/blog/{{post.slug}}" role='button' class="btn btn-primary">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> </div> </div> </div> {% endfor %} {% endblock body %} -
"GET /media/img/image.png HTTP/1.1" 404 2575
When viewing page the image is not loaded. The image is uploaded via Django-admin The part of HTML template loading image is: Home.html <img class="card-img-top" src="{{ product.image.url }}"> settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The error shown in the terminal: Not Found: /media/img/sandstone.png [00/Aug/0000 00:00:00] "GET /media/img/image.png HTTP/1.1" 404 2581 -
Django - Larger files failing to uploading files to heroku
I am having trouble doing a post to a django app hosted on heroku. I have a form that submits 3 images and everything works fine when I use smaller images of about 100kb, however when I user larger images of ~3MB the upload fails with error in heroku logs showing as at=error code=H13 desc="Connection closed without response" method=POST path="/" In django, am simply saving the images then emailing them as shown below, where formdata is holding the images. Hope the snippet is enough: for each in form_data: pic = form_data[each] if pic: filename = os.path.join(self.location,f"{i} - {pic.name}") imgbytes = pic.read() with open(filename, 'wb+') as destination: destination.write(imgbytes) i+=1 fileholder.append(filename) email = EmailMessage( subject = 'Hello', body = 'Body goes here', from_email = 'example@yahoo.com', to = ['test@google.com'], ) for each in fileholder: email.attach_file(each) email.attach_file(newpath) email.send() What is causing this and how can i ensure any image size is uploaded succesfully? -
How to make a field required if the request is POST but if the request is PUT the field not required? (django model)
I created a model of 7 fields where all fields blank=True, null=True but one of them is required. The problem is I want to make it required only the the request is a POST otherwise its not required for example: in case if a PUT method users don't need to mention at all. -
Django pypdftk - subprocess.CalledProcessError
I'm tring to fill a pdf with information from a dictionary. When i run the following code: fields = {'zeitraum': getMonth(month), 'arzt': doc.name, 'rechnungsnr': verrechnungsNr, 'verrechnungsbasis': total['verrechnungsbasis'], 'marketing': total['marketing'], 'dauer': str(total['dauer'])+" min.", 'miete': total['miete'], 'geraeteaufwand': total['geraet'], 'labor': total['labor'], 'material': total['material'], 'materialust': materialust, 'mwst':mwst, 'gesamt': gesamt} result = pypdftk.fill_form('/assets/docs/sf_rechnung_arzt.pdf', fields) return FileResponse(result, as_attachment=True, filename='output.pdf') i get the following error: subprocess.CalledProcessError: Command 'pdftk /assets/docs/sf_rechnung_arzt.pdf fill_form C:\Users\pataki\AppData\Local\Temp\2\tmpyf2o6cgc output C:\Users\pataki\AppData\Lo cal\Temp\2\tmpqqolt1_3 flatten' returned non-zero exit status 1. And I can't figure out what's wrong. Does anyone have hints? Thanks! -
how to fix this error: No module named 'allauth'?
I want to use allauth in django API but when I installed it I got some errors I fixed it by django.setup() and after that, I get the error which tells me that I have to set DJANGO_SETTINGS_MODULE now I did that in manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import django def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings' django.setup() main() but I get this Traceback: Traceback (most recent call last): File "manage.py", line 23, in <module> django.setup() File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/abdelhamedabdin/.local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' please can anyone tells me how can I fix that exception … -
django custom user can't set attribute error
I followed CodingEntrepreneurs tutorial on Custom Users and extended it to have 3 types of users: school, parent and vendor. I have created view, form for each type of user. In forms.py I have class ParentSignUpForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta(): model = User fields = ('email', ) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super(ParentSignUpForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.is_parent = True user.save() return user I try to change is_parent attribute from False to True. However, error is: File "/home/azamat/dev/dj_test/src/accounts/forms.py", line 137, in save user.is_parent = True AttributeError: can't set attribute How to solve this issue? Or any better way to save users with different types? -
Can run two web frameworks on one website
Can run two frameworks on one website? There is two Django and Wordpres and suppose to deploy like this: www.myDjangoSite.com/blog-wp/ How to config and which technologies shall use? -
Django with mssql backend KeyError: 'deferrable' when running migrate
I am trying to start a new project in Django which will be using Microsoft SQL Server as database backend. I have installed django-mssql-backend with pip. Here is my pip freeze output: asgiref==3.2.10 Django==3.1 django-mssql-backend==2.8.1 pyodbc==4.0.30 pytz==2020.1 sqlparse==0.3.1 and this is my config in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db', 'HOST': 'hostIPinstance', 'PORT': '1433', 'USER': 'username', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'unicode_results': True, }, } } The problem is when i try to run 'manage.py migrate`. Everything runs fine until the 8th step. Here's the output: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length...Traceback (most recent call last): main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\HPI\OSES\Django-OSES\test_mssql\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\HPI\OSES\Django-OSES\test_mssql\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\HPI\OSES\Django-OSES\test_mssql\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "D:\HPI\OSES\Django-OSES\test_mssql\env\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "D:\HPI\OSES\Django-OSES\test_mssql\env\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) … -
Django admin cannot delete/change instances
I am working on a Django project, and had registered all my models to admin. But due to some reason, I cannot change any of the instances of any model that I created. This is how it shows: This is the initial screen as I log in. As soon as I click on add/change, instead of the usual screen it shows like this: Can anyone please help! Thanks in advance :) -
Saving object from ListView in django
I have a generic ListView which displays all objects from a model and I would like users to be able to choose one object for further processing by storing in session or in another model. What would be the best way to go about this? views.py class TranscriptListView(generic.ListView): model = Transcript template_name = 'transcript_list.html' template {% block content %} <ul> {% for transcript in transcript_list %} <li> <a href="{{ transcript.get_absolute_url }}">{{transcript.name}}</a> <p>{{transcript.text}}</p> </li> {% endfor %} </ul> -
502 Bad Gateway error because of Gunicorn WORKER TIMEOUT while uploading large files
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I need to get .igs file in one of my forms and save it to S3 Bucket but I was getting 413 Request Entity Too Large error. Then I have created a folder as .platform/nginx/conf.d/mysite.conf and I have added the code below into it. client_max_body_size 50M; client_body_buffer_size 30M; After creating this config file, when user press the submit button, the file I uploaded on the form can now save to S3 Storage, so the 413 Request Entity Too Large error fixed but the page gives a 502 Bad Gateway error. The file which I try to upload is 4 MB. However, there is no error with smaller files. I have tried many solutions but they all didn't work. My nginx error.log file; 54 upstream prematurely closed connection while reading response header from upstream and my web.stdout.log file; [16639] [INFO] Starting gunicorn 20.0.4 [16639] [INFO] Listening at: http://127.0.0.1:8000 (16639) [16639] [INFO] Using worker: threads [16715] [INFO] Booting worker with pid: 16715 numexpr.utils - INFO - NumExpr defaulting to 2 threads. [16639] [CRITICAL] WORKER TIMEOUT (pid:16715) [16995] [INFO] Booting worker with pid: 16995 … -
TypeError: validate_email() missing 1 required positional argument: 'password'
I am trying to override rest_auth's default LoginSerializer, when I try to login, it throws this error. Here is my code: settings.py REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'Customer.apis.serializers.LoginSerializer', } and Login Serializer class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = Customer fields = ['email', 'password'] def validate_email(self, email, password): user = None if email and password: user = authenticate(email=email, password=password) else: raise exceptions.ValidationError('Invalid Credentials') return user def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = self.validate_email(email, password) attrs['user'] = user return attrs What could be the error? And the possible workaround? -
django rest api call admin action
i created a simple model and created an admin action for it. Then i installed dango-rest and connected to model so i can use it from another machine with rest api calls. Is there a way i can call the admin action as well? Here is my sample: models.py from django.db import models class my_model(models.Model): my_id = models.CharField(primary_key = True, max_length=20) my_line = models.CharField(max_length=20, default='#') my_description = models.CharField(max_length=255) admin.py from django.contrib import admin, messages from .models import my_model def precheck_action(modeladmin, request, queryset): for obj in queryset: if obj.my_line == 'second step': obj.my_description = 'provided' else: obj.my_description = 'waithing for second step' obj.save() class my_form((forms.ModelForm): class Meta: model = int_unmanaged fields = '__all__' class my_form_admin(admin.ModelAdmin): form = my_form list_display = ('my_id', 'my_line','my_description') actions = [precheck_action] admin.site.register(my_form, my_form_admin) Any help on solving this or maybe a better way of doing it would be great. Thank! -
{% extends 'base.html' %} doesn't loaded in django
I am working on a one page website, and try to disect each section to different html file, and now the base.html that contain css, js file don't want to load. Instead, it returns "Invalid block tag on line 21: 'static', expected 'endblock'. Did you forget to register or load this tag?" comment on some of the {% include "page.html" %}. I've tried add {% load static %} {% load staticfiles %} on each {% include "page.html" %}, still don't help with the css, js from the base.html. Any thoughts to solve this issue? Thank you in advance Here are my codes: Here is my base.html <!DOCTYPE html> {% load staticfiles %} {% load fontawesome %} {% load static %} <html lang="en"> <head> {% fontawesome_stylesheet %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Website</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'https://fonts.googleapis.com/css?family=Montserrat:400,700' %}" rel="stylesheet" type="text/css"> <link href='{% static "https://fonts.googleapis.com/css?family=Kaushan+Script" %}' rel='stylesheet' type='text/css'> <link href='{% static "https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic" %}' rel='stylesheet' type='text/css'> <link href='{% static "https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700" %}' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> … -
Django+Celery+RabbitMQ, Does Celery need separate server in production?
I have recently learned to integrate Celery + RabbitMQ in local machine, all three of them were running in separate servers. During production, should I run celery & RabbitMQ in separate server ? I have searched for Celery hosting options but couldn't find useful links. I usually use Pythonanywhere to host my Django app I found this https://stackoverflow.com/a/46105723/10515390 answer useful but did't get a clarification