Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: sitemap index only To use a custom domain
I'm using django + react(next.js) Instead of the domain set in the admin. For the sitemap index, we want to specify the domain used by Django. For example, if you set up example.com in admin, it will look like the following. I want to change the example.com part to api.example.com. <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc>http://example.com/sitemap-video.xml</loc> </sitemap> </sitemapindex> # sitemaps.py class VideoSitemap(Sitemap): changefreq = "weekly" def items(self): return Video.objects.published() def location(self, obj): return f"/video/{obj.pk}" def lastmod(self, obj): return obj.updated_at # urls.py urlpatterns = [ path( "sitemap.xml", sitemaps_views.index, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "sitemap-<section>.xml", sitemaps_views.sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), ] -
Stop Form From Being Submitted Until Verified
I have a form structured as so. <form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/"> <div class="form-group"> <label for="id_email_address" class="d-none">Email Address</label> <input type="email" id="id_email_address" class="form-control border-0 rounded-0" name="email_address" value="" placeholder="Email Address"> <input type="hidden" name="mailpiece_slug" value="{{ page.settings.email_newsletter_slug }}" /> <input type="hidden" name="event_slug" value="subscribe" /> </div> </form> I also have a script at the bottom of the file. The point of the script will be to verify a recaptcha before submitting the form. Here is my script. <script> document.getElementById('email_subscription_form').addEventListener('submit', verifyRecaptcha); function verifyRecaptcha(e) { e.preventDefault() return false } </script> I was thinking, based on some research, that the function returning false would stop the form from submitting. However, the form still submits and hits the endpoint. I have also tried this: <form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsubmit="return verifyRecaptcha()"> and <form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsbubmit="return false"> but the form still submits. What can I do to stop the form from submitting until verified? This is a Django project, so the template is a Django template. -
Django JWT Refresh Asking for Email and Password
I'm trying to implement JWT in django and am using rest_framework_simple_jwt. The TokenObtainPairView is working properly and gives me the access and refresh token when I pass the email and password in the body. However, when I use the TokenRefreshView, it doesn't work and asks me for the email and password even though I should only have to pass the refresh token in the body. Any help here would be appreciated! -
Problems displaying Django formset using JS with button
I'm having trouble deploying my formset. It happens that by clicking on the "add Part" button you must duplicate, triple, etc. the form. However that doesn't happen, I can't find the error, previously they told me it was here: container.insertBefore(newForm, addButton). But I already checked and I can't find the fault, they also told me that by not using this: let Id="id_form-TOTAL_FORMS" the line of code totalForms.setAttribute('value', ${formNum+1}); can't work. Can someone help me what is happening? by the way I am basing myself on this tutorial to make the formset JS let parteForm = document.querySelectorAll(".part-form") let container = document.querySelector("#part-form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_form-TOTAL_FORMS") let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing addButton.addEventListener('click', addForm) function addForm(){ let newForm = parteForm[0].cloneNode(true) console.log("en la funcion newForm:",{newForm}) let formRegex = RegExp(`form-(\\d){1}-`,'g') console.log("en la funcion formRegex:",{formRegex}) console.log("en la funcion formNum:",{formNum}) formNum++ console.log("en la funcion formNum:",{formNum}) newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`) console.log("en la funcion newForm:",{newForm}) container.insertBefore(newForm, addButton) totalForms.setAttribute('value', `${formNum+1}`) } HTML <section id="section-form"> <div> <form method="POST" id="part-form-container"> {% csrf_token %} <input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" /> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <div … -
React post request not returning
Doing a post request to fetch the given category on the backend. Using postman this works. Setting the headers to content type application/json and in the body writing: "category": "design" Then sending a post request to backend. It then returns the posts in the given category. However when doing it from react it does not work. App.js import React from 'react'; import { BrowserRouter, Routes, Route, } from 'react-router-dom'; import Layout from './hocs/Layout'; import Home from './components/Home'; import Blog from './components/Blog'; import BlogDetail from './components/BlogDetail'; import Category from './components/Category'; function App() { return ( <BrowserRouter> <Layout> <Routes> <Route exact path='/' element={<Home />} /> <Route exact path='/blog' element={<Blog />} /> <Route exact path='/category/:category_slug' element={<Category />} /> <Route exact path='/blog/:slug' element={<BlogDetail />} /> </Routes> </Layout> </BrowserRouter> ); }; export default App; Updated function for fetching posts in given category const getCategoryBlogs = () => { let list = []; let result = []; blogs.map(blogPost => { return list.push( <div className="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div className="col p-4 d-flex flex-column position-static"> <strong className="d-inline-block mb-2 text-primary">{capitalizeFirstLetter(blogPost.category)}</strong> <h3 className="mb-0">{blogPost.title}</h3> <div className="mb-1 text-muted">{blogPost.month} {blogPost.day}</div> <p className="card-text mb-auto">{blogPost.intro}</p> <Link to={`/blog/${blogPost.slug}`} className="stretched-link">Continue reading</Link> </div> <div className="col-auto d-none d-lg-block"> <img width='200' height='250' src={blogPost.thumbnail} alt='thumbnail' … -
save an upload file without database in django
I want to upload a file via form and save it without using database. Here is the code. But i cant see file any where after i upload. upload.html <form action = "" method = "post" enctype="multipart/form-data"> {% csrf_token %} {{form }} <input type="submit" value="Submit"> </form> forms.py class UploadVideoForm(forms.ModelForm): class Meta: model=VideoUploadModel fields = "__all__" views.py def upload(request): if request.method=='POST': form = UploadVideoForm(request.POST,request.FILES) if form.is_valid(): print('form is valid') output=form.cleaned_data['video'] print('output',output) #form.save() return render(request,'upload.html',{'form':form,'hr':'hr'}) else: print('form is invalid') return render(request,'upload.html',{'form':form}) else: form = UploadVideoForm() return render(request,'upload.html',{'form':form}) models.py class VideoUploadModel(models.Model): video=models.FileField(upload_to='videos') settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") -
how to throw user friendly error message if validation fails for query params in django
I am writing an API in Django, and the URL is something like foo.com/api/places?city_id=123 So, here my query_param is city_id, and my API should accept integers only, if query_param is sent as city_id="xyz", then my API needs to send some user-friendly message instead of 500. May I know how to achieve that in Django, please? -
Video broadcasting from server based on Django to all clients
I'm building a website based on Python/Django as a backend and react.js as a frontend. The situation is: Django gets a list of videos from a database. this list should be broadcast to all clients (it is like a TV stream). By searching, I found that webRTC can handle video streams by doing peer-to-peer. what I understand is that webRTC makes a client connect to a client but in my situation, I need the server to broadcast videos to all clients. Now, Is webRTC is the best solution in my case? if so, how many clients can be served at the same time? -
Advanced filtering for many-to-many annotations
I have following models: class CloudObjects(models.Model): object_id = models.AutoField(primary_key=True) object_name = models.CharField(max_length=256) creation_time = models.DateTimeField() removed_date = models.DateTimeField(blank=True, null=True) item = models.ManyToManyField(BackupItems, db_table='cloud_object_items') class BackupItems(models.Model): name = models.CharField(max_length=100) I'd like to annotate for each BackupItem, the most recent creation_time field from CloudObject for items which are planned to be removed in removed_date in future. As an example: CloudObject looks likes this. object_id | object_name | creation_time | removed_date | item 1 | object_one_in_cloud | 2021-01-01 | 2021-10-01 | 1 2 | object_two_in_cloud | 2021-02-02 | 2099-12-31 | 1 3 | object_three_in_cloud | 2021-03-03 | 2099-12-31 | 1 4 | object_four_in_cloud | 2021-12-31 | 2022-01-01 | 1 For above example I'd like to annotate with item 3, as it has removed_date in the future and this is the most fresh item (item 2 is also planned to be removed in future, but 3 is more recent) Now in my Views I'd like to annotate this. I tried different ways, but can move forward now. This is last one I tried: from django.db.models import Subquery, OuterRef class BackupListView(ListView): template_name = 'somefile.html' def get_queryset(self): last_item = CloudObjects.objects.filter(item=OuterRef("pk")).filter(removed_date__gte=timezone.now()).last() all_items = BackupItems.objects.annotate(last_backup=Subquery(last_item.get('creation_time'))) return all_items How to get it working? -
Django 3.2.9 send email using Azure App service
I'm trying to send emails from my Django application to users in Azure. The issue I've been having is that even that works with no issues in development or localhost. There's no exceptions being showed in the logs stream when try to send email thought the server. What might be reasons? from django.core.mail import EmailMessage from smtplib import SMTPException email = EmailMessage( subject=email_subject, body=email_body, from_email=settings.EMAIL_HOST_USER, to=[user.email, ] ) try: email.send() except SMTPException as e: print('There was an error sending an email: ', e) except: # It will catch All other possible errors. print("Mail Sending Failed!") -
Django Crispy Forms 'as_crispy_field' ignore formhelper
as per the title, I'm trying to render a single field in the template but is not inheriting the properties of formhelper, mainly adding the placeholder to all the fields I usually render the form trough the formhelper but in this case i need to add the individual fields within the template as the html is too complex If I render the form with {% crispy form form.helper %} the placeholder is shown Here it is the code # forms.py class ApplicationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' # Moving field labels into placeholders layout = self.helper.layout = Layout() for field_name, field in self.fields.items(): layout.append( Field(field_name, placeholder=field.label) ) self.helper.form_show_labels = False class Meta: model = Application fields = '__all__' # views.py class ApplicationUpdateView(UpdateView): model = Application template_name = "template.html" form_class = ApplicationForm # template.html {{ form.email|as_crispy_field }} Thank you for any help -
Is there a way to implement Django templates in a form
I have a Django form where admins create user-specific pages, and I want admins to add {{username}} as input in the form so that when the content of the created page is rendered to a user the tag {{username}} becomes the username. Here's what I have tried so far; views.py: from django.template import Template, Context template = form.cleaned_data['HTML_content'] context = Context(dict(username='xxxx')) # instead of xxxx, users.objects.filter(username='John') rendered: str = template.render(context) This method is returning an error "str object does not have render", because HTML_content is a Text_filed in forms.py and I couldn't find a workaround to make this work. -
Django web project "blog.views has no attribute"
So I had the basic server running fine and then I created a page that said "Blog Home", but after I added another page that said "Blog About" now I'm getting this in my Cmd: File "C:\Users\Christopher\Desktop\poo\blog\urls.py", line 6, in <module> path("about/", views.about, name="blog-about"), AttributeError: module 'blog.views' has no attribute 'about' views.py: from django.shortcuts import render from django.http import HttpResponse def home(response): return HttpResponse("<h1>Blog Home</h1>") def about(response): return HttpResponse("<h1>Blog About</h1>") urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.home, name="blog-home"), path("about/", views.about, name="blog-about"), I also had a very strange problem in that my code was not running at all yesterday, but then I started my computer today and ran the server and....magic! The server was working! Not sure if you can give me any suggestions as to why that was not working. Thanks. -
TypeError: bad operand type for unary +: 'list'
I am getting above error by adding this line in urls.py file urlpatterns =+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to implement registration and login logics as an API using ViewSet instead of generic views in Django Rest Framework
I am new to viewset when using Django Rest Framework to create registration and login logics as an API using ViewSet instead of generic views, and exposing resources to a React standalone frontend app on a diffrent port. In a previous project where I had the possibility to use django template as frontend inside the django project, I simply used django Views to implement the registration and login logics and template by doing this: // MyOldMethod.py @login_required def index(request): return render(request,'customers/index.html') def signup(request): context = {} form = UserCreationForm(request.POST or None) if request.method == "POST": if form.is_valid(): user = form.save() login(request,user) return render(request,'customers/index.html') context['form']=form return render(request,'registration/signup.html',context) And by this mean, the basic login authentication were set. Now for this case, I need to use viewset and serializer and at the end, connect the React frontend app to the django API using axios. So far I implemented, the models.py, serializer.py and api.py and the urls.py as follow in the customers app. // models.py inside customers App from django.db import models from django.core.validators import RegexValidator class Customer(models.Model): name = models.CharField(max_length=100) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) … -
Image directory changes automatically in django 3.2 tenant schemas
I am working with Django Tenant Schemas. I have Image field in user model and i have used upload to function to store the avatars inside the /avatars/<tenant_name>/<user_id>/filename. When i upload it uploads successfully but it stores inside the tenant folder by default and when i try to get it back it shows there is error. versions: django = 3.2 django-tenant-schemas = 1.11 I am attaching my screen shot images below. my settings files settings.py. settings.py. Django admin page image url. file Directory in my system. models.py -
python flask web app, pdf form generator and e-signature
after lots of research trying to find a solution regarding generating a pdf from an online form fields , also the main issue is that user should be able to digitally sign it and after completion the filled pdf form should be sent to a predefined email address. Any ideas on where i should start. i found PDFtron and it could be a solution, any other pointers are welcome. Thanks -
Occasional 403 CSRF error in React Native WebView
I am loading a form (powered by Django) in a React Native app using react-native-webview. This form has CSRF protection. And most of the time it actually works fine, you can submit the form in the app through the webview and everything is fine. But sometimes I get a 403 CSRF error (CSRF verification failed, Request aborted). I'm not sure what could be causing this and how could it be avoided? I'm using the WebView in a fairly straightforward way with a wrapper around it. If there was a network connection issue on the mobile phone then I would probably get a timeout error instead right, not something specific like this? import { WebView as BaseWebView } from 'react-native-webview'; const FullScreenWebView = styled(BaseWebView)` flex: 1; `; ... export const WebView: FC<WebViewProps> = props => { ... return ( <Layout.Root> {url.startsWith('/') ? ( <Layout.LoadingFlex1 /> ) : ( <FullScreenWebView ref={webviewRef} source={{ uri: urlWithLang }} startInLoadingState={true} onShouldStartLoadWithRequest={globalZendeskIntercept} // only allow secure webviews and those for our deeplink scheme originWhitelist={['https://', `${Config.DEEPLINK_SCHEME}://`]} decelerationRate="normal" allowsBackForwardNavigationGestures onNavigationStateChange={navState => { if (navState.canGoBack) { setCanGoBack(true); } else { setCanGoBack(false); } }} /> )} </Layout.Root> ); }; -
How to change date format django?
I am new to django, and I want to change date format from 2022-01-01 00:00:00 to 2022-01-01 00:00:00.000000. How can I do that? Thanks in advance. the code that I am using is: start_date=datetime.strptime(room["available_from_date"], '%Y-%m-%d') -
Filling out username automatically when adding user in Admin
I am using django-allauth with the following settings: ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True When a new user signs up, the username is filled out automatically based on the user's email address. However, this does not happen when I add a user using Admin. How do I make it happen? This is the relevant code I have so far: class CustomUser(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.username if self.username else self.email # https://stackoverflow.com/a/15603839/2725810 CustomUser._meta.get_field('email')._unique = True class CustomUserAdmin(UserAdmin): model = CustomUser # Adding to Add User form first_name and email, removing username add_fieldsets = \ ( ( (None, {'fields': ('first_name', 'email')}), ) ) + \ ( ( (None, {'fields': UserAdmin.add_fieldsets[0][1]['fields'][1:]}), ) ) list_display = ['first_name', 'email'] save_as = True admin.site.register(CustomUser, CustomUserAdmin) -
Django FormSet extra fields
I have a inline formset with 3 fields, is it possible to add extra of just 2 fields? Example - i do a service to a car, usually one service needs multiple parts to be used so i want to add extra 'Part' and 'Price' field and be able to save it properly. Picture below explains it. https://ibb.co/VDWDcPM -
Restrict weekend days in html datetimepicker
I am currently building a django application with an appointment booking feature. This is all working fine however I would like to restrict the weekends on it. I've tried a few solutions with jquery but nothing seems to be working. My desire is just to have the weekends greyed out when a user opens the datetime picker. -
Microsoft Outlook Add-in can't extract/pass data to a localhost server via Ajax
I'm trying to build an Outlook add-in for encrypting/decrypting emails. The Add-in itself uses a web app, which in turn uses Javascript. I basically want to pass the unencrypted/encrypted email to a local server running python using GET/POST requests, perform some encryption/decryption on it in python, and then pass it back to Outlook Add-in. The problem is that the Add-in just won't pass any data to the local server nor get something in return. I have tried to work with both Django and Flask with the same results. I also configured the local servers to use locally-generated certificates and keys with no improvement. I even tried routing the HTTP connection using ngrok, but none came of it. Server response to GET request on HTTP Server response to GET request on HTTPS using Werkzeug The code given below never returns "Here5" on item-status. Clearly the success snippet isn't being run. $.ajax({ url: "https://127.0.0.1:8000/getPost/hello/", type: 'GET', dataType: 'json', // added data type success: function (res) { $('#item-status').text("Here5"); $('#item-message').text(res); } }); I've also added the required URLs in the App Domain part of the manifest file: <AppDomain>https://127.0.0.1:8000/getPost/hello/</AppDomain> The Add-in performs fine when running GET requests from other sites on the internet, like: https://api.github.com/users … -
how to access database object from another server in client sid
I have working on project that using Django.I have render some data as json format with httpresponse in url like this "1.1.1.1:8080/data". and get data with javascript and AJAX in client side, I should mention that this server have no access to intenet and it work in internal network of our company. this work prefect. but another server like 'example.com' want to render my html and i manage it, this work well but the data "1.1.1.1:8080/data" do not load and return error on pinging. so is there any solution to make access my django app load data on 'example.com'. best regarads -
How to pass value of a selection option to a class parameter in flask?
I am trying to create a flask app for a machine learning model. Here is the data.html file which contains the view. <select multiple name="features" class="form-control"> <option value=""></option> {% for col in columns %} <option value="{{col}}">{{col}}</option> {% endfor %} </select> Machine learning has long lines of code but here is how it looks ml.py: class sequential_learning: min_distances_list=[] y_pred_dtr_mean=None y_pred_dtr_std=None ... def __init__(self,dataframe,init_sample_size,target_treshhold,number_of_executions, sample_treshold,sigma,distance,model,strategy ): #constructor self.dataframe= dataframe self.model=model self.strategy = strategy print(type(self.dataframe)) self.apply_feature_selection_to_df(self.dataframe) self.apply_target_selection_to_df(self.dataframe) if(len(fixedtargets)>0): print(fixedtargets) self.target_df=self.target_df.join(fixedtargets)#self.dataframe[fixedtargets]) self.standardize_data() init_sample_set=self.init_sampling() def apply_feature_selection_to_df(self,dataframe): self.features_df = self.dataframe[features] Here is the flask app.py: @app.route('/data/slamd', methods=['GET', 'POST']) def slamd(): #print(df) dataset = df ... fixedtargets = request.form.get('fixedtargets') features = request.form.get('features') targets = request.form.get('targets') s = sequential_learning(dataset,initial_sample_size,target_quantile,iterationen,sample_quantile,std, dist,model,strategy) dt=DT("Decision Tree",s,target) s.model=dt s = s.main() return render_template('slamd.html', s=s, df = df, fixedtargets=fixedtargets, targets=targets, features=features) I have two questions here: 1 when I select the select box, it has the string but not the value which is in my file. 2 In my ml.py, the variables which are a get request are not recognized, such as the features inside my class are not recognized because I mentioned them in my app.py, not in ml.py. How to make it recognizable?