Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset validation with axios
I have searched for a few hours with no luck. Also, I'm new to programming. I am trying to perform form validation on a Django formset. I have multiple dynamically added (javascript) forms on one page. When a user submits the form/s, if there are errors in the form the forms will be over wirtten by the redirct back to the registration page. My solution to perform form validation via axios. The problem: My problem is that I'm getting django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] Full traceback: [19/Aug/2018 14:39:42] "GET /event-registration/?event=Lone%20Wolf HTTP/1.1" 200 13455 [19/Aug/2018 14:39:42] "GET /static/events/style.css HTTP/1.1" 200 340 [19/Aug/2018 14:39:42] "POST /event_formset HTTP/1.1" 200 7917 in error checking > Internal Server Error: /error_checking Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shanecheek/Desktop/projects/lobos/events/views.py", line 164, in error_checking if formset_post.is_valid(): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/formsets.py", line 301, in is_valid self.errors File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/formsets.py", line 281, in errors self.full_clean() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/formsets.py", line 322, in full_clean for i in range(0, self.total_form_count()): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/forms/formsets.py", line 110, in total_form_count return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line … -
Accessing a remote Postgresql database using django
I'm a newbie in django and trying to run a remote db instance at aws. I've changed my database settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '*****', 'USER': 'postgres', 'PASSWORD': '******', 'HOST': 'jfkdljfkdsljf.rds.amazonaws.com', 'PORT': '5432', } I already have data in remote database but my question is how to access that data in django? For example in views, and templates etc. -
Fail to create Django registration form with email and password only
Creating basic registration/ authentication in Django is insanely hard. After many tries, I manage to create basic registration/ authentication in Django using username and password. The code is shown in https://github.com/yccheok/django Now, I wish to create registration form which only use email and password. No username. I try to following the official example https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example . The example is using email, password and DOB for registration. I'm not interested in DOB, but I will just simply follow the example at this point. I made the following changes : https://github.com/yccheok/django/commit/ae0b16d38a39fad78a2137e2649c0f3fda12a3ff However, I'm facing 2 problems. The registration form, still look the same as previous registration form. It has username and password text fields. What I'm expecting are email and password text fields. Error Manager isn't available; 'auth.User' has been swapped for 'accounts.MyUser' after clicking Sign up button. I had read Manager isn't available; 'auth.User' has been swapped for 'polls.User' , but total clueless on how to apply the solution in my case. Any idea how I can modify my basic workable registration/login example (https://github.com/yccheok/django), to make them register using email and password? -
How to update models.py when I create a new table in my database?
I was wondering how to automatically update my models.py in a specific app in django. I created a new table in my database through HeidySQL, when i syncdb, i see the table appears in the directory in the command line, but not in models.py . I also tried migrate and make migrations but still not working. Any idea? Thanks! -
What action need to take for django settings.py file in production?
I need some help to host the django application.This is my settings.py file.I am going to host it on AWS. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY'), EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'www.domain.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'feed', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backmyitem.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'feed.views.notification_context', ], }, }, ] WSGI_APPLICATION = 'backmyitem.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': '5432' } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LOGIN_REDIRECT_URL = '/report' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N … -
Customizing Django Admin's verbose_name by init, using default
As I would use in version 2 of django the default_app_config = 'catalog.apps.CatalogConfig' in init to set verbose_name and customize django admin? It returns the error 'No Module named catalog'.Details, I use my apps to a directory below and in INSTALLED_APPS I put' projectName.AppName ' -
Queryset Union in Django
I'm trying to do a simple double entry accounting with Django. Every transaction is currently one object with debit and credit accounts being foreign keys. Now I'm trying to get all transaction objects out so that there's debit and credit object for every transaction and I can easily order and represent every account's transactions and totals in the template. So every transaction object needs to have debit object and credit object in the final outcome. I think in MySQL you could achieve this with something like: SELECT date, description, amount, debit_account AS account, debit AS 1 FROM Transaction UNION SELECT date, description, amount, credit_account AS account, debit AS 0 FROM Transaction What is the right way to do this with Python's objects in Django? Union seems to override the changes within the for loop I currently have and I end up with no distinction between debit and credit. models.py class Transaction(models.Model): date = models.DateField() description = models.CharField(max_length=150) debit_account = models.ForeignKey('ledger.Account', related_name='debit_account', blank=True, null=True, on_delete=models.CASCADE) credit_account = models.ForeignKey('ledger.Account', related_name='credit_account', blank=True, null=True, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) debit_in_ledger = models.BooleanField(default=False) views.py def ledger(request): transaction_list_debit = Transaction.objects.all() transaction_list_credit = Transaction.objects.all() for a in transaction_list_debit: a.debit_in_ledger = True transaction_list = transaction_list_debit.union(transaction_list_credit, all=True).order_by('debit_account', 'public_date') … -
Python3 ImportError: cannot import name 'cookies' from 'http'
This seems to be a very common, possibly involving a conflict between Python 2.x and Python 3.x libraries. For instance, this answer suggests the problem is with the path: Import Python module fails (http.cookies) but the full error that I get is: ImportError: cannot import name 'cookies' from 'http' (/usr/local/lib/python3.7/site-packages/gunicorn/http/init.py) and if I do this: cat ImportError: cannot import name 'cookies' from 'http' (/usr/local/lib/python3.7/site-packages/gunicorn/http/init.py) I see: # -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. from gunicorn.http.message import Message, Request from gunicorn.http.parser import RequestParser __all__ = ['Message', 'Request', 'RequestParser'] So clearly, for the version of HTTP that I have, there is no cookies module exported. If I do this: find /usr/local/lib64/python3.7/site-packages/ -name cookie.py I see two entries: /usr/local/lib64/python3.7/site-packages/django/contrib/messages/storage/cookie.py /usr/local/lib64/python3.7/site-packages/django/http/cookie.py This file: /usr/local/lib64/python3.7/site-packages/django/http/cookie.py starts with: from http import cookies Does it make sense that this can import from itself from http, when it lives in http? And http does not export this in its __init__.py file? -
Django matplotlib tkinter.TclError: NULL main window
I've been working with matplotlib.pyplot, pdflatex and django to create an app that retrieves data from a database, createspng charts based on that data and compile a tex file that has that images. I create four kinds of charts, each one associated with a function: #A bar/line with a rezised chart plt.figure(figsize=(16.0, 10.0)) plt.bar(y_pos, values) plt.plot(areas, standardValues) plt.clf() # A barchart with resized chart plt.figure(figsize=(16.0, 10.0)) plt.bar(y_pos, diferrenceValues) plt.clf() # 10 histogram with distribution chart shape, loc, scale = stats.lognorm.fit(hours_per_program, floc=0) x_fit = np.linspace(data.min(), data.max(), 100) hours_per_program_fit = stats.lognorm.pdf(x_fit, shape, loc=loc, scale=scale) ax.hist(data, N_bins) plt.clf() # And 10 side bar charts plt.barh(r1, data1, barHeight) plt.barh(r2, data2, barHeight) plt.barh(r3, data3, barHeight) plt.clf() The functions for each kind of chart is called in that order and that number of timer. So when I generate the pdf for the first time ... File "/home/me/docs/project/t1/client/views.py", line 1359, in generatePdf lineBarChart(areas_names, areas_program_hours, areas_standard_value, "cliente/static/img") File "/home/me/docs/project/t1/client/chartGenerator.py", line 45, in lineBarChart plt.figure(figsize=(16.0, 10.0)) File "/home/me/docs/project/t1/venv/lib/python3.5/site-packages/matplotlib/pyplot.py", line 548, in figure **kwargs) File "/home/me/docs/project/t1/venv/lib/python3.5/site-packages/matplotlib/backend_bases.py", line 161, in new_figure_manager return cls.new_figure_manager_given_figure(num, fig) File "/home/me/docs/project/t1/venv/lib/python3.5/site-packages/matplotlib/backends/_backend_tk.py", line 1053, in new_figure_manager_given_figure icon_img = Tk.PhotoImage(file=icon_fname) File "/usr/lib/python3.5/tkinter/__init__.py", line 3397, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/usr/lib/python3.5/tkinter/__init__.py", line 3353, in __init__ … -
Django create a valid ModelForm with an invalid Model to add fields manually after form validation
How do you create a post request to have a ModelForm be valid (giving you everything the user needs to fill out) but then alter the model (with everything the user shouldn't have to give you [such as username/profile, datetime, other computable variables, etc...]) before the form/formset is validated in the view? Sample Code: views.py def view(request): # Create the formset, specifying the form and formset we want to use. LowerFormSet = formset_factory(LowerForm, formset=BaseLowerFormSet, extra=0) # If they are posting data if request.method == 'POST': # Grab the data they submitted formData = request.POST # highestForm = MealForm(formData, meal=meal, prefix='recipe') lower_formset = LowerFormSet(formData, prefix='lower_formset') lower_form in lower_formset: lower_form.instance.a = A.objects.create(…) # HERE # Each form isn't valid, because it is missing its associated higher object, despite not including the field in the ModelForm lower_form.save() # But if we create a foreign key/higher object and add it here, we are circumventing the validation step, and creating objects when the validation might not be True lower_form.instance.higher = Higher.objects.create(…) lower_form.save() # How do you separate these concerns, so you can create a valid Model Form, then add the necessary parts after the validation? # Check for valid data if all([otherForm.is_valid(), lower_formset.is_valid(), other_formset.is_valid(), ]): … -
django instance.id=None
I'd like to save a profil photo for each user.instance.id is returning None when upload image.I'm waiting for your help. models.py def get_image_path(instance, filename): return "%s/%s" % (instance.id, "profil.png") class UserProfile(models.Model): profile_image = models.ImageField(upload_to=get_image_path, blank=True, null=True) froms.py from .models import UserProfile class image(forms.ModelForm): class Meta: model = UserProfile fields = '__all__' views.py def model_form_upload(request): if request.method == 'POST': form = image(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = image() return render(request, 'model_form_upload.html', {'form': form}) model_form_upload.html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Using {% include 'includes/some.html' %} in django template
I have a template as under:- <div class= "comment-form m-2"> {% include "includes/comment_reply_form.html" %}</div> If the user is authenticated then the html shows the form. However if the user is not logged in I want to show a Login button. I am handling the same by the following javascript. $(".comment-reply-btn").click(function(event){ event.preventDefault(); if (user_is_authenticated === false) { $(".comment-form").html('{% include "includes/reply.html" %}'); $(this).parent().next(".comment-reply").fadeToggle(); } else { $(this).parent().next(".comment-reply").fadeToggle(); } }); But, instead of including the html in from reply.html, it is showing {% include "includes/reply.html" %} in the webpage. There is no problem with the javascript and if I add <p> You need to Login </p> in the following line. It works fine :- $(".comment-form").html('{% include "includes/reply.html" %}'); But since I need more options in my reply.html I want to add it as includes. I have tried using the escape character "/" in front of { but it didn't help. -
Accumulated sum of parent child hierarchy in Django
I want to create a hierarchy of costs in django and display the accumulated value of parent nodes in a parent-child hierarchy. I also want to show the child nodes values. For this I have the following model: class accounts(models.Model): account_nr = models.IntegerField(null=True) account_name = models.CharField(max_length=100) parent_account_nr = models.IntegerField(null=True) a typical list of accounts would be: account_nr account_name parent_account_nr 1000 project 1 null 1010 subproject 1 1000 1011 task 1 1010 1012 task 2 1010 I have another model in which I add values as a transaction: class transactions(models.Model): transaction_id = models.CharField(max_length=100) account_ID = models.ForeignKey(accounts, on_delete=models.CASCADE) debit_value = models.DecimalField(max_digits=10, decimal_places=2) credit_value = models.DecimalField(max_digits=10, decimal_places=2) I currently have the following view which shows me the accumulated entries into the transactions model: def home(request): account_query = accounts.objects.all() \ .annotate(Sum('transactions__debit_value')) \ .annotate(Sum('transactions__credit_value')) \ .order_by('account_nr') args = {'account_queryx': account_query} return render(request, 'home.html', args) with the following template I can view the accumulated entries in the model. {% extends "base.html" %} {% block content %} <table> <tr> <th>Account</th> <th>Omschrijving</th> <th>Debit</th> <th>Credit</th> </tr> {% for account_query in account_queryx %} <tr> <td>{{ account_query.account_nr }}</td> <td>{{ account_query.account_name }}</td> <td>{{ account_query.transactions__debit_value__sum}}</td> <td>{{ account_query.transactions__credit_value__sum }}</td> </tr> {% endfor %} </table> </div> {% endblock %} the issue I can't get my … -
Django Ajax is redirecting me to another page
My ajax keeps on redirecting me to the page http://localhost:8000/process/ even though it's should not. I'm fairly new to ajax and I just got this ajax code from a youtube video. HTML <form action= "{% url 'process' %}" method="POST" enctype="multipart/form-data" class="w-100" id="form_submit"> {% csrf_token %} <div class="col-sm-4 mx-auto"> <input type="file" name="pcap_file" id="pcap_file" required="True" class="form-control-file text-center w-100"> </div> </div> <div class="row h-50"> <div class="col-sm-3 mx-auto"> <input type="submit" value="testing" class="w-100" id="testbtn" data-toggle="modal" data-target="#exampleModal"> </div> </form> SCRIPT <script type = "text/javascript"> $(document).on('submit','#form_submit',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/process/', data:{ pcap_file:$('#pcap_file').val csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert("okay") } }); }); </script> Views.py def process(request): if "GET" == request.method: return HtppResponce("error") myfile = request.FILES["pcap_file"] print(myfile) #classpercent = SOM(myfile) return HttpResponse('') URL urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^process/$',views.process, name='process'), path('admin/', admin.site.urls), ] The post request is working with status code OK. I'm stuck with this problem for about an hour now Please help. -
Django queryset objects return None instead of 0 even though the database has 0 stored as the field value
I encountered a problem when I started using mysql-connector/python instead of mysqlclient for my Django project. Suddenly values stored as 0 in the database is turned to "None" in the resulting queryset, here's an example. queryset = SomeModel.objects.get(status=0) print(queryset.status) # Prints "None" Where the same statement would have printed 0 with mysqlclient. Is there a good way to fix this? I haven't gotten mysqlclient to work well with my current setup and would rather not have to track down all the calls depending on a 0-value and restructure it to handle Nonetypes. -
Django My form is not saving in django db ?
I am newbie and after reading documentation of django . i made forms but my form is not saving to my db and not showing in my db . please help me i tried so many ways but still its not saving . i have drivers for this purpose i want to register them . but its not saving to my db . and I think its not posting data to my db. please help me . Views.py def driver_form(request): args = {} template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html")#sir this ? return render(request, template_page, args) def driver_save(request): args = {} if request.POST: driver_firstname = request.POST.get('driver_firstname') driver_lastname = request.POST.get('driver_lastname') driver_save_form = DriverForm(request.POST) if driver_save_form.is_valid(): new_driver = driver_save_form.save(commit=False) new_driver.driver_firstname = driver_firstname new_driver.driver_lastname = driver_lastname new_driver.save() template = Template.objects.get(template_default__exact=1) template_page = template.template_alias + str("/rentacar/rentacar_driver_form.html") return render(request, template_page, args) else: return HttpResponseRedirect('/') else: return HttpResponseRedirect('/') rentacar_driver_form <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div class="container"> <form method="POST" action="/rentacar/driver-save/"> {% csrf_token %} <label> First Name<br> <input type="text" name="driver_firstname" required> </label> <br> <label> Last Name<br> <input type="text" name="driver_lastname" required> </label> <br> <input type="submit" class='btn btn-primary' value="Submit"> </form> </div> </body> </html> Forms.py from __future__ import unicode_literals from django import forms from rentacar.models import … -
Django REST Framework Serialize Multiple Models into one "Timeline"
I have an abstract base "Post" model with multiple child models that have their own required fields. I have serialized these different post types into something that looks like this "timeline": { "text": [ { "id": 1, "heading": "Yea", "text": "hello world", "render": "<p>\n Yea\n</p>\n<p>\n hello world\n</p>\n", "created_on": "2018-08-18T16:05:45.910124Z" } ], "video": [], "image": [] } What I'm trying to do is be able to display them chronologically on the front end. What is the best way to implement this? -
django leaflet map show attribute table for each layer on click
Hello guys I have created a map using leaflet and geoserver wms layers. I would like to display the attributes of my layer when I click on it. Do i have to built a template to display them or there is no need to. Can somebody provide me an example so that I can apply it. I tried to use onEachFeature but I couldn't display any attribute, I guess it works only for layers that are display by geoJSON. Thank you! -
Why doesn't function call in Django models refresh values if it includes a db query while other functions work fine?
Here's my code which only pulls values the first time but not again: def slist(): return list(set(Product.objects.values_list('servicecat', flat=True))) class CustomerProduct(models.Model): pub_date = models.DateField(verbose_name="Date Data Last Refreshed", default=timezone.now) servicecat = models.CharField(max_length=50, verbose_name='Service Category', null=True, blank=True, choices=tuple(zip(slist(), slist()))) It works fine, but it will only pull the values once. timezone.now works dynamically, but slist() does not. Why? -
Django rest framework- Single class based view bound to multiple urls
I'm creating a rest api with class based views. I want my urls to be like this with a view class named ProjectView: api.myapp.com/project/ -> uses ProjectView get api.myapp.com/project/create/ -> uses ProjectView post api.myapp.com/project/edit/ -> uses ProjectView put I couldn't manage to bind a single view class to multiple urls without exposing all other actions(get, post, put) to that url. Instead I created ProjectView, ProjectViewCreate, ProjectViewEdit classes which seems pretty pointless. Is there anyway I can accomplish the url configuration that I outlined with a single view class? -
Serving Django content through AWS Application Load Balancer
I'm building a django web application on an ec2 instance that's in an autoscaling group and fronted with an Application Load Balancer. I've configured uwsgi and nginx and when I run the command uwsgi --socket /tmp/uwsgi.sock --module MyProject.wsgi --chmod-socket=666 --virtualenv /path/to/my/virtual/env/ Everything works great when I access the application through the IP adress. I can navigate to the site and everything works well. However, when I try and access the website through the URL using the domain name that I own and registered though Route 53, the website's functionality works and is being served, but the static content (css files, etc) aren't rendering. My Auto-Scaling Group says the instance is healthy. The target group says the targets are healthy. The ALB is listening on ports 80 and 443 and forwarding the traffic to the Target Group. Does anyone know why the static content isn't rendering when going through the registered domain name even though it works when accessing it directly through the Public IP Address? -
How to compile a template saved in database in django
I am building an email sending application, I have many HTML templates stored in the database, So for each recipient, I need to customize this template by merging the tags/placeholders in the HTML, example email template <html> .... Hello {{ Name }}, .... </html> So I need to compile this based on the context variables I have. Like we compile Django templates, How can I do this in the current scenario, Tried, render_to_string() and get_template() functions, but they look for the actual template files stored in the templates/ folder. -
Django ajax POST works but then the page is stalled because it does not hit next GET
Here is my use case : My views displays an inline formset (formset associated to modelform). The view will display each object created by the user and allow him to modify them through the form. This works without Ajax. But as the user may create many objects, using Ajax would prevent the page from reloading after each submit. I implemented Ajax. It works on the first submit. But then, the page looks stalled : i cannot submit anymore. NOTE about the strategy used : the main template (education_form.html) {% include %} the form template (education_form_inner.html). While adding some print statement in my view, i realized that the else part after the POST is never executed... Here is my view : def education_edit(request, pk): curriculum_inst=get_object_or_404(Curriculum, pk=pk) EducationFormSet = inlineformset_factory(Curriculum, Education, form=EducationForm, extra=1, max_num=15, can_delete=True) if request.method == 'POST' and request.is_ajax(): education_formset = EducationFormSet(request.POST, prefix='form', instance=curriculum_inst) if education_formset.is_valid(): education_formset.save() html = render_to_string( 'cv_frontend/education_form_inner.html', {'formset': education_formset} ) payload = { 'result': 'success', 'message': 'Form valid', 'form': html } else: html = render_to_string( 'cv_frontend/education_form_inner.html', {'formset': education_formset} ) payload = { 'result': 'error', 'message': 'Form invalid', 'form': html } print('>>>>>>>>>>>> AJAX POST') return JsonResponse(payload) else: print('>>>>>>>>>>>> prepare object') education_formset = EducationFormSet(prefix='form', instance=curriculum_inst) print('>>>>>>>>>>>> GET') return … -
How to display the verbose_name in html?
k2o = models.FloatField(verbose_name="K<sub>2</sub>O (wt%)") I want to display verbose_name as html like K2O in the admin page but fail after trying format_html() Is there any way to display the verbose_name in html? -
Spotify Authorization Code Flow returns incomplete response
I have a django server, and I wish to perform the spotify Authorization code flow. Here is a basic skeleton I have created: The user opens the spotify/login url. The SpotifyLoginView redirects them to https://accounts.spotify.com/authorize url. The spotify servers callback to the spotify/callback endpoint. The SpotifyCallbackView makes a POST request to https://accounts.spotify.com/api/token to get the auth token. urls.py urlpatterns = [ path( "spotify/callback", views.SpotifyCallbackView.as_view(), name="spotify callback" ), path("spotify/login", views.SpotifyLoginView.as_view(), name="spotify login"), ] views.py def build_authorize_url(request): params = { "client_id": "<my client id>", "response_type": "code", "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), "scope": " ".join( [ "user-library-read", "user-top-read", "user-read-recently-played", "playlist-read-private", ] ), } print(params) url = ( furl("https://accounts.spotify.com/authorize") .add(params) .url ) print(url) return url AUTH_HEADER = { "Authorization": "Basic " + base64.b64encode( "<my client id>:<my client secret>".encode() ).decode() } def handle_callback(request): code = request.GET["code"] response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "client_credentials", "code": code, "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), }, headers=AUTH_HEADER, ) return response.json() class SpotifyLoginView(RedirectView): query_string = True def get_redirect_url(self, *args, **kwargs): return build_authorize_url(self.request) class SpotifyCallbackView(TemplateView): template_name = "success.html" def get(self, request, *args, **kwargs): print(spotify.handle_callback(request)) return super().get(request, *args, **kwargs) However, the response returned by the spoitfy servers doesn't contain the scope and refresh_token! So for these params: {'client_id': '<my client id>', 'response_type': 'code', …