Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing data and charts corresponding to buttons in Django frontend
I am taking 15 files from users as input and I am running an algorithm in views.py on those files. I make lists of all the information which I want to show on dashboard for all 15 files. Now on the frontend, I want to give users 15 buttons corresponding to each file and onclicking each button, respective data and charts must be shown. I am using chart.js for charts but I am not sure how I can add the functionality of showing charts and data from clicking corresponding buttons. -
Django .save() method is not appearing in Visual Studio Code
I am relatively new to python and currently exploring django. I am facing this problem in Visual Studio Code where the save() method is not reflected in my main app. The method reflects in other apps and I am not sure how to go about solving this. The codes are situated in the views.py of the respective applications. For this image, form.save() does not return any method which results in not saving any information. This is situated in my main app For this image, form.save() returns a method that allows the saving of information. This is situated in my register app. -
Create A model In Django Which Accept Value For A Specific Choice
I Am Working In Django & DRF(Django-Rest-Framework) In Which I have A Choices In which if Video Is Paid Video , Now I'm creating another Model which Stores all Paid Video's Information from django.db import models from userapi.models import User # from taggit.managers import TaggableManager import datetime class post(models.Model) : Public = 'Pub' Private = 'Pri' Paid = 'Paid' selection = [ (Public, 'Public'), (Private, 'Followers'), (Paid, 'Paid'), ] username = models.ForeignKey(User, on_delete=models.CASCADE) post_description = models.TextField(max_length=500) post_timestamp = models.DateTimeField(auto_now = True) post_selection = models.CharField(max_length=10,choices=selection) def __str__(self): return self.username This is userpost.py now I want to create model named paid_videos in which If post_selection is Paid then It takes amount of it I'm NEW TO DJANGO -
Pagination on Pandas Dataframe in Django
I Have data in Postgresql and getting that data through ORM query into my dataframe named as data, My view.py is given below: view.py from operator import index from django.shortcuts import redirect, render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.shortcuts import render from bar_chart.models import AirQuality from django.core.paginator import Paginator #from django.views.generic import TemplateView #from django.shortcuts import render #from django.db.models import Sum from django.db.models import Avg from django.http import JsonResponse from bar_chart.models import AirQuality #from .models import * import pandas as pd # Create your views here. def authenticate(request): count= User.objects.count() data= AirQuality.objects.all().values() print(data) df= pd.DataFrame(data) df1= df.tail(10) mydic = { "df": df1.to_html() #"count": count } return render(request, 'auth_home.html', context=mydic) #, {'count':count} I want to render those pages of pandas dataframe (All data not just the tail of data) in my auth_home.html. What would be the way out (code) to apply django pagination on my pandas dataframe? -
Django: How to use same abstract class twice with same fields but different names?
I have an abstract model called Address with fields such as address_line, postcode etc. Now I want to create a model Person which has multiple types of addresses like residential_address, office_address etc. How can I achieve that in Django? My Address model: class Address(Model): address_line_one = CharField( blank=True, null=True, max_length=255, ) address_postcode = CharField( blank=True, null=True, max_length=50, validators=POSTCODE_VALIDATORS ) class Meta(GlobalMeta): abstract = True My Person class: class Person(Address, Model): name = CharField( blank = True max_length = True ) class Meta: app_label = "person" ) forms class PersonForm(forms.ModelForm): class Meta: model = Person exclude = [] widgets = {} form.html <div> {% form.name %} </div> -
Bootstrap Modal doesn't popup
Below is the code which I copied from the Bootstrap website. I can't understand why is it not working, even though it works on its website as a demo. <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> <!-- Modal --> <div class="modal" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Below is my script and link tags for bootstrap <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> How should I debug this? -
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. Django ecommerce website ajax
views.py def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) return JsonResponse('Item was added', safe=False) cart.js function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:',data) }); } script getCookie, I heard that this script can solve this problem. But, it didn't help. function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string besgin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); Still Error: POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) updateUserOrder Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 -
Django email sending but not received
In my django project I am trying to send a message. There is a message in the sent ones, but I do not receive it. The letter is not in spam. This my settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 I tried to do what is written here Django email sending, but not received -
How can I dynamically reference the fields in a Django query set object in a template?
I have a model that is referenced by a generic ListView, and feeds into a template. Attempts to create a table in the template give me a TypeError: not iterable - what am I doing wrong? Sample code Class bookmodel(models.Model): Book = models.CharField(max_length=255) Author = models.CharField(max_length=255) Views Class bookview(generic.ListView): model = bookmodel template = “books.html” Which generates an object_list something like: <Queryset [<bookmodel: Grapes of Wrath >, <bookmodel: I, Robot>]> The template is laid out as follows: {% extends ‘base.html’ %} {% block content %} <table> <thead> <tr> <th> book </th> <th> author </th> </tr> </thead> <tbody> {% for object in object_list %} <tr> {% for field in object %} <td> {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endblock %} But this fails with the aforementioned error. -
What is the error in my syntax of javascript in django website?
See i am making a basic e commerce website in django for my django practice and i dont know javascipt really well. Can you please find problem in my javascript. Code in my checkout page's checkout.js checkout.js Error coming in this part image My views.py checkout function views.py Please help me out -
config sendgrid and django
hello despite my trying I can not configure sendgrid here is the code thank you for your help SENDGRID_API_KEY = 'password' EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER='API Key ID' EMAIL_HOST_PASSWORD=SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Python ecommerce <API Key ID>' BASE_URL = 'sitename' DEFAUT_FROM_EMAIL='API Key ID' MANAGERS = ( ('mohamed aymen hssen', "API Key ID"), ) ADMINS = MANAGERS error HTTP Error 401: Unauthorized -
python How to force download generated pdf?
I am using `xhtml2pdf` library in a django project to generate pdf file from html, and I would like to know how to force download the generated pdf to the server. If you need more information, please comment below. Thank you in advance. -
Post a JSON object on conditional input -- Django Restframework
Iam working on Django Restframework. I want to POST into an API to create an object. The problem is the condition I want to make, is itself in the POST data. For example, I have 5 fields: Name Lastname Email is_member membership_id I want to create a membership_id, if the user sends "is_member== True" while data posts. Problem: The data does get posted but the "membership_id" is blank. And no errors received. I could conclude that the reason is the "if/else" condition is triggered before all the fields are set. I tried to give the "if/else" condition when the function starts Inside the object which save the entry ie user_object. But nothing works Iam until here def create_user(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') is_member = request.POST.get('is_member') # default is = False category = request.POST.get('category') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) if is_member == True: membership_id = hashString(str(timestamp)) else: membership_id = "" try: user_object = MasterUser( firstname = firstname, lastname = lastname, email = email, is_member = is_member, membership_id = membership_id ) user_object.save() return HttpResponse('User successfully created') Is it possible or do I have to look out for some different apporach. Any ideas are welcomed! Thanks. -
Test failed for Date of Birth
I am a beginner in python-django coding. Currently I'm at the challenge part of https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing. My tests are going well except for def test_form_date_of_death_initially_set_to_expected_date(self). The error is AssertionError: datetime.date(1900, 1, 1) != datetime.date(2020, 6, 11) From what I understand the 1900,1,1 is the date that return to me after the function is done checking. But the problem is I have no idea how this date is coming out. I check thru my files and I cant see any codes setting it as 1900, 1, 1. So is this a default date if it is not set? If it is default by nature, how come i set test author date of death, it is still coming out 1900, 1, 1. Appreciate if anyone could help me. Thanks class AuthorCreateTest(TestCase): def setUp(self): # Create a user test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() # Create a book test_author = Author.objects.create(first_name='John', last_name='Smith', date_of_death='2006-06-11') def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('author-create')) self.assertRedirects(response, '/accounts/login/?next=/catalog/author/create/') def test_forbidden_if_logged_in_but_not_correct_permission(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 403) def test_logged_in_with_permission(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 200) def test_uses_correct_template(self): login … -
trying to override allauth templates on a Django 3.2 app recognized in python 3.9
I'm working with ALLAUTH on Django 3.2. Most solutions I found are for Django 1, so I'm hoping to find something more up-to-date here. I have the module/app installed, but I'm having problems overriding the templates with my own. In settings.py: INSTALLED_APPS = [ ... 'Landing.apps.LandingConfig', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Already defined Django-related contexts here # `allauth` needs this from django 'django.template.context_processors.request', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] Research Urls #The Project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('Landing.urls')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] Landing/urls.py #app-level urls from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('login/', views.LoginView.as_view(), name='account_login'), path('signup/', views.SignupView.as_view(), name='account_signup') ] Home.html <...> <body> <H1>This is the homepage</H1> <p><a href="{% url 'account_login' %}">login</a></p> <p><a href="{% url 'account_signup' %}">Create Account</a></p> </body> <...> Note: account_login and account_signup are both in Landing urls and Landing Views Landing Views … -
Design decision for deleting Django fields
I have a preexisting Postgres Database connected with the Django app. I want to delete a field in one of my Django models. I have 2 ways to do this: Manually delete the field from the auto generated files created during the previous migrations which django created -> Drop the column manually in the preexisting database -> Run migration again with the new migrations. Run makemigrations again which will cause django to create another migration file to drop the aforesaid field -> Migrate the preexisting database with the new migrations. Could anyone advice me what is the best practice to remove the field? Cheers, Fellow StackOverflower -
How to reposition form button in a Django template
I have a Django template that renders a form. The code is: {% block body %} <h3> Create Listing </h3> <table> <form action="{%url 'create' %}" method="POST"> {% csrf_token %} {{ form.as_table }} <input type="submit" value="Create Listing" class="btn btn-primary"> </form> </table> {% endblock %} Note: I'm using <table> to left justify the input boxes (otherwise the form looks messy on the screen). The blue "Create Listing" button is currently appearing above the input boxes. How do I move this button such that it's positioned below the input boxes? Thanks in advance! -
I have a confusion about creating the user profile when the user is newly registered
views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: login(request,user) return redirect('homepage') else: messages.error(request,'No current user!') else: form = AuthenticationForm() context = {'form':form} return render(request,'login.html',context) def logout_view(request): logout(request) return redirect('login') @login_required def profile(request): Profile.objects.get_or_create(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfileForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request,'Profile updated successfully!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileForm(instance=request.user.profile) context = { ## 'user':request.user, 'u_form':u_form, 'p_form':p_form, } return render(request,'profile.html',context) signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py class Profile(models.Model): name = models.OneToOneField(User,on_delete=models.CASCADE) mobile = models.IntegerField(null=True) address = models.CharField(max_length=350,null=True) image = models.ImageField(upload_to='profile_pics', default='default.png',null=True) def __str__(self): return str(self.name.username)+'\'s Profile' forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['mobile', 'address', 'image'] I am facing an issue that the user profile could not get created or updated although I used the signals for the profile model. When I login a registered user, the error message told me that User has no profile so in order to automatically … -
ValueError at /new_post/ The 'image' attribute has no file associated with it
In my django blog site if I want to add a new post there is an option of post it with or without an image. If I make a post with the image then it works fine, but if I make a post without any image it shows this error: ValueError at /new_post/ The 'image' attribute has no file associated with it. my codes are given below models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.TextField() image = models.ImageField(upload_to='post_image', blank=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.author}\'s Post' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) views.py: class PostCreateView(CreateView): model = Post fields = ['title', 'content', 'image'] success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'New Post' return context def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) home.html: {% if post.image %} <img class="card-img-right flex-auto d-none d-md-block" style="width:200px;height:200px;" src="{{ post.image.url }}" alt="{{ post.title }}"> {% endif %} -
Django email address not showing in admin
I'm trying to create a simple email and name collector , everything looks fine but I can only see the name option in the admin site the email option is not there admin page model Here is my code Forms.py from django import forms from sonus import models from django import forms class NameForm(forms.Form): your_name = forms.CharField(label="Your Name",max_length=20) your_email = forms.EmailField(label="Email",max_length=100) Here Goes my Views.py def get_name(request): person = Person() if request.method=="POST": form = NameForm(request.POST) if form.is_valid(): person.name = form.cleaned_data['your_name'] person.email = form.cleaned_data['your_email'] person.save() return HttpResponseRedirect(reverse('index')) else: form = NameForm() return render(request,'form.html',{ 'form': form }) My Admin.py from django.contrib import admin from django.contrib.admin.decorators import display from django.contrib.auth.admin import UserAdmin from .models import Details, Person,list from sonus import models # Register your models here. admin.site.register(Person) -
How to subtract datefield from datetimefield in django
I'm using Django, the model for field A is DateField and the model for field B is models.DateTimeField(auto_now_add=True) . I want to get the day difference by subtracting field A from field B. I tried as below because the properties of the two fields are different, but the result is output as datetime.timedelta(0) . Please tell me how to solve it. I've been thinking about it for a few days. Help... Feedback.objects.filter(Q(date__gte='2020-01-01')) .annotate(days_diff=ExpressionWrapper(F('create_date') - F('date'), output_field=DurationField()))\ .values('days_diff', 'id') -
checkbox to allow the staging frontend to connect with backend on localhost:8000 or staging backend
I have hosted the frontend and backend on staging server, sometimes I need to test the frontend with my local changes in the backend, so basically, I need a checkbox that allows the frontend to connect to localhost:8000 instead of staging server for the backend? That way, I will have no need to run the front-end locally just to change the endpoint. the frontend is written in React and the backend is written in Django. anyone who can help me with this thing? thanks in advance -
Problems with filtering data in Django
I am making a post, and the question is that i need to filter a list with the users who have published the most posts. I had tried, but only managed to filter the total posts, and have had trouble with that. The fields in Models.py from User: from django.contrib.auth.models import AbstractUser class Usuario(AbstractUser): email = models.EmailField(unique=True) creation_time = models.TimeField(auto_now_add=True) description = models.TextField() avatar = models.ImageField(blank=True, null=True, upload_to='autores/', default='img/default.jpg') social = models.URLField(blank=True, null=True) slug = models.CharField(max_length=60, unique=True, blank=True) is_author = models.BooleanField(default=False) meanwhile in models.py from Blog: class Post(ModeloBase): title = models.CharField('Titulo del Post', max_length=200, unique=True) slug = models.SlugField(max_length=200, blank=True, unique=True) description = models.TextField('Descripcion') author = models.ForeignKey(Usuario, on_delete= models.CASCADE) category= models.ForeignKey(Category, on_delete= models.CASCADE) content= RichTextField() referential_img = models.ImageField('Imagen Referencial', upload_to='imagenes/', max_length=255) published= models.BooleanField('Publicado / No Publicado', default=False) publication_date = models.DateField('Fecha de Publicacion') like = models.ManyToManyField(Usuario, blank=True, related_name='likes') dislike = models.ManyToManyField(Usuario, blank=True, related_name='dislikes') class Meta: verbose_name = 'Post' verbose_name_plural = 'Posts' def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) Looking in the django documentation, i tried to do the filtering but it didn't work for me. I don't know what my mistake was, so i hope someone could help me. for example, so i have my … -
Problems with accessing a Model in the Admin website
I have created Profile model, which works fine in the admin website in Django, obviously, I try creating a very complex model but I keep getting error, anyway decided to streamline the process and I created a very simple model. models.py from django.db import models from django.conf import settings #from django_countries.fields import CountryField #from phone_field import PhoneField class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return f'Profile for user {self.user.username}' class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) def __str__(self): return f'{self.firstname}' I ran python manage.py makemigrations and python manage.py migrate and the code works fine, I have also ensured that all previous migrations are deleted, so I successfully created a 0001_initial.py file in migrations. I decided to include my new model in the admin.py file so I can interact with the model from Django's user interface from django.contrib import admin from .models import Profile, Client @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'photo','role'] @admin.register(Client) class Client(admin.ModelAdmin): list_display = ['firstname'] #list_display = ['firstname', 'lastname','position','country','email','phone'] And this is where the problem starts, I can successfully see that the Clients model is create din the admin section, but when I click the … -
Use django-compressor on form assets (media) in Django
According to the Django Doc on Form Assets. You can add static files (.css and .js) to your forms and widgets via the Media meta-class. However, I am trying to add .scss and .ts files instead. Those files would obviously be compressed by django-compressor. Everything is working fine with the normal static files in *project*/static/style/stylesheet.scss and in my apps' static directories, but how would I compress the files specified in the Media class ? I don't know if that's possible using django-compressor or if there is another way to achieve what I am trying to do. I could not find any documentation on this problem on the django-compressor doc. I tried to directly add the .scss file directly in the Media meta-class as such: class Media: css = {'all': ('accounts/style/accounts.scss',)} However, django tells me that the stylesheet is not of type text/css. That would mean that overriding the media system for this would be an option to render with text/scss instead and try to compress the file... Nonetheless, that approach seems a bit overkill. I would appreciate any help!