Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django-templated-email does not send email
I am using the following package https://github.com/vintasoftware/django-templated-email in a Django app to try and send an email. I am running it inside a django management command. When I run the command the email part outputs to the console but no email is actually sent out. The SMTP settings and such are correct as emails work fine for other areas of the application. from templated_email import send_templated_mail send_templated_mail( template_name='welcome', from_email='from@example.com', recipient_list=['to@example.com'], context={ 'username':"test", 'full_name':"test", 'signup_date':"test" }, ) Any help is appreciated. I suspect I have misunderstood the syntax of the package. -
Django3: How to display the results of a model function into an HTML template and/or Admin
So I have the following Classes one for user and one for "Project": class CustomUser(AbstractUser): pass class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) def monthlyTotal(self,user): this_month = now().month return Project.objects.filter( created__month=this_month, user=user ).aggregate( sum_total=Sum('total') )['sum_total'] def __str__(self): return self.name and my view which is also used to populate the Project Class: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') I would like to pass the currently logged in user to the function monthlyTotal so that it displays on my template. This is what I tried so far <p>Total monthly sales = {{ Project.monthlyTotal(user.username) }}</p> <p>Total monthly sales = {{ Project.monthlyTotal(request.user) }}</p> but can't get it to work, also would I be able to display this field in the admin so you see it when you look at a user admin portal? Thanks -
Update A Profile Picture In Django ImageField : Dynamic Method Used In Django Admin
My Application has a system where user can upload his profile pic. I created this feature later so used the foreignkey method this is the model class Profile_Pic(models.Model): user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic') profile_pic = StdImageField(upload_to='photos', default='', blank=True, ) and the html page {% extends 'datas/base.html' %} {% block content %} {% load static %} <h1 class="text-center" style="color: white">Add Profile Picture</h1> <br><br> <div class= "col-md-6.offset-md-3"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> <p>Data Error, Please Check Again.....</p> {% for field in form %} {% if field.errors %} {{ field.errors }} {% endif %} {% endfor %} </div> {% endif %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"> </form> </div> {% endblock %} the view @login_required def profile_pic(request): if request.method == 'POST': form = Photo(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, 'Your Profile Picture Has Been Updated Successfully') return redirect('profile') else: form = Photo() return render(request, 'datas/user_image.html', {'form': form}) and finally the form class Photo(forms.ModelForm): class Meta: model = Profile_Pic fields = ['profile_pic'] widgets = { 'Add Profile Pic': forms.FileInput(attrs={'class': 'form-control'}), } Now when we upload from the admin site,the system automatically deletes … -
Braintree hosted fields not appearing when using server side generated client token
I'm using the hosted fields example from braintree: https://developers.braintreepayments.com/guides/3d-secure/client-side/javascript/v3 Inside their javascript there is a function which calls: https://braintree-sample-merchant.herokuapp.com/client_token function getClientToken() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 201) { onFetchClientToken(JSON.parse(xhr.responseText).client_token); } }; xhr.open("GET", "https://braintree-sample-merchant.herokuapp.com/client_token", true); xhr.send(); } I substitute that endpoint with my own, which generates my client token using the settings I got from braintree sandbox. #settings.py from braintree import Configuration, Environment Configuration.configure( Environment.Sandbox, BT_MERCHANT_ID, BT_PUBLIC_KEY, BT_PRIVATE_KEY ) #views.py import braintree def return_client_token(request): return JsonResponse({ "client_token": braintree.ClientToken.generate() }) My endpoint returns the client token, but when I use it, the hosted fields do not materialize. The length of the key from the Braintree's example endpoint is 3664, whereas my is 2364.