Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin css doesn't work when using aws s3 buckets
I am using s3 buckets on AWS to store my statics files and media files which works well for my site but when doing this the css on my the django admin page doesn't work. Here is my settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) AWS_ACCESS_KEY_ID = '*' AWS_SECRET_ACCESS_KEY = '*' AWS_STORAGE_BUCKET_NAME = 'name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-west-2' -
Django Apache 2 ModuleNotFoundError: No module named 'django'
I am trying to deploy my django application on apache2, I am on an AWS ec2 ubuntu instance. Originally I got an Fatal Python error: Py_Initialize: Unable to get the locale encoding, so I switched my python from 2.7 to 3.6 by removing my env and starting a new virtual env on 3.6, I also purged python 2.7 and 3.7 from my instance. After that I got a no module named 'Django error' in my apache. Any help is appreciated been stuck on a while with this :). <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/pydjangoenv/myproj ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/pydjangoenv/myproj/static <Directory /home/ubuntu/pydjangoenv/myproj/static> Require all granted </Directory> <Directory /home/ubuntu/pydjangoenv/myproj/myproj> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess delta_new python-path=/home/ubuntu/pydjangoenv/myproj python-home=/home/ubuntu/pydjangoenv/venv2 WSGIScriptAlias / /home/ubuntu/pydjangoenv/myproj/myproj/wsgi.py </VirtualHost> Also when I run pip3 install django my django is in Requirement already satisfied: django in /home/ubuntu/pydjangoenv/venv2/lib/python3.6/site-packages (3.2.5) -
How do I add a new field using conditional expression?
I'm currently using Django and its in-built database. Assuming in the models.py file, I have a class called User: class User(models.Model): RACE = [ ('0', 'Black'), ('1', 'White'), ('2', 'Asian'), ('3', 'Hispanic'), ('4', 'Others'), ] ASIAN = [ ('0', 'Chinese'), ('1', 'India'), ('2', 'Filipino'), ('3', 'Japanese'), ('4', 'Korean'), ('5', 'Vietnamese'), ('6', 'Others'), ] HISPANIC = [ ('0', 'Mexican'), ('1', 'Puerto_Rican'), ('2', 'Others'), ] race = models.CharField(max_length = 1, choices = RACE, null=True) sub_race = models.CharField(max_length = 1, choices = ASIAN, null=True) if race == 'Asian' else (models.CharField(max_length = 1, choices = HISPANIC, null=True) if race == 'Hispanic' else '0') I was hoping to create a field called sub_race, where its value depends on race. Nonetheless, the above method does not work. Is there a way to fix it ? -
Manipulating the data of a Model field from another model Django
I need some assistance with this if possible. So in the code below, what I tried to do is make a function that checks if there's any order in the database, if there is then I increment the value variable by 1 (and this has to happen each time a new order is made and the variable will keep getting updated, not quite sure if that's alright like that). Then I made a function to set a name for a field in my Counter model and what I want to do is go to the Order model and set that field as the value of code attribute there. To be more specific: class Order(models.Model): code = models.CharField(max_length=10, unique=True) code_year = models.IntegerField class Counter(models.Model): def count(self): value = 0 code_year = Order.objects.get['code_year'] if Order.objects.filter(code_year=code_year).exists(): value += 1 return value @property def names(self): return "P+ %s + %s" % (self.value, Order.code_year) name = models.CharField(max_length=10) value = models.IntegerField(validators=[count]) So basically, I concatinated the fields that I wanted and set that to the name field in Counter. Now I need the value of this name to bet set as the value of code on the Order model. Also quick question, will the value get … -
Django how to disappeared bootstrap alert box messages after few seconds
Before posting this question I found few solutions on stackoverflow and tried but non of them didn't work. I want the message will be disappeared after 2 or three seconds. here is my code: {% if messages %} <ul class="messages"> {% for message in messages %} <div class="alert alert-danger" role="alert"> <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </div> </ul> {% endif %} it look like this: here given below few JavaScript code which I tried for disappeared the alert box after few seconds but none of them didn't work: code1: <script text="javascript"> setTimeout(fade_out, 3000); function fade_out() { $(".messages").fadeOut().empty(); } </script> code2 <script> $(document).ready(function() { // messages timeout for 10 sec setTimeout(function() { $('.message').fadeOut('slow'); }, 10000); // <-- time in milliseconds, 1000 = 1 sec // delete message $('.alert').live('click',function(){ $('.alert').parent().attr('style', 'display:none;'); }) }); </script> code3 <script> setTimeout(function() { $('.messages').fadeOut('fast'); }, 30000); // <-- time in milliseconds </script> -
Using Ajax to update model data after javascript alert button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. I did research online, and I came across many articles talking about using Ajax, but I can't really figure it out. Can someone please help me? My code is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } Views.py: def acceptdonation(request): donations = Donation.objects.all() context = {} return render(request, 'acceptdonation.html', context) -
why html element created by javascript being appended multiple times in html page?
I have a Django project and I need to add a new email to the HTML page, however each time I click on the button, the content will be appended again, I want the information to be appended once using the function show_email(email, mailbox) , and for the buttons to be disabled if the user is on the mailbox section and enabled again when the user clicks on another button. ps. this is a one-page project. JS : document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archive').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('form').onsubmit = send_email; // By default, load the inbox load_mailbox('inbox'); }); function send_email() { const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); localStorage.clear(); load_mailbox('sent'); return false; } function show_email(email, mailbox) { let emailContainer = document.createElement('div'); emailContainer.id = "email" emailContainer.className = "row"; let recipient = document.createElement('div'); recipient.id = "email-recipient" recipient.className = " " if (mailbox === "inbox"){ recipient.innerHTML = email.sender; } else { recipient.innerHTML = email.recipients[0]; } emailContainer.append(recipient); let subject … -
Django HTML Send POST data to url as PK value when submitting
I have a form that's just a date field and submit button Forms.py from django import forms from datetime import date class DateInput(forms.DateInput): input_type = 'date' class HomeForm(forms.Form): EnterDate = forms.DateField(widget=DateInput, initial=date.today()) Because of a user request, I just want to send the data to the url like this home/2021-07-01 so I tried to do this for my html form, just stick the form.EnterDate.value in the form Action part, but it only works on the 2nd try. <form method="POST" class="form-inline my-2 my-lg-0" action="{% url 'mint-post' form.EnterDate.value %}"> {% csrf_token %} <label for="{{form.EnterDate.id_for_label}}">Enter Date</label> {{form.EnterDate}} <button class="btn btn-primary my-2 my-sm-0" type="submit">Submit Date</button> #Inital loading the form def mintHome(request): form = HomeForm() context = { 'form': form } return render(request, 'mintyHome.html', context) #after Post def mintHomePost(request, pk): if request.method =='POST': form = HomeForm(request.POST) if form.is_valid(): datePost = form.cleaned_data['EnterDate'] stringDate = datePost.strftime("%Y%m%d") context = { 'form': form } return render(request, 'mintyHome.html', context) I made an example here: https://alisayt.pythonanywhere.com/minty/home/2021-07-07 It sends the form.EnterDate.value only in the 2nd submit, but not the first one. -
How to read link from beautifulsoup output python
I am trying to pass a link I extracted from beautifulsoup. import requests r = requests.get('https://data.ed.gov/dataset/college-scorecard-all-data-files-through-6-2020/resources') soup = bs(r.content, 'lxml') links = [item['href'] if item.get('href') is not None else item['src'] for item in soup.select('[href^="http"], [src^="http"]') ] print(links[1]) This is the link I am wanting. Output: https://ed-public-download.app.cloud.gov/downloads/CollegeScorecard_Raw_Data_07202021.zip Now I am trying to pass this link through so I can download the contents. # make a folder if it doesn't already exist if not os.path.exists(folder_name): os.makedirs(folder_name) # pass the url url = r'link from beautifulsoup result needs to go here' response = requests.get(url, stream = True) # extract contents with zipfile.ZipFile(io.BytesIO(response.content)) as zf: for elem in zf.namelist(): zf.extract(elem, '../data') My overall goal is trying to take the link that I webscraped and place it in the url variable because the link is always changing on this website. I want to make it dynamic so I don't have to manually search for this link and change it when its changing and instead it changes dynamically. I hope this makes sense and appreciate any help I can get. If I manually enter my code as the following I know it works url = r'https://ed-public-download.app.cloud.gov/downloads/CollegeScorecard_Raw_Data_07202021.zip' If I can get my code to pass that exactly … -
filtering items on current page
how can I apply sorting to the current page, if I am on a page of a certain category and want to sort by price, it will return me to the page with all products sorted by price template for main page of store <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="">default</option> <option value="price">price: $ - $$</option> <option value="-price">price: $$ - $</option> <option value="collection">collection</option> <option value="-collection">collection2</option> </select> <input type="submit" class="d-none" value="submit"> </form> template for category {% for cat in shoes_subcategories %} <li><a href="{% url 'shop_category' cat.slug %}">{{ cat.name }}</a></li> {% endfor %} views class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = True model = Item def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) ***context*** return context def get_ordering(self): return self.request.GET.get('orderby', ) class ShopBySubCategory(Shop, ListView): def get_queryset(self): return Item.objects.filter(sub_category__slug=self.kwargs['slug']) class ShopByBrand(Shop, ListView): def get_queryset(self): return Item.objects.filter(brand__slug=self.kwargs['slug']) -
TemplateDoesNotExist for base.html of each app
Here's the structure of my project: project_name/ app1/ templates/ base.html app1/ index.html app2/ templates/ base.html app2/ index.html app3/ templates/ base.html app3/ index.html And in settings.py: TEMPLATES = [ { ... 'DIRS': [BASE_DIR / 'templates/', ], ... }, ] and BASE_DIR is defined as (the default for Django 3.2 on Windows): Path(__file__).resolve().parent.parent None of my index.html files are able to locate their own base.html using {% extends 'appX/base.html' I get TemplateDoesNotExist error. What I'm missing? -
How can I let my users send emails from their gmail account through my django application?
I am building a Django App and I would like users to be able to trigger sending an email from my app to an email they chose using their gmail account as a sender. I know this is doable for one users only by changing the setting in django, but can I do it for multiple users? -
Fetch related and inversely related objects at once - Django
I'm trying to fetch objects in my database using one line with select_related(). Here is my models: class Asset(models.Model): """Store information about an asset.""" is_active = models.BooleanField(default=True) rank = models.PositiveIntegerField() class AssetMarketData(models.Model): """Store market data of an asset.""" asset = models.OneToOneField(Asset, related_name="market_data", on_delete=models.CASCADE) class AssetQuote(models.Model): """Store quotes of an asset.""" asset = models.ForeignKey(Asset, related_name="quote", on_delete=models.CASCADE) I want to retrieve all Asset objects using select_related() like this: assets = Asset.objects.order_by('rank').select_related('market_data', 'quote') However, this is not possible because quote is a reverse relationship. I can access the quotes using: assets[0].quote.all() But I can only do it for one Asset at a time which I want to avoid. prefetch_related() can only retrieve inversely related objects so it doesn't help. So I would like to know how to retrieve all related AssetQuote when I select all Asset objects. -
image corrupted after reading image file in chunk
so i am trying to ready image file form django request in chunks, the django filehandler chunks method does not work well for me, so i created a custom on, it works but the end product wasnt what i was expecting, so after reading the files in chunks and putting them together somehow the image get corrupts and i dont have any solution for it. def process_download_with_progress(self, image_file, length): process_recoder = ProgressRecorder(self) print('Upload: Task Started') fs = FileSystemStorage() buffer = io.BytesIO() chunk_size = 0 for chunk in read_chunk(image_file.file, length): chunk_size += 1 buffer.write(chunk) process_recoder.set_progress(chunk_size, length, description=f'uploaded {chunk_size*length} bytes of the file') buffer.seek(0) image = ImageFile(buffer, name=image_file.name) fs.save(image_file.name, content=image) return 'Done' def read_chunk(file_object, chunk_size=125): while True: file = file_object.read(chunk_size) if not file: break yield file so this my code, any help will be appreciated, thanks. -
I'm trying to use tkinter in python but I'm getting an import error [closed]
I'm trying to use tkinter in python but I'm getting an import error.i installed tkinter but did not import tkinter -
function to check if an object exists Django
This is all a little too confusing for me, what I need to do is make a function to check if an object exists on the database (so it's already been created), and if it does, get its ID, store it on a field in a model, lets say value, and then I need made a function called get_name, where i concatinate what I need to do, store it to the field name. Now I need to make it so the code attribute on Order model, is equal to the name attribute. Any suggestions would be welcomed. Also some pointers on weather the code is okay because I wasn't sure how to test it after writing it. What I've done so far: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField class Counter(models.Model): def count(self): value = 0 code = Order.objects.get['code'] if Order.objects.filter(code=code).exists(): value += 1 return value def get_name(self): return str('P' + self.value + Order.code_year) name = models.CharField(max_length=10, validators=[get_name]) value = models.IntegerField(validators=[count]) -
ImportError: attempted relative import beyond top-level package in django
enter image description here enter image description here enter image description here I am trying to use one app model function in other app model function but it show an ImportError. -
How to serve image files from MongoDB in Django
I am building a Django application that stores image files in a mongodb GridFS. I use Djongo to work with the database and followed this example https://www.djongomapper.com/using-django-with-mongodb-gridfs/ to store the images to the DB. So now I can, currently through the admin page, upload images to the DB, which need to be accessed using a URL like this: http://127.0.0.1:8000/files/60fae4884db41b9ad761c8b0 Now I have this in the urls.py urlpatterns = [ ... path('files/<str:fileid>', views.files, name='files'), ] But in View file I don't know how to retrieve the image from the DB: @login_required def files(request, fileid): return response I searched the documentation of Djongo and Django but couldn't find an easy way to do it, any help is appreciated. Note: In the main DB collection only the image file name is stored. In gridfs collection 'files' an ID (the one in the URL), the image name (the only link to the main collection) and other details are stored. And in the 'chunks' collection there is an ID , a files_ID (foreign key to the files ID) and the binary data. -
Django - annotation produces duplicate joins
The following annotation produces duplicates .annotate( **{ f"{key}_bundle_id": F('item__child_link__parent_item__bundle__id'), f"{key}_bundle_name": F('item__child_link__parent_item__bundle__name') } ) Both of these annotations join across a many to many table to get the id and name of the joined table. I would expect this to produce a join, and select both the id and name from the join. Instead it duplicates the join and selects the id from 1 set and the name from the other. Is there a solution to work around this or do annotations always produce their own joins? Here's the sql it generates: SELECT T8.id as x_axis_bundle_id, T12.name as x_axis_bundle_name .... INNER JOIN "item" ON ("gmdts"."item_id" = "item"."id") INNER JOIN "link" ON ("item"."id" = "link"."child_id") INNER JOIN "item" T8 ON ("link"."parent_id" = T8."id") INNER JOIN "bundle" T9 ON (T8."id" = T9."item_id") INNER JOIN "link" T10 ON ("item"."id" = T10."child_id") INNER JOIN "item" T11 ON (T10."parent_id" = T11."id") INNER JOIN "bundle" T12 ON (T11."id" = T12."item_id") -
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter?
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter? Views: class GenreViewSet(ModelCVDViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('name', 'slug') search_fields = ('name', 'slug') lookup_field = 'slug' class TitleViewSet(viewsets.ModelViewSet): queryset = Title.objects.all() serializer_class = TitleSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('genre__slug', 'category__slug', 'name', 'year') search_fields = ('=genre__slug', '=category__slug', 'name', 'year') -
Cascade delete of model with GenericForeignKey without using GenericRelation
I'm creating a reusable django app which includes a model with GenericForeignKey which I need to be cascade deleted. This model may be attached to any other. I have no control over target model class as it is outside of the app. This means I can not add GenericRelation field to it and can't force user to add it as target might be in another third-party app. Assuming we have such models (having NO control over Post and PostGroup): class Tag(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() object = GenericForeignKey() class PostGroup(models.Model): title = models.CharField(max_length=255) class Post(models.Model): title = models.CharField(max_length=255) group = models.ForeignKey(PostGroup, on_delete=models.CASCADE) Is there a way to delete Tag in case of PostGroup queryset is being deleted? E.g. not only post_group.delete() but also PostGroup.objects.delete(). -
how can I add a django array element into a js array using an if condition
I have a Django project with data being submitted by form , I am trying to use chart.js to display the data. I need to check whether an array exists() if so then add an item to 'labels' array in 'mycharts.js' . Heres what I have so far django views.py ing1 = request.POST.getlist('ingredients1') ing2 = request.POST.getlist('ingredients2') ing3 = request.POST.getlist('ingredients3') ( I've passed the above into my context ) mycharts.js var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: {chart.js labels: ['{{ing1.0}}', '{{ing2.0}}', {% if ing3|length > 1 %} '{{ing3.0}}', {% endif %}], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], (etc...) if I take out the if statement inside of 'labels' array , then it shows the 'ing1' and 'ing2' headings , but I can't get it to work with this if statement , whats the correct way of doing it. -
Django rest framework and react - CORS issue only on same URLs
I'm using react on the frontend side and Django on the backend. I using corsheaders.middleware.CorsMiddleware ALLOWED_HOSTS = ["127.0.0.1", "localhost"] and for some URLs I have no issue sending a request and for others, I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/actions' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. error. Working URL: http://localhost:8000/api/profiles/auth-data Not working URL: http://localhost:8000/api/actions method: GET settings.py: """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path from corsheaders.defaults import default_headers # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["GH_BE_SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True PROD = False ALLOWED_HOSTS = ["127.0.0.1", "localhost"] CORS_ALLOW_HEADERS = list(default_headers) + [ "businessId", ] # Application definition # TODO need to check security in PROD ['corsheaders'] … -
How can I query data from two tables in Django, when some of the data is conditional
We have multiple data tables, the 'main' one is Player with the primary key Player Name, which is a foreign key to a few other tables, and a foreign key Team Name which is a foreign key to a table called Team, with Team Name being that primary key. We have this query in SQL: SELECT p.TeamName, AVG(b.G) as avg_games_for_team, AVG(b.OPS) FROM Players as p JOIN batter as b ON p.PlayerName = b.PlayerName GROUP BY p.TeamName ORDER BY avg_games_for_team LIMIT 15; And we can't translate this into Django ORM. I know you're supposed to give some of the code you've tried, but we really aren't able to put anything down into paper. The only thing we can get is something like Players.objects.select_related('Teams').get(TeamName).filter(...) using this as a start. We also know to use .annotate() but can't discover where or how. Thanks! -
django-js-routes resolver not finding url
using https://pypi.org/project/django-js-routes/ along with Vue2 and Inertia.js the resolver.js file is not finding the routes i have included in my JS_ROUTES_INCLUSION_LIST application urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.index, name='index'), path('article/<int:id>/', views.articleDetailsPage, name='article'), ] urlpatterns += staticfiles_urlpatterns() Vue template attempting to call route <template> <div> … <div class="sm:p-6 sm:flex sm:flex-col"> <div v-for="article in articles" :key="article.id" class="sm:text-xl"> <inertia-link :href="route('article', article.id)"> {{article.title}} </inertia-link> </div> </div> … </template> <script> export default { props: [ 'articles', 'num_articles' ], methods: { 'page_name': function() { return 'Articles Page' }, 'route': function(...args) { return window.reverseUrl(...args); }, }, } </script> project urls.py #add articles app urls urlpatterns += [ path('articles/', include('articles.urls')), ] project settings.py # Django JS Routes Inclusion List JS_ROUTES_INCLUSION_LIST = [ 'trends', 'articles:index', 'articles:article', ] I have also tried a settings.py where the list only included the app name, articles, whose urls are not being found error returned in console URL 'article' was not found. The error message is being returned by the django-js-routes resolver.js file