Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth SocialAccount model's "extra_data" field
SocialAccount model has the extra_data field in the table. And this model has a relation with the User table. when I am retrieving the User table, trying to add the SocialAccount into the User but having an error. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class SocialAccountExtraDataSerializer(serializers.ModelSerializer): class Meta: model = SocialAccount fields = ["extra_data"] depth = 1 class UserDisplaySerializer(serializers.ModelSerializer): extra_data = SocialAccountExtraDataSerializer() class Meta: model = User fields = ["username", "extra_data"] depth = 1 the error message says: Got AttributeError when attempting to get a value for field extra_data on serializer UserDisplaySerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'extra_data'. How should I insert the SocialAccount's extra_data into User serializer as field. incase if you need to see views.py from rest_framework.response import Response from rest_framework.views import APIView from users.routes.serializers import UserDisplaySerializer class UserDisplayApiView(APIView): def get(self, request): serializer = UserDisplaySerializer(request.user) return Response(serializer.data) -
MultiValueDictKeyError at /register 'email'
class User(AbstractUser): is_reader = models.BooleanField(default=False) is_writer= models.BooleanField(default=False) -
Multiple root pages in Wagtail
I currently use wagtail as a blog which is accessible via example.com/blog and the admin via example.com/blog/admin. I would like to also use wagtail to create a support (knowledge base) section. This would then be accessible via example.com/support. The pages and models for the blog vs support section would be different since they're catering to different use cases. Would something like the following be possible? example.com/wagtail - wagtail admin (for both the blog and knowledge base) example.com/blog - blog section of the site example.com/support - knowledge base / support section of the site If the above is not possible I would also be open to having two completely separate wagtail apps in my django project, eg: example.com/blog - this is a blog wagtail section with its own admin example.com/blog/admin example.com/support - this is a separate support wagtail section with its own admin example.com/support/admin I'm not entirely sure which option is possible or how to go about getting either one to work. -
Integrate Dataframe from a Python File to Django
I've developed a complex data analysis model using Python (for the sake of simplicity, let's call it analysis.py) which contains multiple long algorithms to transform a set of raw data and spits out output in the form of dataframe as well. I've been looking into some tutorials recently on Django framework and have tried building a simple web app that resembles a forum/blog post web app. With the dataframe output from the analysis.py, I would like to display the data in the form of multiple charts on the web app. Can anyone point me to a direction to move from here? I've looked for multiple resources online but I think I am unable to find the correct keywords that match with what I actually want to build. I just want a shell code kind of a thing to integrate into my current django backend in order to be able to call the dataframe from the analysis.py Thank you very much in advance. -
Django static files for dashboard not loading
Hi I am fairly new to django and I am trying to learn adding dashboard to django using this tutorial - Django Plotly Dash Tutorial on Youtube. I was able to load all the html files, unfortunately I am unsuccessful with the static files. This is my project file directories My Project Settings.py STATICFILES_LOCATION = 'static' STATIC_URL = '/static/' STATIC_ROOT = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'sample2/static') ] Some base.html code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="../images/favicon.ico" type="image/ico" /> <title>This </title> <!-- Bootstrap --> <link href="{% static '../vendors/bootstrap/dist/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Font Awesome --> <link href="{% static '../vendors/font-awesome/css/font-awesome.min.css'%}" rel="stylesheet"> <!-- NProgress --> <link href="{% static '../vendors/nprogress/nprogress.css'%}" rel="stylesheet"> <!-- iCheck --> <link href="{% static '../vendors/iCheck/skins/flat/green.css' %}" rel="stylesheet"> MY welcome.html under home app {% extends 'base.html'%} {% load static %} The only things that I didn't follow on the tutorial was not install a database and not declare the {%load staticfiles%} because I have read that Django 3.1.3 has depreciated this command. What am I missing here? Thank you. -
How to intigrate paypal in Django (3.1) [closed]
I'm working on a project in which I'm using Python(3.9) & Django(3.1.2) and I need to implement the Paypal payment method in this project. -
UnboundLocalError at / local variable 'context' referenced before assignment
Getting this error with views.py in my Django app - UnboundLocalError at / local variable 'context' referenced before assignment. Here is a snippet of the code that is not working: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context: {'products':products} return render(request, 'store/store.html', context) -
How to customize the HyperLinkedRelatedField in Django Rest Fraemwork?
Hey I am working with Django Rest Framework. I am using HyperLinkedRelatedField from Rest Framework Serializer. As shown in image, the url is "http://127.0.0.1:8000/api/teams/new/" but I want it like "http://127.0.0.1:8000/api/teams/new/join/" Here is the Serializer code class TeamListSerializer(serializers.ModelSerializer): privacy = serializers.ChoiceField(choices=options) avatar = serializers.ImageField(default='users/avatar/default/user.png') url = serializers.HyperlinkedIdentityField(read_only=True, view_name='team-detail', lookup_field='slug') class Meta: model = Team fields = ( 'url', 'slug', 'name', 'description', 'avatar', 'privacy', 'pinned', ) read_only_fields = ('slug',) -
Label after forms.Select does not move to a new line
So I have a Category model that is a part of my Post model. I would like to choose from available categories when creating a post by having the forms.Select widget. The problem is that the select widget does not make the next label shift to a new line. How can I make "Content" appear on the next line and not next to "General?" Please see the screenshot. . My models look like this: class Post(models.Model): title = models.CharField(max_length=100, unique=True) header_image = models.ImageField(null=True, blank=True, upload_to='post_photos') thumbnail_image = models.ImageField(null = True, blank=True, upload_to='post_thumbnails') slug = models.SlugField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = RichTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=255, default='Coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name='blog_likes') class Category(models.Model): name = models.CharField(max_length=255) My form is: categories = Category.objects.all().values_list('name', 'name') choices = [x for x in categories] class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'header_image', 'slug', 'snippet', 'author', 'category', 'content', 'status',) widgets = { 'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'views.author', 'type': 'hidden'}), 'category': forms.Select(choices=choices, attrs={'class': 'form-control'}), } Html is simply: {% csrf_token %} {{ form|crispy }} {{ form.media }} -
How to put checkboxes side by side Django Form
I'm using Django and I need to present a ModelForm with some checkboxes in my template. The problem is that the checkboxes are in a vertical line, one after another. I need them to be evenly distributed in my page, for example 3 columns containing 4 checkboxes each. At the moment I only have 1 column with all my checkboxes inside it. This creates a scroll and the page looks awful. I've tried adding CSS classes and IDs as widgets in my "forms.py" file, I can change some styles, but I can't "play" with columns and lines. Is it possible to do this using Model Forms? -
Change to Django code gives NameError name (function) is not defined
I have a Django project where the model has two classes - Equity and Article. Within the Equity class I used to have the following code which worked smoothly def fundamental_list_actual(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) return l_fund However, I recently updated my code to include the following in the model code but outside any class: filename = 'fake_nums_trial_covar' #infile = open(filename, 'rb') infile = open('PATH_HIDDEN_FOR_PRIVACY/fake_nums_trial_covar', 'rb') covar_trial_nums = pickle.load(infile) infile.close() And within the Equity class, the following: def covars_abs_above_mean(row_index): covars = covar_trial_nums #cov_to_dataframe('Russel_1000_tickers_3.xlsx') stocks = covars.index pos_relation_list = [] neg_relation_list = [] pos, neg = avg_pos_and_neg(row_index) for stock in stocks: if (covars.loc[row_index, stock] > pos): pos_relation_list.append(stock) if (covars.loc[row_index, stock] < neg): neg_relation_list.append(stock) return pos_relation_list, neg_relation_list def fundamental_list(self): name = self.equity_name pos_related_cos, neg_related_cos = covars_abs_above_mean(name) #now we want to get a list of articles whose equity__equity_name matches that of ANY #of the equities in our pos / neg lists (though we'd like 2 separate filters for this) #try: pos_filtered = Article.objects.filter(equity__equity_name__in = pos_related_cos) neg_filtered = Article.objects.filter(equity__equity_name__in … -
select branch_id from report group by branch_id order by max(date) desc to Django Query
I have a model with the following fields id -> int vivitor_id -> int branch_id -> int date -> datetime I need to perform the following query in Django. How to do this using Django ORM. select branch_id from report group by branch_id order by max(date) desc ; -
getiing an AttributeError at /pay/ 'str' object has no attribute 'get' while trying to render another view
//models.py from django.db import models class CustomerInfo(models.Model): full_name = models.CharField(max_length = 150) email = models.EmailField() phone = models.CharField(max_length = 150) def __str__(self): return self.email //the code from my views.py from .forms import CustomerInfoForm def customer_info(request): if request.method == 'POST': customer_form = CustomerInfoForm(request.method) if customer_form.is_valid() and customer_form.cleaned_data: customer_form.save() return render(request, 'pay/payment.html', {'email': customer_form.email}) else: return HttpResponse('invalid input try again') else: customer_form = CustomerInfoForm() return render(request, 'pay/customer_info.html', {'customer_form':customer_form}) -
Django return none when y try to save in vars by POST method
I'm trying to save the data from a form by POST method. When i try to save in vars at views.py it put inside none here i show important parts of my code: add.html: <form method="POST"> {% csrf_token %} <h5>AÑADIR PEDIDO</h5> <div class="form-group"> <label for="cliente">Nombre del Cliente</label> <input type="text" class="form-control" id="cliente" placeholder="pepito" /> </div> <div class="form-group"> <label for="producto">Codigo del Producto</label> <select class="form-control" id="producto"> {% for cantidades in cantidad_pedido %} <option value="{{cantidades.Cproducto}}"> {{cantidades.Cproducto}} </option> {% endfor %} </select> </div> <div class="form-group"> <label for="cantidad">Cantidad de dicho producto</label> <input type="number" class="form-control" id="cantidad" placeholder="cantidad" /> </div> <button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button> </form> models.py: class Stock(models.Model): Cproducto = models.CharField(max_length=50, primary_key=True) cantidad = models.IntegerField() class Pedido(models.Model): Cpedido = models.CharField(max_length=50, primary_key=True) Ccliente = models.CharField(max_length=50) FechaPedido = models.DateField(default=datetime.now) class detallePedido(models.Model): Cpedido = models.ForeignKey(Pedido, on_delete=models.CASCADE) Cproducto = models.ForeignKey(Stock, on_delete=models.CASCADE) Cantidad = models.IntegerField() views.py : def add(request): cantidad_pedido = Stock.objects.all() if request.POST: client = request.POST.get('cliente') producto = request.POST.get('producto') cantidad = request.POST.get('cantidad') stock_producto = Stock.objects.get(Cproducto=producto) if(cantidad > stock_producto.cantidad): messages.error(request, 'Error, la cantidad es mayor') return render(request, 'add.html', {'cantidad_pedido': cantidad_pedido}) and here one picture of the vars: -
CSRF verification failed when logging into admin panel
In production my app is giving me CSRF verification failed when I log into my admin panel. I have the following in my settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True As my site doesn't currently have an SSL certificate I have ignored the following after running python manage.py check --deploy: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. -
page not found when making new url / view Django
Hello i am trying to add a basic url called localhost:8000/shop so that when i am on my homepage, I can click a link called shop and It will lead me to localhost:8000/shop in my urls.py i added from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from homepage import views urlpatterns = [ path('' , views.home), path('admin/', admin.site.urls), path('reviews/' , include('reviews.urls')), path('shop/' , include('product.urls')), ] in my folder called product i have a urls.py file with from django.urls import include, path from . import views urlpatterns = [ path('shop/' , views.shop), ] and in my product folder i have a views.py file with from django.shortcuts import render # Create your views here. def shop(request): return render(request, 'product/shop.html') linking It to my html file inside my product folder.. when i run the server, I get this error message Page not found (404) Request Method: GET Request URL: http://localhost:8000/shop Using the URLconf defined in yorleico.urls, Django tried these URL patterns, in this order: admin/ reviews/ shop/ The current path, shop, didn't match any of these. What am i doing wrong?! -
Why is any jwt authenticating the user in djangrestframework_simplejwt?
I am implementing jwt token authentication method using djangoreostframework_simplejwt module. It seemed to be working normally, but I decided that there was no problem with putting jwt in the header that was not issued by my server and passed it. I wonder if this is the problem of my server, this module or the inevitable problem of jwt. Can anyone give me an answer? -
File Upload Multiple Change On Input Gives Unexpected Results
I wrote a fileupload handler in JavaScript to send multiple files using formdata to django. The script works as expected if the user sends multiple files to the server using the input. However, if the user sends multiples files, and then tries to send multiple files BEFORE the last input (of multiple files) has finished, then the program gives unexpected results. Can anyone explain why? Possible solutions: change loop indices create some type of fileupload queue (which I think I already somewhat implemented) disable the input button until the first round of uploads is done processing (last resort) var uploadcount = 0; var folderuploadsinprogress = 0; var uploadfinished = 0; var uploadscanceled = 0; var uploadsize = 0; var fdata = new FormData(); var datalist = []; var xhrcancel = new Set() var xhr; $("#uploadstop").click(function(e){ if(xhrfolder){ xhrfolder.abort(); $("#fu").css("display","none"); return; } xhr.abort(); for(let i=uploadfinished+1; i<uploadcount; i++){ xhrcancel.add(i); } datalist = []; uploadcount = 0; fdata = new FormData(); return; }); function cancelupload(thisid){ console.log('cancel upload ',thisid); console.log('cancel upload finished ',uploadfinished); $("#"+thisid).css("display","none"); //check if canceled upload is a folder if(uploadfinished+uploadscanceled == thisid){ //cancel current upload console.log('cancel current'); if($("#"+thisid).hasClass("folder")){ console.log('has class folder'); xhrfolder.abort(); }else{ console.log('does not have class folder'); xhr.abort(); } uploadscanceled++; $("#"+thisid).css("display","none"); console.log('dl … -
How to set environment variable DJANGO_SETTINGS_MODULE
I've bee trying to send a pandas dataframe to the django database, though when I try this: user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] # host = settings.DATABASES['default']['HOST'] # port = settings.DATABASES['default']['PORT'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) I get this: ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What could I do to fix this? thanks -
Django 1 parent table that contains 2 children models, instead of creating 2 children tables
I have three models as following: class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="%(class)ss") timestamp = models.DateTimeField(default=timezone.now) amount = models.IntegerField(null=False) class Meta: abstract = True class Income(Transaction): INCOME_CATEGORIES = [ ("YEARLY", "Yearly"), ("MONTHLY", "Monthly"), ("ONETIME", "One-time"), ] category = models.CharField(max_length=9, choices=INCOME_CATEGORIES, null=False) class Expense(Transaction): EXPENSE_CATEGORIES = [ ("LUXURY", "Luxury"), ("ESSENTIAL", "Essential"), ] category = models.CharField(max_length=9, choices=EXPENSE_CATEGORIES, null=False) can_be_cheaper = models.BooleanField(default=False) But this creates 2 tables for Income and Expense models. I want to have 1 table called Transaction that'll contain these child models in it, is this possible? -
How do I do a Django query filter that matches against a list of values?
Hey guys I'm doing a small social media app and right now I'm having trouble figuring out how to display the posts of users someone is following. Right now I create a list that adds all of the usernames to it as values. How can I filter out the Django query results where it prints out all the results of those contained in the list? I can do it where it prints out only one of the followers posts, since I can compare one value easily. But how can I do the same when I need to compare to a list of values? Any ideas? Thanks guys. Below is my code: def follows(request, username): # create list list = [] # get the username of the signed in user userSearch = User.objects.get(username = username) # get the user ID of the signed in user userID = userSearch.id # get the user IDs of the followers of the signed in user query = Follow.objects.filter(follower_id = userID) #get the usernames of the followers of the signed in user query2 = User.objects.filter(id = query[0].following_id) #add the usernames to a list for i in query: list.append(i.following_id) query3 = NewPost.objects.filter(username = query2[0].username) paginator = Paginator(query3, … -
Using formsets to upload many files to a record, it isn't quite working
I have used as many examples online as I could cobble together in an attempt to get my two simple models: class Technical_Entry(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ema = models.ForeignKey(EMA, on_delete=models.CASCADE) system = models.ForeignKey('System', on_delete=models.CASCADE) # are SYSTEMS RELATED TO SUBSYSTEMS OR JUST TWO GROUPS? sub_system = models.ForeignKey(SubSystem, on_delete=models.CASCADE) drawing_number = models.CharField(max_length=200) drawing_title = models.CharField(max_length=255) engineer = models.CharField(max_length=200) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) date_drawn = models.DateField() ab = models.BooleanField() class Technical_Entry_Files(models.Model): tech_entry = models.ForeignKey(Technical_Entry, on_delete=models.CASCADE) file = models.FileField(upload_to='techdb/files/') def __str__(self): return self.tech_entry.drawing_number To upload using a formset. While the page 'displays' mostly correctly, it flat out does not create the record in the Technical_Entry_Files model. Relevant forms.py: class FileUploadForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FileUploadForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-4' self.helper.field_class = 'col-lg-8' class Meta: model = Technical_Entry_Files fields = ('file',) TechFileFormSet = inlineformset_factory(Technical_Entry, Technical_Entry_Files, form=FileUploadForm, extra=1) class Technical_EntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Technical_EntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-4' self.helper.field_class = 'col-lg-8' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = Technical_Entry fields = ('category', 'ema', 'system', 'sub_system', 'drawing_number', 'drawing_title', 'engineer', 'vendor', 'date_drawn', 'ab') widgets = { 'date_drawn':DateInput(attrs={ 'class':'datepicker form-control', 'id' : 'datetimepicker2', 'tabindex' : '1', 'placeholder' : 'MM/DD/YYYY hh:mm', 'autocomplete':'off', }, format='%m/%d/%Y'), … -
Getting really strange error when deploying a django app on Heroku
I tried to deploy my django application to heroku using the starter guide and the other manual that shows you to create your runtime, requirements, procfiles, installing django-heroku, etc. So I've now deployed my site but recieve the following error.My error I'm unsure of why this error is showing up at all especially when it worked perfectly fine locally. I haven't followed all of the django deployment checklist yet, such as setting DEBUG to False because I'd like to ensure that it works correctly before I do. If anyone could help me, that'd be much appreceiated! -
Django get children of parent on parent detail page
I'm trying to get access to the children of a model and list them on the parents details page. Here is how I have it set up... Models: class Destination(models.Model): title = models.CharField( null=True, max_length=60, blank=True) featuredimage = models.ImageField(null=True, blank=True, upload_to ='media/') location = PlainLocationField(based_fields=['title'], zoom=7, null=True, blank=True) class Airport(models.Model): title = models.CharField( null=True, max_length=60, blank=True) city = models.ForeignKey(Destination, null=True, blank=True, on_delete=models.SET_NULL) Views: def destination_detail(request, slug): destination = Destination.objects.get(slug=slug) context = { 'destination': destination, 'airport': Airport.objects.filter(city = destination.id), } return render(request,"destination/detail.html",context) Template: <h1> {{ airport.title }} </h1> It doesn't throw an error or anything but nothing is displayed. I have everything imported and set up correctly, I think I'm just missing on how to properly set it up in my views. Any insight would be greatly appreciated. -
Django template breaking model value string at space
I have the following HTML template in Django: <select name="store" id="store_select"> <option>Search by Store</option> {% for store in stores%} <option value= {{store.store_name}} >{{store.store_name}}</option> {% endfor %} </select> However, it renders the following: <select name="store" id="store_select"> <option>Search by Store</option> <option value= "Best" buy >Best buy</option> <option value= "Costco" >Costco</option> <option value= "Staples" >Staples</option> </select> How do I make it render "Best buy" and not "Best" buy ? TIA