Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I have child divs automatically position restrained within a parent div?
I have the following CSS for a div box within a larger page container div: .mybox{ position: relative; width:20%; max-height: 100%; min-height: 25%; } I want to be able to add multiple of these dynamically using a django for loop, so I want them to space themselves out automatically while still remaining inside the parent div. This is because I can't set position values on each item if they are created at runtime. Anyone know how I can do this? -
Python - Django The submit button does not work when I submit a form
I'am developing a website in Python Django. I want to code a form which send me by email the email address that the users put in the form. The problem is that the submit button does not work. When I click the button submit, I am not redirected to a new page and I am not receiving the content of the form. Can you help me to fix it ? My views def test(request): if request.method == 'GET': form = newsletterForm() else: form = newsletterForm(request.POST) if form.is_valid(): subject = 'New Subscriber' from_email = 'no-reply@test.com' message = ' Email Adress: ' + form.cleaned_data['from_email'] try: send_mail(subject, message, from_email, ['info@test.com']) messages.success(request, 'Thank you for contact us we will get back soon') render(request, "Test.html") except BadHeaderError: return HttpResponse('Invalid header found.') render(request, "Test.html") return render(request, "Test.html", {'form': form}) My HTML <form id="newsletterForm" class="contact-form" action="#" method="post"> <div class="input-group input-group-rounded"> {{ form.from_email|add_class:"form-control" }} <span class="input-group-append"> <button class="btn btn-light text-color-dark" type="submit"><strong>GO!</strong></button> </span> </div> </form> My forms class newsletterForm(forms.Form): from_email = forms.EmailField(label='search', widget=forms.TextInput(attrs={'placeholder': 'Email Address'})) -
Image saving in Database using Django giving Error "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
Hi I am extracting frames from video and want to store these frames into database using Django. Here is my code : def saveFrame(request): video = Video.objects.last() path = os.path.dirname(__file__) path = path.replace('videos',video.video.url) clip = VideoFileClip(path) clip = clip.subclip(0, 15) clip = clip.cutout(3, 10) clip.ipython_display(width = 360) cap= cv2.VideoCapture('__temp__.mp4') i=0 image = Image() while(cap.isOpened()): ret, frame = cap.read() if ret == False: break image.video_id = video image.title = video.title +str(i) image.imagefile = frame image.save() print(i) i+=1 cap.release() cv2.destroyAllWindows() When i run this code i recieve this error : Error in image.save() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Can anyone help me with this issue so I can save images into database. -
How to get list of the Postgres databases on Google Cloud using Django/Python
I intend to get the list of databases that are available PostGreSQL instance on Google Cloud. With command line gcloud tool the following provides the expected result for my project : gcloud sql databases list --instance=mysqlinstance How can I get the same result through python / django while using google cloud ? -
SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in django [duplicate]
I am facing one issue dimension = ['category','amount'] // Just imaging I am getting an array like this frim request for _, obj in enumerate(qs1): kwargs.update({obj[dimensions[1]]: Count(dimensions[1], filter=Q(dimensions[1]=obj[dimensions[1]]))}) Here I'm getting an error like this SyntaxError: expression cannot contain assignment, perhaps you meant "=="? in django If I am changing my code like this it will work , but my issue is that I am using filtering option there so I need to get the exact field name that user passed in the dimensions dimension = ['category','amount'] // Just imaging I am getting an array like this frim request for _, obj in enumerate(qs1): kwargs.update({obj[dimensions[1]]: Count(dimensions[1], filter=Q(filter_data =obj[dimensions[1]]))}) I -
error: Someip:port is not a valid port number or address:port pair
This is the first time I am deploying a django application. I created an AWS ec2 ubuntu instance. I followed the steps in this tutorial- https://adeshg7.medium.com/deploy-django-postgresql-on-ec2-using-apache2-from-scratch-42dc8e6682c1 The demo project was running fine on the server http://MyPublicIPv4Address:443. I then added another port in the security groups in AWS, and after that whenever I run "python manage.py runserver http://MyPublicIPv4Address:443 " on the puTTY connection command line, it gives me the same error: CommandError: "http://MyPublicIPv4Address:443" is not a valid port number or address:port pair. This seems like a django error in a very old version: https://code.djangoproject.com/ticket/14928. I cant find a way around this error. Any help would be appreciated. Thankyou -
Heroku logs drain (stream) guidance
I have a simple Django webApp, which involve several workers as well, running related jobs. I would like to stream Heroku logs into the webApp for a dashboard view, so that users could track the workers progress within the webApp. I'm not sure how to access the logs from the Django view (then pushing the content back to the Ajax caller). As far as I know, the Heroku logs can be retrieved by either Heroku UI, Heroku CLI or Heroku Log-Drain (or by some 3rd party add-ons). I think that Heroku Log Drains, with Logplex, could address this feature, but I'm not sure how to technically achieve that behavior. Which steps shall be taken for achieving the desired behavior, as described above? -
"Error: Error decoding signature" and "Variable '$token' is never used in operation 'VerifyToken'."
Tools: Django + Next.js + Django-GraphQL-JWT What works: I can login the user and obtain a JWT token, which I save in addition to saving the token in the localStorage to retrieve and verify later. What does not work: I can successfully retrieve the localStorage token, but when I try to use the library to verify the token on the server, I get this error: [GraphQL error]: Message: Error decoding signature, Location: [object Object], Path: verifyToken Verification code: const [authToken, setAuthToken] = useState(null); const [localToken, setLocalToken] = useState(); useEffect(() => { setLocalToken(localStorage.getItem("token")); }, []); ... const verifyToken = async () => { const client = createApolloClient(); const data = await client.mutate({ mutation: verifyMutation, variables: { token: localToken }, }); if (data) { setAuthToken(data.data.tokenAuth.token); } return data; }; ... Mutation: export const verifyMutation = gql` mutation VerifyToken($token: String!) { verifyToken(token: $token) { payload } } `; schema.py: class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() revoke_token = graphql_jwt.Revoke.Field() Here is what happens when I try this manually in GraphQL: If my mutation includes the token: mutation VerifyToken($token: String!) { verifyToken(token: "token_string_here") { payload } } returns: { "errors": [ { "message": "Variable '$token' is never used in operation … -
Django emails with a name over 75 characters
how are you? I am having trouble sending emails because of the sanitize_address() Django function. There is a ticket who talks about this: https://code.djangoproject.com/ticket/31784 The problem is: In the process of sending an email the addresses is sanatized: django/core/mail/message.py:98 => def sanitize_address(addr, encoding) The Name portion is encoded via the Header class email.header.Header.encode which will introduce newlines at 75 characters. Essentially Django seems to no longer accept send emails with names longer than 75 characters. How can I send emails with a name over 75 characters? There is a way to do it? Thank you in advance. Regards. -
Directly setting http only cookie in browser from django (frontend is svelte)
I am trying to send a http-only cookie from django response to svelte. The cookie reaches svelte using fetch, but it doesn't come into the browser. Is there a way to set cookie from django directly in the browser? Without using svelte? If no, then how to set an http-only cookie using svelte. Any help is much appreciated!!! -
TypeError: items is undefined while using DRF Api
I'm trying to connect my React Frontend to my Django Backend using the Dango-REST-Framwork to create an API. But i can't fetch my data with React. After my tries didn't worked i tried this example in the React Documentation. Everytime i try to map and 'print' my result this error is shown: TypeError: items is undefined Here is my code: import React, { Component } from 'react'; import axios from 'axios'; import {ThemeNavbar} from '../../../components'; import EinsatzTableRow from './components/EinsatzTableRow'; import './EinsaetzePage.scss'; export default class EinsatzePage extends Component { state = { error: null, isLoaded: false, items: [] }; componentDidMount() { axios.get("http://127.0.0.1:8000/api/einsatzverwaltung/") .then( (result) => { this.setState({ isLoaded: true, items: result.items }); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. error => { this.setState({ isLoaded: true, error }); } ); } render() { const { error, isLoaded, items } = this.state; if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div> <ThemeNavbar></ThemeNavbar><div>Loading...</div></div>; } else{ return ( <div className=""> <ThemeNavbar></ThemeNavbar> <div className="container"> <table class="table table-striped"> {items.map(item => ( <EinsatzTableRow einsatznummer="" alarmierungszeit="" stichwort="" meldebild="" ort="" einsatzbericht_link="#"></EinsatzTableRow> ))} </tbody> </table> </div> </div> … -
Django: session key doesn't works in CORS?
I want to create a object(Cart) with user session_key. models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items', blank=True) views.py: @api_view(['GET']) def addToCart(request, pk): product = Product.objects.get(id=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'added'}) urls.py: path('addToCart/<str:pk>/', views.addToCart, name='addToCart'), if I go to this url directly from my browser search bar, session key works fine. But if I want to access this url from React app it doesn't work. It shows server error. django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint DETAIL: Failing row contains (54, null, null) In front-end, I've made a button, it will call addToCart function. Reactjs: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCart/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', } }).then(res=>res.json().then(result=>{ if(result.response === 'added'){ //do something } })) } I'm using localhost for both front-end and back-end. I also want to add that, if I do like this⬇️ def addToCart(request, pk): if not request.session.session_key: request.session.save() product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) print(request.session.session_key) #it print different session_key for same user (every time user call this function) return Response({'response':'ok'}) when this function is called (by clicking that button from … -
Django import_export Imported file has a wrong encoding: 'charmap' codec can't decode byte
I'm using django's import_export lib. But when I'm importing my json file I'm receiving the following error Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x81 in position 1602: character maps to I've found similar questions but they don't conver django import_export. My json file contains arabic caracters and ascii caracters. Here's a json object from it : {"id":"35","code":"35","name_fr":"Boumerd\u00e8s","name_ar":"بومرداس"} Here's my import_export class where I'm precising utf-8 encoding class SpecAdmin(ImportExportActionModelAdmin): from_encoding = 'utf-8' def get_instance(self, instance_loader, row): try: params = {} for key in instance_loader.resource.get_import_id_fields(): field = instance_loader.resource.fields[key] params[field.attribute] = field.clean(row) return self.get_queryset().get(**params) except Exception: return None If anyone had a similar problem with this library can you please tell me what I'm doing wrong. -
Not being able to remove virtual environment using command 'pipenv --rm'
I'm trying to use requests package in my django project. I've installed pipenv using the following command pip install pipenv And I installed requests by using the command pipenv install requests as (myEnv) C:\Users\dell\PycharmProjects\WeatherApp\weather>pipenv install requests Creating a virtualenv for this project... Pipfile: C:\Users\dell\PycharmProjects\WeatherApp\weather\Pipfile Using C:/Users/dell/AppData/Local/Programs/Python/Python39/python.exe (3.9.4) to create virtualenv... [=== ] Creating virtual environment...created virtual environment CPython3.9.4.final.0-64 in 5997ms creator CPython3Windows(dest=C:\Users\dell\.virtualenvs\weather-5a5okUMG, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\dell\AppData\Local\pypa\virtualenv) added seed packages: pip==21.1.2, setuptools==57.0.0, wheel==0.36.2 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Successfully created virtual environment! Virtualenv location: C:\Users\dell\.virtualenvs\weather-5a5okUMG Creating a Pipfile for this project... Installing requests... Adding requests to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Locking...Building requirements... Resolving dependencies... Success! Updated Pipfile.lock (fe5a22)! Installing dependencies from Pipfile.lock (fe5a22)... ================================ 0/0 - 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. (myEnv) C:\Users\dell\PycharmProjects\WeatherApp\weather>pipenv install requests Installing requests... Adding requests to Pipfile's [packages]... Installation Succeeded Installing dependencies from Pipfile.lock (fe5a22)... ================================ 0/0 - 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Then I imported requests package in my views.py file and run my server … -
How can I solve this? 'int' object is not iterable
I'm making an Online shop using Django and trying to add quantity of each product from cart and it throws the error under : 'int' object is not iterable I know that it should be integer in this code(this is my views.py): def minus_cart(request): pnum = request.GET.get("pnum") cart = Order.objects.get(prod_num_id = pnum) cart.save() # save 호출 return redirect( "minus_cart_pro" ) def minus_cart_pro(request): memid = request.session.get( "memid" ) cart = Order.objects.filter(order_id_id = memid) member = Sign.objects.get(user_id = memid) pnum = request.GET.get("pnum") template = loader.get_template("cart_view.html") count = 0 for add in cart : count -= add.quan - 1 context = { "memid":memid, "cart":count, "member":member, "pnum":pnum, } return HttpResponse( template.render( context, request ) ) so I changed like this : count = 0 for add in cart : count -= add.quan - 1 the error shows that I have an error at my last line. return HttpResponse( template.render( context, request ) ) and this is my template : {% if memid %} <li class="nav-item"><a class="nav-link" href="/member/mypage?user_id={{memid}}">MyPage</a></li> <li class="nav-item"><a class="nav-link" href="/member/logout">Logout</a></li> <span class="fw-bolder">{{ memid }} 님 안녕하세요</span> {% endif %} {% if not memid %} <li class="nav-item"><a class="nav-link" href="/member/login">MyPage</a></li> <li class="nav-item"><a class="nav-link" href="/member/login">Login</a></li> {% endif %} how can I solve this? -
Django admin list_editable custom query
I have a model Submission that is shown in the admin of a Django site. class SubmissionAdmin(admin.ModelAdmin): """ Display information about the submission """ model = models.Submission #--> Define model to get info list_display = ( #--> View elements 'id', 'statusStaff', ) list_editable = ['statusStaff'] list_filter = ['statusStaff'] # Filter by statusStaff is a foreign key column referencing the following model: class StatusStaff(models.Model): """ Status of the submission used by the staff members """ #--> Fields name = models.CharField( verbose_name = ('Status'), max_length = 100, unique = True, ) active = models.BooleanField( default = True, ) #--> Meta class Meta: verbose_name = "Submission Status" verbose_name_plural = "Submission Status" #--> Methods def __str__(self): """ """ return self.name #--- #--- Right now the list_editable option leads to all values in StatusStaff being shown in the dropdowns and also in the Filters options. I would like that only entries with active = True are shown in both the dropdown generated with list_editable and in the Filters options. Is there a way to modify the query used to get the values for list_editable and Filters? -
How to represent Geodjango model in a django-leaflet leaflet map?
In my django app I am using Geodjango, django-leaflet and leaflet-ajax. I have a route model with a LineStringField. I want to render that route in a template using a leaflet map. I have tried the following code with other models (those that have a Point field instead). But for any reason this code is not working with the RouteModel. The leaflet map shows nothing. How can I add that route to the "gis" leaflet map Here is the model definition from django.contrib.gis.db import models class RouteModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False) route_type_id = models.ForeignKey("RouteTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="routes") start_date = models.DateField(verbose_name=_("Fecha inicio")) end_date = models.DateField(verbose_name=_("Fecha fin")) route_geom = models.LineStringField(verbose_name=_("Ruta"), srid=4326) def __str__(self): return self.name class Meta: db_table = 'riesgo_route' managed = True verbose_name = _('Ruta') verbose_name_plural = _('Rutas') Here is the ajax view: @login_required(login_url='/login/') def route_get_location(request,pk): route=serialize('geojson',RouteModel.objects.filter(id=pk)) return HttpResponse(route,content_type='json') urlpatterns = [ # url definitions path('ruta/localizar/<str:pk>', route_get_location, name='route_locate'), ] And in the template: {% leaflet_map "gis" callback="window.our_layers" %} <script type="text/javascript"> function our_layers(map,options){ //var datasets= new L.GeoJSON.AJAX("{% url 'mailapp:polygon_get_location' %}" ,{}); var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{}); datasets.addTo(map); } </script> -
Using Django Model: Concatenating Model Fields
This appears easy in my head, but still can't get it done. This is my model, and it's working as I'd like, though I admit it can be better. ''' from django.db import models class Engineers(models.Model): position = ( ('NOC', 'NOC'), ('Supervisor', 'Supervisor'), ('Site Manager','Site Manager'), ('Site Engineer', 'Site Engineer'), ) region = ( ('SS','South-South'),('SW','SW'),('SE','SE'), ('NE','NE'),('NW','NW'),('NC','NC'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20) phone = models.CharField(max_length=11) position = models.CharField(max_length=20, choices=position) workarea = models.CharField(max_length=20, choices=region) face = models.ImageField(upload_to='', height_field=15, width_field=9, blank=True) ''' So the issue is, instead of asking the user to enter a username, I want the username field to be automatically populated with the firstname.lastname concatenated like firstname + '.' lastname. in the database. How do I get this done? Thank you in anticipation. -
Error when uploading/viewing certain pictures - rendition not found - django storages
Wagtail version: 2.9.2 Django storages: ==1.11.1 Error: 2021-06-07 14:13:12 ERROR Internal Server Error: /admin/images/38/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/wagtail/images/models.py", line 300, in get_rendition focal_point_key=cache_key, File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get self.model._meta.object_name wagtail.images.models.Rendition.DoesNotExist: Rendition matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 559, in get_or_create return self.get(**kwargs), False File "/app/.heroku/python/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get self.model._meta.object_name wagtail.images.models.Rendition.DoesNotExist: Rendition matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/app/.heroku/python/lib/python3.7/site-packages/django/template/base.py", line 163, … -
Best way to do a URL dispatcher for this situation?
I'm really new to django and django rest framework and really need help on how to optimize this. So I have this in my views.py and url.py files. urls.py from . import views from django.urls import path urlpatterns = [ path('api/aapl/',views.aapl.as_view()), path('api/msft/',views.msft.as_view()), path('api/tsla/',views.tsla.as_view()) ] views.py from django.shortcuts import render from rest_framework import generics, viewsets from .models import Stock, priceHistory # Create your views here. from .serializers import StockSerializer, PHSerializer class aapl(generics.ListCreateAPIView): a = Stock.objects.get(ticker='AAPL') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer class msft(generics.ListCreateAPIView): a = Stock.objects.get(ticker='MSFT') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer class tsla(generics.ListCreateAPIView): a = Stock.objects.get(ticker='TSLA') queryset = priceHistory.objects.filter(stock = a) serializer_class = PHSerializer As you can see the aapl, msft, tsla views are basically the same thing. I want to make it more efficient and compact by only writing 1 APIView. I want to be able to have a path of path('api/stock/<str:id>',views.generalstock.as_view()) but I tried a few thing but it doesn't seem to work. I don't know how to pass the id to the view and what kind of viewset to use. How would I write out a more compact and general solution in urls.py and views.py? Thank you so much! -
I want to have two foreign key for a model in djano. One of these foreign key must create when something special happens
I want to have two foreign key for a model. One of these foreign key must create when something special happens. How can I write this and call it at a specific time? Can I write it as a function in model and call it in view when something special happens? -
RemovedInDjango20Warning: "Direct assignment to the forward side of a many-to-many set is deprecated" with setattr in the loop
In Django 1.11 I get this warning: RemovedInDjango20Warning: Direct assignment to the forward side of a many-to-many set is deprecated due to the implicit save() that happens. Use categories.set() instead. But it happens inside of the loop in place where we use setattr to add the attribute and assign it with value: for f, v in m2m_fields.items(): setattr(rule, f, v) How to avoid the arising of this warning from this code snippet? -
How to change cursor on chartjs doughnut chart hover?
I have a doughnut chart created with chartjs. I want to chart the mouse cursor to "pointer" when I hover any of the doughnut sections. How do I do that? Here is my code <canvas id="myChart" width="50" height="40"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script type="text/javascript"> const data2 = { labels: {{chart_labels|safe}}, datasets: [{ label: 'My First Dataset', data: {{chart_data|safe}}, backgroundColor: [ 'rgb(54, 162, 235)', 'rgb(255, 99, 132)', ], hoverOffset: 4 }] }; var ctx = $("#myChart").get(0).getContext("2d"); var myChart = new Chart(ctx, { type: 'doughnut', data: data2 }); </script> -
I want to schedule the email send for some choosen date . How can I do that in DRF?
I want to take the receiver email address and schedule date as an input and send mail to the schedule date. I have following lines of code in views.py Actually I'm looking forward to use apscheduler package for async background task in django but any suggestions and solutions are appreciable. class SendMailView(APIView): def post(self, request, *args, **kwargs): ''' POST Method for sending Email ''' send_to = request.data.get('receiver_email') schedule_for = request.data.get('schedule_date') email_plaintext_message = " Hello" send_mail( # title: "Test mail, # message: email_plaintext_message, # from: 'some@gmail.com, # to: [send_to] ) return Response({"status":"Email Send"},status=status.HTTP_200_OK) -
React With Django, Not auto refreshing with npm run dev
I've built React components in Django, but every time I update my react component I have to run npm run dev + reload the browser to see the changes. How can I fix this issue to make react refresh automatically after changes? I have --watch on my script but still doesn't work package.json { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.12.3", "@babel/preset-env": "^7.12.1", "@babel/preset-react": "^7.12.5", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "webpack": "^5.4.0", "webpack-cli": "^4.2.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.12.1", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "react-router-dom": "^5.2.0" } } index.js import App from "./components/App"; App.js import React, {Component} from "react"; import {render} from "react-dom"; import HomePage from "./HomePage"; class App extends Component { constructor(props) { super(props); } render() { return ( <div className="center"> <HomePage/> </div> ); } } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); Homepage.js import React, {Component} from 'react'; class Homepage extends Component { constructor(props) { super(props); } render() { return ( <div> test 1 </div> ); } } export default Homepage;