Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having a page not found error after submitting a custom form
I have a custom html/css form that I have been working with for a bit and I have been able to get the form to render, but when I click the submit button for my form I am hit with an error of: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/register/register Using the URLconf defined in Sub.urls, Django tried these URL patterns, in this order: admin/ home/ about/ addinfo/ register/ [name='register'] The current path, register/register, didn’t match any of these. In my views.py file I have it set up to where it should redirect the user back to the homepage like so: return redirect('home/') I have 2 urls.py files, one for the registration app and one for the Main app that renders the home page and other tabs. Here is my register.urls file: urlpatterns = [ path('register/', views.register, name='register') ] Here is my main urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('home/', views.homepage), path('about/', views.about), path('addinfo/', views.addinfo), path('', include('register.urls')) ] -
Using Django-admin startproject --template on invalid cert
I am attempting to pull a template off of a local server with an invalid cert. I was wondering if there was a way to run django-admin startproject --template insecurely? (Equivalent to cURL's -k command) -
How to reference a variable from outside it's loop scope in Django template
I am sorry if the title is poorly phrased, but what i am trying to do is to use a variable that was in a for loop outside of it's scope ( in another part of the template ) here is my template: <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in items%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> i want to be able to use that category variable so i can loop through all the items in that specific category and add them in the items <div>, if there is a better way to do this please guide me ! -
Custom Django context processor not returning any value
I have written a custom context processor to return some frequently-used variables. I have followed multiple tutorials and read the official documentation, but nothing is happening: the context processor is either not loading or not returning any value. I am not getting any errors. app name: auctions context_processors.py def test_context_processor(request): return { 'message': 'Hello, world.' } settings.py ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.media', 'auctions.context_processors.test_context_processor' ], }, }, ] ... layout.html ... <h1>{{ test_context_processor.message }}</h1> ... When I inspect the H1 element, it is empty - nothing was returned. It looks like this: <h1></h1> I have tried: loading the function in shell and trying it out (it works) Renaming the function Restarting server {{ test_context_processor['message'] }} (This generates an error) Complaining on SO All I can think of is that every tutorial example is using the context processor to return a list of objects from a database, whereas I'm just returning a plain string value. But surely that can't matter, right? Thanks! -
How to convert a django template to use bootstrap-table server-side pagination
I have a number of pages rendered by django templates to which I have applied bootstrap-table to implement column switching, client-side pagination, and multi-column sorting. This was after having created a fully functioning django template. My tables are very large and each column has multiple manipulations, such as: links to other pages on the site number formatting horizontal alignment (e.g. right-justify numbers) concatenating values from related tables, delimited by various strings (e.g. comma-delimiting) tooltips filling in empty values with "None" converting timedeltas to days or weeks ... A number of the manipulations utilize simple_tags and filters written in python. There's even one template that uses javascript to do some custom stuff with some colspans using bootstrap table events (e.g. $("#advsrchres").bootstrapTable({onAll: ...). And every example I look at that uses bootstrap-table's server-side pagination, there is no template and all the data is obtained using a "data-url" that returns JSON. I'm hoping I'm wrong about this, but my assessment is that I would have to rewrite all those cell decorations in the template in javascript or something. I haven't started looking into how to do it yet, so after much fruitless googling, I'm here to see if anyone knows a way to … -
Error: Invalid data. Expected a dictionary, but got InMemoryUploadedFile
I am getting the above error when trying to upload multiple pictures from react to django rest api. This is my django view code: def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.FILES.getlist('image[]'), many=True) print(posts_serializer) if posts_serializer.is_valid(): posts_serializer.save() return Response(posts_serializer.data, status=status.HTTP_201_CREATED) else: print('error', posts_serializer.errors) return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is a print from posts_serializer: PostSerializer(data=[<InMemoryUploadedFile: 1PSM Logo.png (image/png)>, <InMemoryUploadedFile: Microsoft-Azure-Fundamentals.png (image/png)>, <InMemoryUploadedFile: DP-900_ProductImage-1.png (image/png)>], many=True): id = IntegerField(label='ID', read_only=True) image = ImageField(max_length=100) Appreciate any help. -
django sitemap add dynamic queryset urls
In my django website i'm trying to create the sitemap using django's sitemap app, i found difficulties in adding some queryset filtered urls, in simple words in my home page i have the url / where you can find all the posts and i'm trying to add urls that filters those posts by category for ex like this: /?category=foo /?category=bar ,checked some questions here but none of them helped here is what i used to add the home url / class PostsSitemap(Sitemap): def items(self): return ['texts'] def location(self, item): return reverse(item) so what should i add to include the filtered posts urls -
Django Error during template rendering no such column
I'm completely new to Django and data bases. I was trying to show the list of the User's to-do lists using view.html. The error says "no such column:testapp_todolist.user_id". But I don't understand where this column is and how it is related to the red line in my view.html: {% for td in user.todolist.all %} Can you please explain in details how do I add this column? Thank you. P.s. Here's my models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", default=0) name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=200) complete = models.BooleanField() def __str__(self): return self.text -
Retrieving specific object *image* from user profile to display on frontend
I am trying to query set a specific image from the Django user. My goal is to let each image have it's own page, when you click on the image from the profile page it should send you to another page with that same photo and just the photo you clicked, the page that I have already done has all the photos in order from when you posted them, I have looked through the documentation of Django 3.0 and I cannot find a query set function that allows me to get the specific image from a specific user for the function single page in views.py. All my other functions work, just wanted to show them just in case yall needed to reference to my other views.py functions. If anyone could guide me a little that would be great. views.py def profile(request, user): img = Uploads.objects.filter(profile_id = request.user.profile) profile = Profile.objects.filter(user = request.user) context = {"profile": profile, "img": img} return render(request, "main/profile.html", context) def profile_uploads(request): profile = request.user.profile if request.method == "POST": form = Uploads_Form(data = request.POST, files = request.FILES) if form.is_valid(): form.instance.profile = request.user.profile form.save() obj = form.instance return redirect('/profile/<str:user>/') else: form = Uploads_Form() img = Uploads.objects.all() return render(request,"main/profile_uploads.html", {"img":img, … -
How to speed up processing time for postgres query that is using index scan?
I am currently having a problem with long sql processing with my application for certain queries that uses Django and postgres. Using the built in django.db.connections.queries I was able to see which queries were taking the longest. I have one more complicated query that joins together 12 different tables where the majority of the processing time is being spend Using pgAdmin I was able to use the 'Explain Analyze' tool to see where the bottleneck seems to be. Most of the time is spent with on Index Scans matching the table ids. Particularly a large chunk of time is spent in this nested loop inner join I want to optimize this query, but since it is already using indexes, I am not sure how to do so. -
Django: How to list or loop multiple classes .as_view() with very similar methods. (How to simplify mutiple classes that are very similar)
I have the following classes in views.py class Base(): def function: ***blah blah blah*** return data # a list of data [data1, data2, data3, ...] class JSONView1(Base,JSONClass) def get_data(self): json_data1 = list(Base().function()[0]) return json_data1 class JSONView2(Base,JSONBase): def get_data(self): json_data2 = list(Base().function()[1]) return json_data2 JSONView1 = JSONView1.as_view() JSONView2 = JSONView2.as_view() Mainly, in class Base I build a data list, then I create 2 classes, each one calling a specific data from class Base, e.g., JSONView1 calls data1 and JSONView2 calls data2. These JSON classes are important because they convert the data to a JSON script using JSONBase (no shown here for simplicity). Finally I use .as_view() in views.py because I will call them in urls.py. The problem is that this is ok for 2 Views, but what if I have +5. I don't want to create a class for each new data in the list because the only difference between the classes is just the index, 0,1,2,3,.... the rest is the same I would like to have something like for k in range(5): class JSONView[k](Base,JSONClass) def get_data(self): json_data[k] = list(Base().function()[k]) return json_data[k] JSONView[k] = JSONView[k].as_view() Iterate over the code itself changing the index. I'm not an expert so an example to … -
How can i turn this PHP and C# code into python i can use on my Django backend? [closed]
We're trying to integrate a payment gateway into our project. Our project uses a Django backend and the example code for the integration was given in both PHP and C#. I've been trying to translate the C# or PHP into working python so i can make a working API that calls the gateway but couldn't really do it, as there are many nuances i'm not familiar with in both PHP and C#. Here is the C# code: public string ClientId = "test_ClientId"; public string ClientSecret = "test_ClientSecret"; public string ENCRP_KEY = "test_ENCRP_KEY"; public class AuthToken { public string AccessToken { get; set; } public string Status { get; set; } } public class AuthSettings { public string Url { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string ENCRP_KEY { get; set; } } protected void Page_Load(object sender, EventArgs e) { AuthSettings myAuthSettings = new AuthSettings { Url = "URL being used for retrieving access token", ClientId = ClientId, ClientSecret = ClientSecret, ENCRP_KEY = ENCRP_KEY }; AuthToken myAuthToken = _download_serialized_object_data(myAuthSettings); Random random = new Random(); if (myAuthToken.Status == "1") { var values = new NameValueCollection { ["tij_MerchantEncryptCode"] = myAuthSettings.ENCRP_KEY, ["tij_MerchantPaymentAmount"] … -
Django form class Variables not updating from signals
I'm having a strange issue where it looks like my form is initially built on startup. I've got a variable that changes within it called location, and I can't get it to update properly. I have confirmed that the variable is updated properly via signals, so I just need to get the form to update somehow. Here's the code of the class based form: class Post(models.Model): Priority_Upload = models.FileField(default='priority', upload_to=Profile.location, blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) The variable that I have changed is Profile.location. It is initialized in profile as an empty string, "". I change it when the user logs in and on post updates, and in other parts of the code the variable is confirmed to be different. It just looks like when I define my class Post, it does it once and I can't figure out how to update it. Any help would be greatly appreciated. Thank you for your time in advance. -
POST http://localhost:8000/api/posts/ 500 (Internal Server Error)
I can not get rid of this error: POST http://localhost:8000/api/posts/ 500 (Internal Server Error) I am using a react frontend with a django rest api backend. I am trying to upload multiple images at once from an input form. It worked before with slightly different code for one image. Any ideas maybe? Here is my code: class App extends Component { state = { images: null }; handleImageChange = (e) => { this.setState({ images: e.target.files }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); for (var i = 0; i < this.state.images.length; i++) { form_data.append('image[]', this.state.images[i]); } let url = 'http://localhost:8000/api/posts/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; render() { return ( <div className="App"> <form onSubmit={this.handleSubmit}> <p> <input type="file" id="image" accept="image/png, image/jpeg" multiple onChange={this.handleImageChange} required/> </p> <input type="submit"/> </form> </div> ); } } export default App; class PostView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.POST.getlist('image[]')) for onepost in posts_serializer: if onepost.is_valid(): onepost.save() return Response(onepost.data, status=status.HTTP_201_CREATED) else: print('error', onepost.errors) return Response(onepost.errors, status=status.HTTP_400_BAD_REQUEST) -
Problems installing M2Crypto in python 3
I am building a web app in Django and use the django-paypal library for integration with paypal. The integration went without a problem, the problem is with the paypal encrypted buttons because to use that button/form I need to install M2Crypto. I am trying to follow this instructions, and I say trying because to be honest I don't quite understand them: https://gitlab.com/m2crypto/m2crypto/-/blob/master/INSTALL.rst For example, one of the instructions that I don't understand is: To install M2Crypto, you must be able to compile and link C sources against Python and OpenSSL I already install OpenSSL and install Swig following this youtube video: https://www.youtube.com/watch?v=HDD9QqLtAws The error generates when use pip install M2Crypto And the error is: Collecting M2Crypto Using cached M2Crypto-0.38.0.tar.gz (1.2 MB) Preparing metadata (setup.py) ... done Using legacy 'setup.py install' for M2Crypto, since package 'wheel' is not installed. Installing collected packages: M2Crypto Running setup.py install for M2Crypto ... error error: subprocess-exited-with-error × Running setup.py install for M2Crypto did not run successfully. │ exit code: 1 ╰─> [60 lines of output] running install running build running build_py copying src\M2Crypto\ASN1.py -> build\lib.win-amd64-3.10\M2Crypto copying src\M2Crypto\AuthCookie.py -> build\lib.win-amd64-3.10\M2Crypto copying src\M2Crypto\BIO.py -> build\lib.win-amd64-3.10\M2Crypto copying src\M2Crypto\BN.py -> build\lib.win-amd64-3.10\M2Crypto copying src\M2Crypto\callback.py -> build\lib.win-amd64-3.10\M2Crypto copying src\M2Crypto\DH.py -> build\lib.win-amd64-3.10\M2Crypto … -
Why I am getting Session is disconnected error in python socketio?
I am using python socketio with django. Why am i getting this error while getting session of sid? Can somebody help me with this? my server.py sio = socketio.Server(async_mode="eventlet") @sio.event def connect(sid, environ): user = environ.get("HTTP_USER") sio.save_session(sid, {'user': user}) @sio.event def join_game(sid, game_id): sio.enter_room(sid, game_id) error File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/middleware.py", line 63, in __call__ return self.engineio_app.handle_request(environ, start_response) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/socketio/server.py", line 597, in handle_request return self.eio.handle_request(environ, start_response) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/server.py", line 429, in handle_request socket = self._get_socket(sid) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/server.py", line 638, in _get_socket raise KeyError('Session is disconnected') KeyError: 'Session is disconnected' -
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Django Rest Framework
I have this function and i want to make an endpoint for updating (adding) points in an answer. Also when someone upvotes an answer i want them to append to voters list. So they cannot upvote again. But i get this weird error with unsupported operand. Do you have any idea why? Model: class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') serializer class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done', 'voters',) Viewset class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): addition_done = serializer.validated_data.get('addition_done', False) number_of_points = serializer.validated_data.get('number_of_points',) voters = serializer.validated_data.get('voters',) if not addition_done and self.request.user not in serializer.instance.voters.all(): number_of_points += 1 addition_done = True voters = voters.append(self.request.user) serializer.save(addition_done=addition_done, number_of_points=number_of_points, voters=voters) Error: Internal Server Error: /api/v1/answers/1/addpoints Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, … -
django runserver returns error when i run py manage.py runserver on a project my friends did how can i resolve this issue?
I wanted to open a Django file my friends did and I installed Django MySQL client etc.. but run server doesn't work, it works when I run my own other file so here's the error and SQL code I pip installed MySQL connector As well but it still didn't change anything do you guys have any suggestions to why the run server is encountering this problem? Requirement already satisfied: mysqlclient in c:\users\user\appdata\local\programs\python\python310\lib\site-packages (2.1.0) C:\Users\user>cd documents C:\Users\user\Documents>cd one_art C:\Users\user\Documents\one_art>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, … -
Api: Django with Api-Rest and Scrapy [ValueError: signal only works in main thread of the main interpreter]
I'm trying to return a dictionary with an Api, that dictionary is being filled with a Scrapy script from rest_framework.views import APIView from django.shortcuts import HttpResponse from scrapy.crawler import CrawlerProcess from scrapyProject.spiders.spider import ProductoSpider, outputResponse class Prueba(APIView): def post(self, request): dato = request.data['dato'] if dato == 'dato': datos = [] process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(ProductoSpider) process.start() datos = outputResponse return HttpResponse(datos) else: return HttpResponse("Adios", content_type='application/json') This is just an experiment. "outputResponse" is a global variable in my spider, and I've already checked out that the info is saving correctly with this: from scrapy.crawler import CrawlerProcess from spiders.spider import ProductoSpider, outputResponse def execute(): process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(ProductoSpider) process.start() return outputResponse print (execute()) This script it does works, but when I want to try the Api doing "POST" in postman I get this: Internal Server Error: /api/experimento Traceback (most recent call last): File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) … -
How to properly import CSV datasets to Django models with ManyToMany / ForeignKey relationships?
Novice alert! I want to use django-csv-importer 0.1.3.5 to import data to models with ManyToMany relationships. Should make different model for every relation or should I put everything in the same model? Also note that i want to allow registered users on my site to submit a form to that same model, would that still work? -
Django custom user not having password column, which is expected to have been inherited from AbstractBaseUser
I am a beginner trying to learn to program in django. I have begun my first website. All I want as of now is a registration form (and login form) to create accounts and for those accounts to be stored on a database. I have created a custom user class, and not defined any column called 'password'. If I was subclassing models.Model or something, I would expect it to throw a 'no such column' error. However, django's default user class has a password column and I am inheriting from it y subclassing AbstractBaseUser, right? This is my models.py for reference: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django.utils.translation import gettext as _ import datetime from django_countries.fields import CountryField # Create your models here. class UserProfile(AbstractBaseUser): phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False) country = CountryField() date_of_birth = models.DateField(max_length = 8, blank = False, null = True) sex = models.PositiveSmallIntegerField(_('sex'), choices = ((1, _('Male')), (2, _('Female')),) ) USERNAME_FIELD = "phone_number" REQUIRED_FIELDS = ['country', 'date_of_birth', 'sex'] Code to my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import … -
Plot routes from json file with location coordinates when searched using start and end locations
I have a json file as follows with all the route information such as start station, end station and waypoint information. I would like to plot the entire route if one searches the RouteId, start and end stations. So far I have tried Gmaps python in Jupyter which helps to plot the route automatically by taking the coordinates of origin, destination and waypoints as shown below. In order to plot in python, I convert the coordinates in the form of list of tuples. When I select list[0], etc I can plot the route for each RouteId. I want to plot in a similar way in a more interactive way using javascript / Flask / Django. If I search for a RouteId, I need to automatically get the path along with waypoints. How do I do that? [ { "RouteId": 0, "StartStation": "Rhenen", "EndStation": "Uitgeest", "StartLatitude": 51.95861053, "StartLongitude": 5.578333378, "EndLatitude": 52.52166748, "EndLongitude": 4.701666832, "Segments": [ { "WaypointLatitude": 52.02000046, "WaypointLongitude": 5.548611164, "WaypointStation": "Veenendaal Centrum" }, { "WaypointLatitude": 52.0280571, "WaypointLongitude": 5.53138876, "WaypointStation": "Veenendaal West" }, { "WaypointLatitude": 52.06416702, "WaypointLongitude": 5.369999886, "WaypointStation": "Maarn" }, { "WaypointLatitude": 52.0652771, "WaypointLongitude": 5.258611202, "WaypointStation": "Driebergen-Zeist" }, { "WaypointLatitude": 52.29844, "WaypointLongitude": 4.95972, "WaypointStation": "Amsterdam Holendrecht" }, { "WaypointLatitude": 52.31222153, … -
not able to send email while user creation
I'm trying to put send a random 6 digit otp through email .Below code work for django 4.0 but not working in 3.2 , I'm not getting any error but when i createsuperuser in django 4.0 setup email send work but not the case in django 3.2 views.py @receiver(post_save, sender=CustomUser) def send_email_otp(sender, instance, created, **kwargs): if created: try: subject = "Your email needs to be verified to use this site" message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})/' email_from = settings.EMAIL_HOST_USER recipient_list = [instance.email] send_mail(subject, message, email_from, recipient_list) print(f"Email Sent to {instance.email}") except Exception as e: print(e) print("Something Wrong at send_email_otp") signals.py from django.db.models.signals import pre_save from .models import CustomUser def updateUser(sender, instance, **kwargs): user = instance if user.email != '': user.name = user.email pre_save.connect(updateUser, sender=CustomUser) I'm not sure what can be the problem,please help me to identify and fix . -
Problems placing formsets in wizard forms
I have a question regarding a multi form step wizard, in 3 steps I am using form sets that I have previously set up from the views and rendering it in the template. Now I see that when using the wizard you have to make some modifications to the view, it is something that does not know how to mix the view with the wizard and the formset. I already saw how it is used with simple forms but with formset I have not found tutorials that explain it. I imagine that when I make that change I also have to make adjustments to the template? Percent I was checking django-formtools-addons and django-multipleformwizard but I didn't understand the documentation views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = … -
I am getting error while installing Herocu with snap
Here is problem. I installed heroku before But i did not recognized herocu commands like heroku login