Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use node modules with Django?
I wish to use date-fns in my django project but not entirely sure how to proceed - I cannot rely on a CDN and need to somehow get it installed. I have run npm init in my root folder followed by npm install date-fns. This generated a node_modules folder and a package.json file. Not entirely sure how to proceed after this. What are the necessary steps? Do I just use <script src="{% static 'node_modules/date-fns' %}"></script> in my base.html file? -
Exclude a file from Django's autoreload in runserver
I have a particular module that takes a little long to load, and is unlikely to change when running my Django server (let's call it badmodule/badfile.py). However, when I run python manage.py runserver, the Django server will autoreload when any file changes (including badmodule/badfile.py). I'd like to keep the autoreload behavior, but just exclude it from watching anything in badmodule. -
Make POST request to my index route fetch API
In my "/" route I have a form with an input textarea field, when the form is submitted, it should dynamically show the content of the textarea, without reloading the page. I'm trying to implement this with fetch API on my Django app. I'm working on http://127.0.0.1:8000/ I have two problems: With the code down here, the console.log doesn't print anything, and If I change response.json() for response.text(), I'm getting the whole html code, not the thing I want to fetch I'm getting Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 2 in my js console when posting the form This is my js code: document.querySelector('form').onsubmit = (event) => { fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "X-Requested-With": "XMLHttpRequest", "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { // Print result console.log(result) let div = document.createElement('div') div.innerHTML = (result.body); div.style.cssText = "border: 1px solid lightblue; padding: 10px; margin: 5px;"; document.querySelector('#posts').append(div); document.querySelector('#new_message').value = "" }); event.preventDefault(); } The POST method is being sent to the server, but the console throws this uncaught error. #new_messageis my textarea field id -
Gmail Schedule Send Email in Django
I want to mimic the functionality that Gmail has, where you can choose to send an email at a certain time (maybe 3:34 am tomorrow) in Django. I looked at something like django-crontab (https://pypi.org/project/django-crontab/). I came up with an idea to use django-crontab to achieve this: Make a crontab that runs every minute Every minute, check if there are any emails that need to be sent Send out those emails This feels a bit hacky and over-engineered. Is there a better way? Thanks! -
Multiple <slug:slug> urlpatterns on the root
Manual type in of URLs are super important for the website I'm working on. Almost all traffic will come from people going directly to domain.com/some-string/. Minimal traffic will come from search engines. This means making URLs as easy to remember as for people is very important. Is there a way to have multiple path('<slug:slug>/', ...) URL patterns in the root directory? For example my models: from django.db import models class Category(models.Model): class Meta: verbose_name_plural = 'categories' title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) description = models.TextField() parent = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) def __str__(self): return self.title class Widget(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) # and various other parameters specific to Widget category = models.ForeignKey('Category', on_delete=models.PROTECT, related_name = 'widgets', null=True) def __str__(self): return self.title And my views: from django.views.generic import ListView, DetailView from .models import Category, Widget class WidgetDetailView(DetailView): model = Widget slug_field = 'slug' slug_url_kwarg = 'slug' class CategoryListView(ListView): model = Category slug_field = 'slug' slug_url_kwarg = 'slug' And my URLs: from django.urls import path from .views import WidgetDetailView, CategoryListView urlpatterns = [ path('<slug:slug>/', WidgetDetailView.as_view(), name='widget-detail') path('<slug:slug>/', CategoryListView.as_view(), name='category-list') ] But obviously this works for domain.com/widget-slug/ but not domain.com/category-slug/ because only the first URL pattern gets called and results in … -
Is there a way for URL to be only accessed through the same origin
I have a URL in my Django application. url(r'^settings/$', views.SettingsView.as_view(), name='settings') This url is just a TemplateView that shows an HTML page. I don't want this page accessed to the public. Is there a way for only the application can access it? For example, the application can call this URL and retrieve data, but any outside user can't. Is there a way to do this? -
Django if and elif statements not working (Integer field)
So I'm in development and I have an IntegerField representing the followers of a user and I'm trying to make (within the templates) different things happen visually depending on the amount of followers in this field. It isn't working though? It only works if all the user.followers in question have the condition instead of a single one This is generally what I'm trying to do {% if user.followers < 50000 %} {% include blahblahblah %} {% elif user.followers >= 50000 %} {% include blehblehbleh %} {% elif user.followers >= 100000 %} {% include bleubleubleu %} {% else %} {% endif %} I had this problem when trying to use the profile photo inside a button as the background image, it would just use the most recently added profile's, profile photo, over and over again for every button background image. Is there a way I can make a list of say 20 items, and just manually go through writing if statements for each item in the list? -
How to display all the available results to a search query in HTML
I have this search engine in django that when you look for let's say "release date" only displays one result with that date, but not all the available results with it. I was wondering how I can manage that, so that if I look for something that has more than one result, it will show all of them and not a random unique result. This is the search function in my view: def films(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() if len(results): for result in results: movie_data = { 'Title' : result['title'], 'Release_date': result['release_date'], 'Director' : result['director'], 'Producer' : result['producer'], 'Description' : result['description'] } movies.append(movie_data) else: message = print('No results found') context = { 'movies' : movies } return render(request,'core/films.html', context) This is my html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | Movies</title> <link rel="stylesheet" href="{% static 'core/films.css' %}"> </head> <body> <div class="layer"> <div class=" header"> </div> <div class="wrap"> <form action='/films' method="POST"> {% csrf_token %} <div class="search"> <input type="text" name="search" class="searchTerm" placeholder=" Type movie name"> <link … -
Django permissions not working properly even when adding permissions
Python 3.7, Django 3.0 Hello everyone, I'm facing an issue with Django permissions. I have a simple Article class as a model, as shown below: class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() active = models.BooleanField() borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) class Meta: permissions = [("can_mark_owned", "Set article as owned")] In my views.py, I have a view that's supposed to be available for users with the "can_mark_owned" permission only. Shown below: class AssignOwnerLibrarian(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): permission_required = ('article.can_mark_owned') template_name = 'articles/article_assign_owner.html' form_class = AssignArticleOwnerForm queryset = Article.objects.all() My problem is that I can only access this view when I'm logged in as a SuperUser, not with a user who has the permission(added the permission through the Admin page), where I get 403 Forbidden. In my testing file, I have the following code: class RenewBookInstancesViewTest(TestCase): def setUp(self): # Create a user test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user2.save() permission = Permission.objects.get(name='Set article as owned') test_user2.user_permissions.add(permission) test_user2.save() test_user2 = get_object_or_404(User, pk=test_user2.id) print(test_user2.has_perm('article.can_mark_owned')) # returns False For some reason the print on the last line returns False. Help would be highly appreciated, I've spent multiple hours now on this problem. Thank you! -
How to implement product variations on the same product as cookie in Javascript?
Working on an eCommerce app and I'm now able to add products to a shopping cart using Pure JS. For unauthenticated users, I'm storing the product details in a cookie/Local Storage and reading it in Django to display on the cart page. Here is what the cart cookie/LS looks like with productIds 1 & 2 and no product variation cart = {1: {'quantity': 2}, 2: {'quantity': 4}} I now want to add a product variation for size and the ability to add to cart the same product with different variations Desired output cart = {1: {'quantity': 1, 'size': 'S'}, 1: {'quantity': 1, 'size': 'M'}} Real output. The last is overwriting the first cartItems = {1: {'quantity': 1, 'size': 'M'}} Code var cart = JSON.parse(localStorage.getItem('cart')) if(cart == undefined ) { cart = {} localStorage.setItem('cart', JSON.stringify(cart)); } //productId is recorded on button click //size is recorded on button click if (cart[productId] == undefined) { cart[productId] = {'quantity': 1} cart[productId]['size'] = size } else if (size != cart[productId]['size']) { //If new size is added cart[productId] = {'quantity': 1} cart[productId]['size'] = size } else { cart[id]['quantity'] += 1 } localStorage.setItem('cart', JSON.stringify(cart)) -
How to check routes on template?
Does anyone know how to check if a template is being accessed through a url route with the django template language? Here is my situation: There's this template article.html, that shows all posts of a blog when accessed through blog-home url route, and that also shows only posts of a given user through user-posts url route. This template works like that because what defines which posts will be shown are the classes in views.py. That being said, here is what I tried to do: (I know its wrong) {% if url == 'user-posts' %} "Some HTML h1 tag I want do be shown only when this template is accessed via 'user-posts' url" {% endif %} How would be the correct way, if there's any, to write this if statement? -
how to save CustomUser model to another model data
here is my code at users/admin.py, from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from store.models import Customer from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] admin.site.register(CustomUser, CustomUserAdmin) I have table on store/models.py , class Customer(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True,unique=True) #name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) def __str__(self): return self.user.username Now can anyone please suggest me how to create a customer instances in user/admins.py or save data to customer table. -
how to take input from one page and send them into another page in django
I'm fairly new at this. I'm trying to build a report page in iframe according to user requirement user can create report with src, width and height ...and i successfully done this...i am able to create the report now i want this created report name will be show in the dropdown menu and when the user click on report name then user can see the report and the name of the report will add on dynamically in the dropdown.... i'm waiting for response ..here i'm going to share the code what i have done ... i would say one more thing i don't want to add these data (Src,width ,hesight,name of the report) in the data base ...is that possible to create report and get the same report when i will click on the report name. index.html <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% if name %} <li> <a href="{% url 'report:add' %}">{{name}}</a> </li> {% endif %} </ul> </li> reportform.html <form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal"> … -
Git commit from a bisect
I have only ever used 'git add .' for this project, but somewhere along the line I started getting the strange "modified content, untracked content" error on one of my subdirectories (called users). Other stackoverflow answers didn't work for me. I used checkout to go back through previous commits, but the buggy/untracked subdirectory didn't change with the rest of the directory. I ended up making manual changes to it and then running 'git checkout master' to make sure everything else was back where it started. Git is saying that I'm bisecting, and it won't let me commit. I looked over stackoverflow answers, and tried some of the following commands: 'git pull': There is no tracking information for the current branch. Please specify which branch you want to merge with. 'git pull origin master': fatal: 'origin' does not appear to be a git repository 'git branch --set-upstream-to=origin/master master' error: the requested upstream branch 'origin/master' does not exist hint: hint: If you are planning on basing your work on an upstream hint: branch that already exists at the remote, you may need to hint: run "git fetch" to retrieve it. hint: hint: If you are planning to push out a new local … -
Sign Up Form Submission Producing a Data Breach pop up in Chrome
I built a django app, but I've run into an issue with my signup form. Whenever a user submits the form on chrome a warning pops up referencing a data breach. It's the same warning referenced here. I can see that that the warning is generated by chrome whenever the user's data is exposed by the web app. However from reading the documentation on Django's default user class it seems like the password should be encrypted. My user class is inheriting from the default user class so I'd think I'd be fine here. This is my User class: class User(AbstractUser): class Meta: db_table = 'auth_user' This is my Form Class: class UserRegisterForm(forms.ModelForm): email = forms.EmailField(label='Email Address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError('emails must match') email_queryset = User.objects.filter(email=email) if email_queryset.exists(): raise forms.ValidationError('This email is already being used') return super(UserRegisterForm,self).clean(*args, **kwargs) And this is my Form: <form method="post" action="{% url 'sign-up' %}"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="signup"> <input type="hidden" name="next" value="{{ next }}"> </form> Any ideas … -
Django: How to mangle through relations
I have an instance of ModelA and want to query all instances of ModelC which are related to ModelA through ModelB. ModelA -> all ModelB instances with FK rel_a = ModelA -> rel_c.all() class ModelA(models.Model): # fields pass class ModelB(models.Model): rel_a = models.ForeignKey('ModelA', ...) rel_c = models.ManyToMany('ModelC') # more fields class ModelC(models.Model): # fields pass I know how I would do this in SQL but I really do not get how I should unmangle these relations -
Using beautiful soup in Django
How would I use information captured in a Django model field to retrieve data with beautiful soup and display it in a Django template -
Integrating bootstrap template with django app
I'm working on a django web app and I wanted to integrate this bootstrap template (https://startbootstrap.com/previews/sb-admin/) to my django web app. Is it possible and if yes could you please detail to me the steps to do that. I'm sorry if my question is not detailed I'm still a newbie and I really need to do this. Thanks in advance -
Front-end, back-end or database: where should I alter data to generate my components?
I'm somewhat new to programming. We're creating an application using React, Redux and Django Rest Framework. The main goal of this application is to present educational data in a nice and comprehensible way. I'm using Nivo to create all sorts of charts. Right now we're creating a simple line chart to show the score every school reached in a certain national test here. Nivo needs the data to generate the charts in this JSON format: [ { "id": "japan", "color": "hsl(175, 70%, 50%)", "data": [ { "x": "plane", "y": 52 }, { "x": "helicopter", "y": 110 }, { "x": "boat", "y": 210 }, ] } ] The data I have is something like this: school_id school_type year grade first_application_score second_aplication_score avg 1 public 2015 3 6.5 7.2 6.9 1 public 2016 4 7.9 7.1 7.5 2 private 2015 5 5.5 6.5 6.0 My question here is: where should I alter the data to create the chart's data? In my actual level of understanding web programming, I could use the following strategies: I can create new tables in the database using SQL. This tables will have the x and y values, so the API in Django will do no calculations, just … -
Don't want to use the Django admi template
I want to render my own html page which execute python script and output on my html page instead of using the django web template where I would have to edit the settings.py or add App. All the same I want to be using the django web framework. How should go by it? -
Good way to run ONE indefinite process on Django Framework
I'm building a web app using a Django framework. There isn't much user interaction with only a few static links, navbar, and a few plots which come from my app itself. The main part of the app comes from a python script which reads data from an external source, does some data processing on it, and then writes to my django database. Then after writing to the database a new page is created with information about the database entry. Note that there is no user interaction so no starting or stopping the task. I want the task to run in the background 24/7. Thus far I've looked into celery and django-background-tasks. Celery seems like a bit much for my use case. I don't think I need a broker service as I just want to run 1 task which the user will never interact with. Additionally, I don't need multiple workers. Django-background-tasks seems like a good lightweight alternative but it seems it does not support indefinite tasks without having to refresh the task every once in a while (ideally I don't want this). Is there a tool that is better suited for this use case? Or am I just completely misunderstanding … -
Simple Tree Using Django and CSS
I have a queryset which returns [{'id': 1, 'username_id': 32, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 2, 'username_id': 33, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 3, 'username_id': 34, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'A'}, {'id': 4, 'username_id': 35, 'schoolCode_id': 2, 'classVal_id': 'CL002', 'class_section': 'B'}, {'id': 5, 'username_id': 36, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 6, 'username_id': 37, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 7, 'username_id': 38, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'C'}, {'id': 8, 'username_id': 39, 'schoolCode_id': 2, 'classVal_id': 'CL003', 'class_section': 'D'}, {'id': 9, 'username_id': 40, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}, {'id': 10, 'username_id': 41, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}, {'id': 11, 'username_id': 42, 'schoolCode_id': 2, 'classVal_id': 'CL008', 'class_section': 'A'}] I would like to display a tree structure in my template like <classVal_id 1> <class_section> <Username_id 1> <username_id 2> <class_section B> <Username_id 3> <Username_id 4> <classVal_id 2> ............... I tried using "ul" and "li" using nested for loop. But somehow got stuck and could not print the values. I tried django-treebeard but seemed a little complicated. Is it possible to print the data using the queryset ? I want to use the snip on the url https://bootsnipp.com/snippets/ypNAe to print my data. Any help would … -
How to pass logged user's id to CreateView
I can't figure out how to pass current user's name as the post's author automatically. If add the author fields = ['headline', 'quote', 'author'], the dropdown menu is shown and passed, but I need the logged user's name to be the default. my view: class PostCreate(CreateView): model = Post user = User fields = ['headline', 'quote'] success_url = '/index' template_name = 'base_homepage.html' @login_required() def get_context_data(self, **kwargs): kwargs['latest_posts_list'] = Post.objects.order_by('-id') return super(PostCreate, self).get_context_data(**kwargs) my model: class Post(models.Model): _id = models.ObjectIdField headline = models.TextField(max_length=255) quote = models.TextField(max_length=140) creation_time = models.DateTimeField(editable=False).auto_now_add author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.headline[:25] -
Problem with Django 3.1 include() function when defining urls for learning_logs web app from Python Crash Course
I get a type error when trying to load my website. path('login/', {'template_name': 'users/login.html'}, name='login') File "/Users/jakeziegelbein/Desktop/crashCoursePython/learning_log/11_env/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). Here is the code from the root urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] Code from the urls.py file from the users app. """Defines URL patterns for users.""" from django.urls import path, include from django.contrib.auth import login from . import views app_name = 'users' urlpatterns = [ # Login Page.dc path('login/', login, {'template_name': 'users/login.html'}, name='login') ] I don't know why I'm getting the error mentioned above. I looked at the django url documentation and it seems I'm writing my code accordingly. Any ideas on the source of the error? -
Which is the best Front-End language combination with a Django application? [closed]
Can you suggest the best front-end language to be used with a Django project. Is it (Angular, React or Vue.js) or the inbuilt Jinja2 is enough? Does it depends case to case, if yes, for what different scenario's they are most suitable to use?