Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does any one know how to get picture_url from LinkedIn using Django Social-Auth Linkedin Extra data?
I am getting id, firstName and lastName by default. It seems followup calls need to be made to retrieve email and picture_url data but I know how to do it in Django. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = "XXX" #YOUR_CLIENT_ID # Client ID SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = "XXX" #YOUR_CLIENT_SECRET # Client Secret SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_liteprofile', 'r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['id', 'firstName', 'lastName', 'profilePicture'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_Name'), ('lastName', 'last_Name'), ('emailAddress', 'email_address'), ('profilePicture', 'picture_url'), ('publicProfileUrl', 'profile_url'), -
Heroku - Application error - Heroku crashes when DEBUG = False
I just figured out how to host my static files on Whitenoise and they are being hosted perfectly when DEBUG = False. I had to host them this way because in production I kept getting 500 errors because Heroku couldn't host my static files. This works fine now. I am now running into another problem, however. When DEBUG = False in settings.py now my whole Heroku app crashes and shows the page below. This is only when DEBUG = False. I originally thought it was allowed host but I set that value equal to '*' which should allow all just for testing and I still got the same problem. How do I stop Heroku from crashing when DEBUG = False. settings.py import django_heroku from pathlib import Path import os from django_quill import quill from inspect_list.security import * # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = os.path.dirname(BASE_DIR) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') #MEDIA_ROOT = os.path.join(BAS_DIR, 'media') TIME_INPUT_FORMATS = ['%I:%M %p',] #Media_URL = '/signup/front_page/sheets/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #SECRET_KEY = 'HERE BUT SECURED IN A DIFFERENT FILE' … -
Auto increment the filed in Python Django model
This is my model class Department(BaseModel): name = models.CharField(max_length=20, null=False) maximum_number_of_employees = models.PositiveIntegerField(MinValueValidator(0), MaxValueValidator(3)) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=False) def __str__(self): return self.name I want to auto-increment the maximum_number_of_employees field upon the creation of the department and the associate of the employee to each department so that I can validate that the maximum_number_of_employees do not exceed the max limit -
Convert List data into Table form on Django template
I have a list of data as below in Python. I wanted to create image as below with data. [1,2,3,4,5,6,7,8,9,10,11,12] and it should be populated as below. 1 should go to box1 and so ..on. Can you please let me know how to do this in Django? In middle of the immage i wanted to include any of teh data. Will it be possible to write on image? enter image description here enter image description here https://i.stack.imgur.com/9sbvj.png -
How to style the input text in Django using CMS
I have a Django input field where I enters text and add CSS and HTML to it manually and output displays as desired. Is there any editing app available for Django so that I can edit and style text easily without hard coding. Please refer attached screenshot -
No module named '_tkinter' while publishing a Django app to Heroku
I have just posted my Django app to Heroku. It is said that the build was successful, but when I am opening the app I see Internal Server Error. I wrote heroku logs --tail and it says that there is no module named _tkinter, however, my application is not using this module at all. What is the problem? Could anyone help me? Here is the full output of heroku logs --tail 2022-01-24T13:00:14.271347+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 167, in _get_response 2022-01-24T13:00:14.271348+00:00 app[web.1]: callback, callback_args, callback_kwargs = self.resolve_request(request) 2022-01-24T13:00:14.271348+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 290, in resolve_request 2022-01-24T13:00:14.271349+00:00 app[web.1]: resolver_match = resolver.resolve(request.path_info) 2022-01-24T13:00:14.271349+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 590, in resolve 2022-01-24T13:00:14.271350+00:00 app[web.1]: for pattern in self.url_patterns: 2022-01-24T13:00:14.271350+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get 2022-01-24T13:00:14.271351+00:00 app[web.1]: res = instance.dict[self.name] = self.func(instance) 2022-01-24T13:00:14.271351+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 632, in url_patterns 2022-01-24T13:00:14.271351+00:00 app[web.1]: patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) 2022-01-24T13:00:14.271351+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in get 2022-01-24T13:00:14.271352+00:00 app[web.1]: res = instance.dict[self.name] = self.func(instance) 2022-01-24T13:00:14.271352+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 625, in urlconf_module 2022-01-24T13:00:14.271352+00:00 app[web.1]: return import_module(self.urlconf_name) 2022-01-24T13:00:14.271353+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2022-01-24T13:00:14.271353+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-01-24T13:00:14.271353+00:00 app[web.1]: File "", line 1030, in _gcd_import 2022-01-24T13:00:14.271354+00:00 app[web.1]: File "", line 1007, in _find_and_load … -
Django ListView with ModelForm local variable 'instance' referenced before assignment
I'm having a trouble with using modelform in my generic.ListView. When I post the form I get the error in the below. That was working with form.Form but when I changed into form.ModelForm , I got this error. **Is there any way to create an object with ModelForm in generic.ListView ? ** The error; local variable 'instance' referenced before assignment forms.py from django import forms from . import models class ActionCreateForm(forms.ModelForm): class Meta: model = models.Action fields = ('client_owner', 'contact_owner', 'topic', 'action_type', 'quote_price', 'quote_currency', 'statement', 'result', 'opportunity_type', 'file') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['client_owner'] = forms.ModelChoiceField(required=True, queryset=models.Client.objects.all(), label="", widget=forms.Select(attrs={'class': 'form-control'})) self.fields['contact_owner'] = forms.ModelChoiceField(required=False, queryset=models.Contact.objects.none(), label="", widget=forms.SelectMultiple(attrs={'class': 'form-control'})) self.fields['topic'] = forms.CharField(required=True, max_length=100, label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Topic'})) if 'client_owner' in self.data: try: alan1 = int(self.data.get('client_owner')) self.fields['contact_owner'] = forms.ModelChoiceField(required=False, queryset=models.Contact.objects.filter(client_owner_id = alan1), label="", widget=forms.SelectMultiple(attrs={'class': 'form-control'})) except (ValueError, TypeError): pass elif self.instance.pk and self.instance.client_owner: self.fields['contact_owner'].queryset = self.instance.client_owner.contact_client.order_by('name') views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views import generic from . import forms from . import models class ActionListView(generic.ListView): # action-listview model = models.Action context_object_name = 'all_actions' template_name = 'crm/action_list.html' ordering = ['-created'] def post(self, request, *args, **kwargs): if 'submit_action_create_form' in self.request.POST: action_form = forms.ActionCreateForm(self.request.POST, self.request.FILES) if action_form.is_valid(): print("*** request.POST: ", request.POST) client_obj = … -
VsCode Vim the custom mappings
I have the Vim VsCode extension. Where can I set custom mappings? Already searched for it but everyone says I have to do it in the settings.json But there isn't anything related to vim \\settings.json { "editor.hover.enabled": false, "security.workspace.trust.untrustedFiles": "open", "workbench.startupEditor": "none", "editor.formatOnSave": true, "workbench.iconTheme": "Monokai Pro (Filter Machine) Icons", "workbench.colorTheme": "Atom One Dark", "liveServer.settings.donotVerifyTags": true, "editor.fontSize": 13, "terminal.integrated.shellArgs.windows": ["-ExecutionPolicy", "Bypass"], "editor.minimap.maxColumn": 300, "editor.minimap.renderCharacters": false, "editor.minimap.showSlider": "always", "liveServer.settings.donotShowInfoMsg": true, "liveSassCompile.settings.formats":[ { "format": "expanded", "extensionName": ".css", "savePath": "/assets/css" }, { "format": "compressed", "extensionName": ".min.css", "savePath": "/assets/css" } ], "php.validate.executablePath": "C:/xampp/php/php.exe", "editor.cursorBlinking": "smooth", "editor.cursorSmoothCaretAnimation": true, "explorer.confirmDelete": false, "editor.renderWhitespace": "none", "vim.startInInsertMode": true, } Already tried to just append something like this in the settings.json, it also does not work { "vim.insertModeKeyBindingsNonRecursive": [ { "before": ["j", "k"], "after": ["<ESC>"] } ], } Any Ideas? Thank you! :=) -
Django stops updating data to mysql after page refresh
I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone? Stuff for reference: views.py from django.shortcuts import render from websiteDB.models import dbInsert from django.contrib import messages def insertToDB(request): if request.method == "POST": if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'): post = dbInsert() post.uname = request.POST.get('uname') post.email = request.POST.get('email') post.message = request.POST.get('message') post.save() messages.success(request, "Message sent successfully.") return render(request, "contact.html") else: return render(request, "contact.html") models.py from django.db import models class dbInsert(models.Model): uname = models.CharField(max_length=100) email = models.EmailField() message = models.TextField() class Meta: db_table = "contactrequest" urls.py """ websiteDB URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls … -
How to redirect a user from django to react during email account activation
I have spent days looking for solution to this but I keep walking round in circles. I have a react application that is receiving API from django. Every part of the react app and django is working individually. With postman I can test the APIs account for email verification and the user gets verified. When I fill account registration form in react and submit it, the user is sent an email confirmation message. When I click on the activation link, how do I redirect the user to react since the email activation link is created in django and as such has django domain and not react domain. React App function App() { return ( <Router> <Header /> <main className="py-3"> <> <Route path='/signup' component={SignUpScreen} /> <Route exact path='/activate/:uid/:token' component={ ActivateAccount} /> </> </main> </Router> ); } Account Activation Component const ActivateAccount = ({ verify, match }) => { const [verified, setVerified] = useState(false); const dispatch = useDispatch() const verify_account = e => { const uid = match.params.uid; const token = match.params.token; dispatch(verify(uid, token)); setVerified(true); }; if (verified) { return <Redirect to='/' /> } return ( <Container className=' auth-container pt-4'> <Form className="auth-form"> <Button className="auth-button btn btn-block w-100" type="submit" onClick={verify_account} > Activate Account … -
django loading fixture "Cannot save object! The state has been changed since fetched from the database!"
I am loading a fixture to get content into the database while testing. The test case starts like this: class FirstTestCase(TransactionTestCase): fixtures = ['alldata.json'] I've created the fixture using a small version of my huge original database with a lot of content removed; this is also the version of the database i use for testing: if "test" in sys.argv: DATABASES = { 'default': { #the details of my smaller database } } when testing, I get the following error: Problem installing fixture '/path/to/my/fixture/alldata.json': Cannot save object! The state has been changed since fetched from the database! I haven't edited the .json file, how can I get this fixture to load -
Append table with Django URL tag JQuery
I have a table I am appending with user details and want to add a Django URL tag to the row and grab the primary key in the tag. something like this: function putTableData(response) { let row; $("#table_body").html(""); if (response["data"].length > 0) { $.each(response["data"], function (a, b) { row = `<tr> <td>${b["first_name"]} ${b["last_name"]}</td <td>${b["phone"]}</td> <td> <a onclick='console.log("${b["pk"]}")' data-url="{% url 'users:edit' user.${b["pk"]} %}"> </a> </td> </tr>`; $("#table_body").append(row) The onclick console log is printing the users primary key, but when I try to add the data url tag, I get "Could not parse the remainder ${b["pk"]} How would I be Abe to make this work? -
The included URLconf '<rest_framework.routers.DefaultRouter object
This is my app route from .views import StudentView from rest_framework import routers router = routers.DefaultRouter() router.register('student', StudentView) and this is my project URLs file and I am trying to include the Student route in it from django.contrib import admin from django.urls import path, include from student_school.urls import router urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(router)) ] But am getting this error django.core.exceptions.ImproperlyConfigured: The included URLconf '<rest_framework.routers.DefaultRouter object at 0x7fddc2abb520>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
Django post but not to correct slug, foreignkey
Making a post/note to a task, the note has a foreignkey to the checklist where the post is supposed to be, however it posts, but i have to self go in admin panel and choose the given checklist it belongs to. models.py class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) task = models.ForeignKey(Task, blank=True, null=True, related_name='checklist', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title class Note(models.Model): title = models.CharField(max_length=55) content = models.TextField() date = models.DateTimeField(auto_now_add=True) checklist = models.ForeignKey(Checklist, blank=True, null=True, related_name='notes', on_delete=CASCADE) def __str__(self): return self.title My views.py def task_detail(request, slug): ''' Detailed view of all tasks on given project ''' context = {} checklist = get_object_or_404(Checklist, slug=slug) context.update({'checklist':checklist}) form = NotesForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n for is valid") author = Profile.objects.get(user=request.user) new_note = form.save(commit=False) new_note.user = author new_note.save() return redirect('teams') context.update({ 'form': form, 'title': 'New Note', }) return render(request, 'projects/checklist.html', context) What is the post method missing, since it will not take into consideration where to post. So I do not have to go into my … -
<HaltServer 'Worker failed to boot.' 3> - Heroku Crash --- Worker failed to boot
Every now and then with my Django project launched on Heroku, it crashes. I know it is a change I am making somewhere but I cannot figure out what I am doing that is causing it. It's not completely random but I set DEBUG = True and turned off collectstatic and it crashed. I don't know if it is totally that or something else that I am doing but I just want to educate myself on it. I'm posting the Heroku log tails below. It is what I have been trying to decipher for a while now. Can anyone help me find out why my Heroku app keeps crashing? 2022-01-24T17:30:11.859242+00:00 app[web.1]: self.load_wsgi() 2022-01-24T17:30:11.859242+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2022-01-24T17:30:11.859243+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-01-24T17:30:11.859243+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-01-24T17:30:11.859244+00:00 app[web.1]: self.callable = self.load() 2022-01-24T17:30:11.859244+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2022-01-24T17:30:11.859244+00:00 app[web.1]: return self.load_wsgiapp() 2022-01-24T17:30:11.859244+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2022-01-24T17:30:11.859245+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-01-24T17:30:11.859245+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app 2022-01-24T17:30:11.859245+00:00 app[web.1]: mod = importlib.import_module(module) 2022-01-24T17:30:11.859246+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-01-24T17:30:11.859246+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-01-24T17:30:11.859246+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-01-24T17:30:11.859247+00:00 app[web.1]: … -
showing error in release phase on heroku for django rest framework
Operations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: Applying api.0004_auto_20220121_0056...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "9223372036854775807" LINE 1: ...TABLE "api_hero" ALTER COLUMN "name" TYPE varchar(9223372036... -
Problem with js files (jquery, bootsrap and bopper) in Django framework
I'm newbie in the Amazing world, World of programming and devlopping web apps, everyday I have new challenge, every time try to figure out the problems and solve them. Today I facing an amazing problem wich is when I write this code in Html page in Django framework: my project work clear without anyproblem (exactly I work on Collapse Button dropdown one) when I use this scripts with url links and using internet, my dropdown Button work normal but when I use <script src="{% static 'js/jquery.min.js' %} "> </script> or My dropdown button never working, eveen the terminal didn't give a an error. why this problem, and how to solve it ? thank you -
"detail": "Authentication credentials were not provided." Django-rest-frameweork and React
I'm trying to create Club object via React form but I get those 2 errors: {"detail": "Authentication credentials were not provided."} and 401 Unauthorized. Obviously there is something wrong with authorisation, I tested it with postman and it did not work, however when I tried with http://127.0.0.1:8000/api/clubs/ everything worked. I am pasting all of my code below. frontend/CreateClub.js import React, {useEffect, useState} from 'react'; import { useNavigate } from 'react-router-dom'; import Base from '../base/Base'; import { isAuthenticated } from '../user/helper/userApiCalls'; import { getAllClubs, createClub } from './helper/apiHelper'; const CreateClub = () => { const [clubName, setClubName] = useState(''); const [clubs, setClubs] = useState([]); const [nameTaken, setNameTaken] = useState(false); const navigate = useNavigate(); useEffect(() =>{ if (!isAuthenticated()) { navigate('/login') } else { loadClubs(); } },[]) const loadClubs = () => { getAllClubs() .then((data) => { setClubs(data); }) .catch((error) => console.log(error)); } const handleChange = (event) => { setClubName(event.target.value) } const onSubmit = (event) => { event.preventDefault(); if (checkExistingClubNames(clubName, clubs)) { const owner = isAuthenticated().user; const name = clubName; createClub({owner, name}) .then((data) => { if (data.name === clubName) { setClubName(''); setNameTaken(false); navigate('/'); } }) .catch((error) => console.log(error)); } else { setNameTaken(true); } } const checkExistingClubNames = (newClubsName, existingClubs) => { const filteredClubs … -
trying to send data from python to html
I'm scraping some content and trying to display on html page but it display nothing when i try to run jinja loop for dictionary i sent from python file, it runs every variable separately but not running loop on dictionary Python dictionary i'm trying to display dictionary = dict( [('page_title', url), ('title', title), ('anchor', anchor), ('images', images)]) Html code with jinja tags <div id="dictionary"> {% for items in dictionary %} <div class="card" style="width: 18rem;"> <img src="{{ items.images }}" class="card-img-top" alt="{{ items.title }}"> <div class="card-body"> <a href="{{ items.anchor }}" class="btn btn-primary"><h5 class="card-title">{{ items.title }}</h5></a> </div> </div> {% endfor %} -
Problems using createview on heroku
I was working locally and 3 Create Views worked perfectly for me to upload data. I passed it to Heroku and sadly out of the 3, only one CreateView works for me, any idea what it could be? I already reviewed the code and it is very similar both in views and in the template. The problem is that when I click the save button it doesn't do anything, it doesn't save anything and it doesn't take me to any link, but it seems strange to me that locally it worked quite well and not on heroku models class Carro(models.Model): placas=models.CharField(max_length=255) año=models.IntegerField() marca=models.CharField(max_length=255) modelo=models.CharField(max_length=255) tipo=models.CharField(max_length=255) motor=models.CharField(max_length=255, default='0') vin=models.CharField(max_length=255) color=models.CharField(max_length=255) agente_seguros=models.CharField(max_length=255) compañia_seguros=models.CharField(max_length=255) no_politica=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.placas} {self.año}{self.marca} {self.modelo} {self.tipo}{self.motor}{self.vin}{self.color}' \ f'{self.agente_seguros}{self.compañia_seguros}{self.no_politica}{self.cliente}' views class create_carros(CreateView): model=Carro form_class=CarroForm template_name='carros/carros-form-add.html' success_url=reverse_lazy('carros:list_cars') -
Django ajax how to add load more functionality?
I am implementing ajax for real-time updating data in my html page without refreshing or reloading page. Now I am thinking to add functionality for load more content by click on load more button or scroll down. Right now my all content displaying in html page. Assume I have 100 object and I want to load only 10 object at a time. If user click on load more button or scroll down then it will load another 10 object. here is my code: views.py class PostJsonListView(View): def get(self, *args, **kwargs): posts = list(Blog.objects.all().filter(is_published='published') ) data = list() for i in posts: blog_cover_image = None if i.blog_cover_image: blog_cover_image = i.blog_cover_image.url data.append({'author_first_name':str(i.author.first_name),'author_last_name':str(i.author.last_name),'blog_cover_image':blog_cover_image,'title':i.title,'body':i.body,'slug':i.slug,'created_at':i.created_at.strftime("%A, %d. %B %Y %I:%M%p")}) return JsonResponse({'data':data},safe=False) html <script> const postsBox = document.getElementById('posts-box') $(document).ready(function(){ setInterval (function(){ $.ajax({ url: '/posts-json/', type: 'get', success: function (response){ $("#posts-box").empty(); for (var key in response.data){ console.log(response.data[key].title) if (response.data[key].blog_cover_image){ postsBox.innerHTML += `<div class="card mb-4"> <img class="img-fluid rounded" style="max-height:300px;max-width:900px;" src=${response.data[key].blog_cover_image} alt="..." /> <div class="card-body"> <h2 class="card-title"><a href=${response.data[key].slug}>${response.data[key].title}</a></h2> <a class="btn btn-primary" href=${response.data[key].slug}>Read More →</a> </div> <div class="card-footer text-muted"> Posted on (${response.data[key].created_at}) <div class="author">${response.data[key].author_first_name}&nbsp${response.data[key].author_last_name}</div> </div> </div>` } else{ postsBox.innerHTML += `<div class="card mb-4"> <img class="img-fluid rounded" style="max-height:300px;max-width:900px;" src="https://via.placeholder.com/900x300" alt="..." /> <div class="card-body"> <h2 class="card-title"><a href=${response.data[key].slug}>${response.data[key].title}</a></h2> <a class="btn btn-primary" href=${response.data[key].slug}>Read More … -
Django: Autofocus different widgets depending on content
I have a form with two fields. I want to autofocus the first if it is empty, but autofocus the second if the first has content (from the initial= argument). How can this be done? It seems that changing the widget attribute after the form has been created doesn't work. # Build edit form initial = { 'title': area_title, } area_form = AreaForm(initial=initial) if len(area_title) > 0: # Focus description if title already exists area_form.fields['description'].widget.attrs['autofocus'] = 'autofocus' else: # Otherwise focus title area_form.fields['title'].widget.attrs['autofocus'] = 'autofocus' -
Django Cloudflare Proxy "CSRF Verification Failed"
I'm trying to proxy my Django App through Cloudflare via workers. The setup is like so: example.com/app/* forwards to my Django site ~everything else~ forwards to my Webflow site So far that part is working! However, I can't get Django to accept CSRF validation. Here are the headers for the request (scrubbed for identity purposes) { 'HTTP_HOST': 'fluent-spring.uc.r.appspot.com', 'HTTP_X_FORWARDED_FOR': '70.192.78.2', 'HTTP_X_FORWARDED_PROTO': 'https', 'HTTP_FORWARDED': 'for="172.70.0.123";proto=https', 'HTTP_CF_WORKER': 'example.com', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_CF_RAY': '6d2a89b3435e8c3b-EWR', 'HTTP_CF_VISITOR': '{"scheme":"https"}', 'HTTP_CF_EW_VIA': '15', 'HTTP_CDN_LOOP': 'cloudflare; subreqs=1', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_REFERER': 'https://fluent-spring.uc.r.appspot.com/', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36', 'HTTP_CF_CONNECTING_IP': '70.19.78.2', 'HTTP_ORIGIN': 'https://www.example.com', 'HTTP_PRAGMA': 'no-cache', 'HTTP_SEC_CH_UA': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"macOS"', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_SITE': 'same-origin', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_X_CLOUD_TRACE_CONTEXT': '959632cd27b84e7aad1a5e3c71f1d8a3/18242229191417730943', 'HTTP_COOKIE': 'csrftoken=GHjnkrOrhave8EJ1eayWxxaSZiaxu5JJcJAaI1dmzc5Tdnb9T1YwaXvYUDr5ZQ83', 'HTTP_X_APPENGINE_CITYLATLONG': '40.735657,-74.172367', 'HTTP_X_APPENGINE_COUNTRY': 'US', 'HTTP_X_APPENGINE_CITY': 'newark', 'HTTP_X_APPENGINE_REGION': 'nj', 'HTTP_TRACEPARENT': '00-959632cd27b84e7aad1a5e3c71f1d8a3-fd296acc51b7177f-00', 'HTTP_X_APPENGINE_TIMEOUT_MS': '599998', 'HTTP_X_APPENGINE_HTTPS': 'on', 'HTTP_X_APPENGINE_USER_IP': '172.70.230.1', 'HTTP_X_APPENGINE_API_TICKET': 'ChBkODIxOGU1YjRmMWE5NDlmGhMI2KyFxePK9QIVY049Ah0P8gjM', 'HTTP_ACCEPT_ENCODING': 'gzip', 'HTTP_X_APPENGINE_REQUEST_LOG_ID': '61eecfb100ff02c818a28bb9f40001737e666c75656e742d737072696e672d3333303332310001323032323031323474313035373136000100', 'HTTP_X_APPENGINE_DEFAULT_VERSION_HOSTNAME': 'fluent-spring-.uc.r.appspot.com' } And the error I get in the logs is Forbidden (CSRF token missing or incorrect.): /app/sadmin/login/ And on the screen is: CSRF verification failed. Request aborted. And my CSRF settings in my settings.py are: CSRF_TRUSTED_ORIGINS = [ "www.example.com", "example.com", "kevin-dot-fluent-spring.uc.r.appspot.com", "fluent-spring.uc.r.appspot.com", "localhost", "https://www.example.com", "https://example.com", ] -
Passing OpenAPI specs to Frontend framwork using DRF
The DRF app is very transaction heavy, it has lots of POST endpoints which expect forms. Some of these forms are 30+ input fields long. My plan is to now request the form that is requiered by the endpoint before I render it in the frondend. I got this idea from learning about the OPTION request, it returns a json that looks as following: { "name": "Snippet List", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { <------------------------- "id": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "title": { "type": "string", "required": false, "read_only": false, "label": "Title", "max_length": 100 }, It gets really interesting in the POST section of the json. Here every field that the API expects is listed, with the label, the type and abviosuly the key. But how do I request this data in the frondend. Also, I don't believe the OPTION request is ment for this. That's why I want to use OpenAPI specs for this. I've read a bit in the Django Docs and was able to create OpenAPI specs for my entire website but I somehow need specs that I can request per endpoint. … -
unable to import models to nested sub-directory django
Here is my project tree: (base) justinbenfit@MacBook-Pro-3 cds_website % tree . ├── api │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── serializers.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── main.py │ ├── management │ │ ├── __init__.py │ │ ├── commands │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ └── private.cpython-39.pyc │ │ │ ├── private.py │ │ │ └── scrape.py │ │ └── test.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── cds_website │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements.txt api is an app in a greater project called cds_website. The settings.py file in cds_website project directory contains the following installed apps: INSTALLED_APPS = [ …