Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a Django website to post articles?
I'm new to django and I really have no idea how should I structure a website for the purpose of posting articles (like tutorials). I'm not asking for specific code, but how does it work? Should I make a base template and a html file for every single article that I'll post? If so, how should be the folder structure in the project? How can I show a list of all those articles and redirect to them if a user clicks on it? Should I link them to a database entry? How can I do that? I'm asking those things because I only did things that involved reading content from the database/model and showing it on a template, but articles need images and other special construction that a blog textfield would not be enough. If it is too confusing, just say so, and I'll try to put in another words, I'm really struggling to put my question into words. -
Im having an issue where it says my form is invalid when I submit it?
models.py class Contact(models.Model): BookID = models.CharField(max_length=30) BookTitle = models.CharField(max_length=30) Author = models.CharField(max_length=35) UploadImage = models.ImageField(upload_to='ContactImg') def __str__(self): return self.BookId views.py def ContactUs(request): user_form=ContactForm() if request.method == 'POST': user_form = ContactForm(request.POST) if user_form.is_valid(): # we load our profile instance Contact.BookId = user_form.get('BookId') Contact.BookTitle = user_form.get('BookTitle') Contact.Author= user_form.get('Author') Contact.UploadImage= user_form.get('UploadImage') Contact.save() return redirect('readingTime:home') else: # Invalid form # messages.error(request, 'Form contains errors. Double check') print(user_form.errors) messages.error(request, 'Form contains errors. Double check') # user_form = user_form.errors # user_form = RegisterForm() else: # Blank form since we do not have an HTTP POST user_form = ContactForm() return render(request,"readingTime/ContactUs.html") Forms.py class ContactForm(forms.Form): BookID=forms.CharField(max_length=30,required=True) BookTitle=forms.CharField(max_length=30,required=True) Author=forms.CharField(max_length=35,required=True) UploadImage=forms.ImageField() class Meta: model = Contact fields = ('BookID', 'BookTitle', 'Author','UploadImage') html <form id="user_form" class="contact-form" method="post" action="{% url 'readingTime:ContactUs' %}" enctype="multipart/form-data"> <div class="contact-container"> <h2>Request To Add A Book</h2> {% csrf_token %} Bookd Id (ISBN) <input type="text" name="BookID" value="" size="30" /> <br /> Book Title <input type="text" name="BookTitle" value="" size="50" /> <br /> Author(Full Name) <input type="text" name="Author" value="" size="30" /> <br /> Book Cover(Optional)<input type="file" id="UploadImage" name="UploadImage"> <br/> <!-- Submit button--> <div> <button type="submit" class="submit-button">Send Request</button> </div> </div> </form> My form gets sent over to the admin side of the website but it appears with the form is not valid … -
Linode server not sending password reset apps
This is my setup. I have allowed less secure apps and did the captcha in google. This is the error message that I am getting. Error: ** SMTPServerDisconnected at /password-reset/ Connection unexpectedly closed** I have a firewall but ran the command sudo ufw allow 465 I really don't know what else could be done to make the password reset work EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = config['EMAIL_USER'] EMAIL_HOST_PASSWORD = config['EMAIL_PASS'] DEFAULT_FROM_EMAIL = True -
How can i add first name and last name in my registration form
i'm working with Django and i customized the Auth System to have an email registration instead of the username, i would like to add the first name and the last name input in my form registration. This is my code from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): username = models.CharField(max_length=255, unique=False, blank=True, null=True) email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] Already i did <form method="post"> {% csrf_token %} <input type="text" name="first_name"> <input type="text" name="last_name"> {{form.as_p}} <input type="submit"> </form> as you can see i added two html field in my form but it doesn't work, both of the columns (first_name + last_name ) still empty in my database table -
Django Channels sleep between group sends
what i am trying to achieve is quite simple as you can read in the title but i can't get it to work "to sleep between two sends". my code: await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(answer_data), } ) await asyncio.sleep(5) await self.channel_layer.group_send( str(self.game_link), { "type": "group_message", "text": json.dumps(data), } ) what happens here is that both send at the same time after sleep is done. -
Permission to write for a view function in django
My question is simple : i have in my django view file a basic function who create a file : fichier = open("data.txt", "a") fichier.write("Hello world") fichier.close() I have begin to test my project online with digitalocean. On local every thing is perfect. But online, when I click on the function with a button in the template page, which call a function in the view.py, it's not word... But If i try the same code in a file alone and i execute it with the console all works fine. So what can i do to permit a function which is in the view.py file to have the permission to write. Thanks in advance ! -
How to migrate to Posgresql?
return self.cursor.execute(sql) django.db.utils.DataError: NUMERIC precision 10440 must be between 1 and 1000 LINE 1: ...RIMARY KEY, "item" varchar(100) NOT NULL, "price" numeric(10... ^ -
Django WebRTC TURN/STUN/ICE Server
So I have a basic question about WebRTC with Python Django. Maybe I start at the beginning: So is it possible that Python Django can serve as a Server for WebRTC? I think in generell it shouldn't be that hard, because how I saw the WebRTC client only needs a Websocket connection. I hope anybody can help me with that. Btw. I use Django Channels, so I think it is possible to build this connection, but how? :) -
The django field to save the file path with id and show nonevideo.mp4 in the file extension
I tried to save the video file with id of the video but it show none instead of id and the file extension be like nonevideoauthor.mp4 my file extension in the video model def get_video_filepath(self, filename): return 'post-videos/' + str(self.id) + str(self.author) + 'video.mp4' the video model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to=get_video_filepath, validators=[validate_file_extension, validate_file_size]) -
How do I overcome this login page error from a downloaded template for Django
I wanted to test out a template and see all of its components (models, initial, migrate etc.) When I run python migrate.py runserver, I am taken to the login/ sign up page that is probably setup by the designers of the template. I cannot really seem to sign up with any details, since I get this error: OperationalError at /register/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.1.5 Exception Type: OperationalError Exception Value: no such table: auth_user Exception Location: C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\puru1\Downloads\django-datta-able-master\django-datta-able-master', 'C:\Python39\python39.zip', 'C:\Python39\DLLs', 'C:\Python39\lib', 'C:\Python39', 'C:\Users\puru1\AppData\Roaming\Python\Python39\site-packages', 'C:\Python39\lib\site-packages', 'C:\Python39\lib\site-packages\win32', 'C:\Python39\lib\site-packages\win32\lib', 'C:\Python39\lib\site-packages\Pythonwin'] Server time: Sat, 03 Apr 2021 22:35:54 +0000 Traceback Switch to copy-and-paste view C:\Python39\lib\site-packages\django\db\backends\utils.py, line 84, in _execute return self.cursor.execute(sql, params) … ▶ Local vars C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute return Database.Cursor.execute(self, query, params) … ▶ Local vars I have attached an image showing the files that the folder contains, as seen in visual studio code What part do I have to delete to just be able to view the webpage without going through the login page? Thanks! -
Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
This is my first time customizing User, the app is working ok, I can edit user fields, sign up, sign in, visit the dashboard. However, when I want to visit another user I'm getting this error: AttributeError at /account/dashboard/10/ Any help on how to resolve this is more than welcome, thank you! urls: path('account/dashboard/', dashboard, name = 'dashboard'), path('account/dashboard/<pk>/', guest_dashboard, name = 'guest_user'), view: #Guest Dashboard @login_required def guest_dashboard(request, pk): user_other = User.objects.get(pk = pk) already_followed = Follow.objects.filter(follower = request.user, following = user_other) if guest_dashboard == request.user: return HttpResponseRedirect(reverse('dashboard')) return render(request, 'account/dashboard-guest.html', context = {'user_other' : user_other, 'already_followed' : already_followed}) settings: AUTH_USER_MODEL = "accounts.User" models: class MyUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser Must have is_staff = True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser Must have is_superuser = True') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null = False) username = models.CharField(max_length=264, null = True, blank = True) is_staff = models.BooleanField(ugettext_lazy('Staff'), default = False, help_text = ugettext_lazy('Designates whenever the … -
When I try to fetch data to a url with {% url %} for implementing PayPal checkout, urls are not found. Why?
I am implementing PayPal checkout for my website using Django, and having some trouble with url. Once the payment is complete I want to fetch data to 'payment_complete' view and then send the customer to 'payment_successful' page. But it does not work. The urls 'payment_complete' and 'payment_successful' are not found. Do you know why ? Thank you for your help. checkout.html {% extends 'main.html' %} {% load static %} {% block title %} Checkout {% endblock title %} {% block content %} <div> <div id = "proceed-to-payment-div"> <div id="paypal-button-container"></div> </div> </div> <script src="https://www.paypal.com/sdk/js?client-id=Ac7c5n8LPoPfEjQjK-PlndbIoLLYm5t5z7Pw8YSPVhMtpU5PJDLmjDxDXO5sYZGl4sBNX-AdgjbGxOuv&currency=EUR" ></script> <script type="text/javascript"> var basket_total = '{{basket.get_total_price}}'; console.log(basket_total); </script> <script type="text/javascript" src=" {% static 'js/payment/checkout-paypal.js' %} "></script> {% endblock content %} checkout-paypal.js function initPayPalButton() { paypal.Buttons({ style:{ color:'white', shape:'rect', size:'responsive' }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: parseFloat(basket_total).toFixed(2) } }] }); }, onApprove: function(data) { var url = "{% url 'payment:payment_complete' %}" return fetch(url, { method:'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ orderID: data.orderID }) }).then(function () { location.href = "{% url 'payment:payment_successful' %}"; }); }, }).render('#paypal-button-container'); }; initPayPalButton(); urls.py (core of the website) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static … -
React Router redirects to BASE_URL when I try to load a page in a new tab
I have been working on a react project and I ran into a problem about 4 days ago. When I try to open a link in a new tab, it redirects to the home/BASE url. Please I need assistance fixing the bug. render route method export const renderRoutes = (routes = []) => ( <Suspense fallback={<Loader />}> <Switch> {routes.map((route, i) => { const Guard = route.guard || Fragment; const Layout = route.layout || Fragment; const Component = route.component; return ( <Route key={i} path={route.path} exact={route.exact} render={(props) => ( <Guard> <Layout> {route.routes ? renderRoutes(route.routes) : <Component {...props} />} </Layout> </Guard> )} /> ); })} </Switch> </Suspense> ); GuestGuard const GuestGuard = (props) => { console.log(props, BASE_URL) if (props.isLoggedIn) { console.log(BASE_URL) return <Redirect to={BASE_URL} />; } return ( <React.Fragment> {props.children} </React.Fragment> ); }; GuestGuard.propTypes = { isLoggedIn: PropTypes.bool.isRequired } const mapStateToProps = (state) => ({ isLoggedIn: state.auth.isLoggedIn }) export default connect(mapStateToProps, )(GuestGuard); AuthGuard const AuthGuard = ({ children, isLoggedIn }) => { // console.log(children, 393) if (!isLoggedIn) { return <Redirect to="/auth/signin-1" />; } console.log("LOGGED IN", children.props) return ( <React.Fragment> {children} </React.Fragment> ); }; AuthGuard.propTypes = { isLoggedIn: PropTypes.bool.isRequired } const mapStateToProps = (state) => ({ isLoggedIn: state.auth.isLoggedIn }) export default connect(mapStateToProps, )(AuthGuard); App … -
Azure Web App - Python: can't open file 'manage.py': [Errno 0] No error
I am trying to deploy my Django application with Azure DevOps as a Azure Web App. The application is pipelined and build to the web app but it will not run. When I am trying to run py manage.py runserver in the Diagnostic Console i get the error below: D:\Python34\python.exe: can't open file 'manage.py': [Errno 0] No error Does anyone have a clue on what the issue might be? This is the first project I am trying to deploy with Azure so my knownledge is not very good. The project files are stored on the following location on the server D:\home\site\wwwroot\<applicationName> Thank you for your help. -
Django How to Add Custom Location Field?
In my profile model I want to hold country or city, country values in custom location field. Also country value must be provided. So I made a LocationField which implements MultiValueField. I'm not advanced at Django, so how can I make only country required? Also I'm not sure this code is totally right. P.S: I can make city and country fields in Profile but holding in them in one field seems more neat. models.py from cities_light.models import City, Country class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') first_name = models.CharField(verbose_name='first name', max_length=10, null=False, blank=False, default='baris') last_name = models.CharField(verbose_name='last name', max_length=10, null=False, blank=False, default='baris') profile_photo = models.ImageField(verbose_name='profile photo', ) #TODO add upload to about = models.CharField(verbose_name='about', max_length=255, null=True, blank=True) spoken_languages = models.CharField(verbose_name='spoken languages', max_length=255, null=True, blank=True) location = LocationField() class LocationField(MultiValueField): def __init__(self, **kwargs): fields = ( Country(), City() ) super.__init__(fields=fields, require_all_fields=False, **kwargs) -
BSModalDeleteView (django-bootstrap-modal-form) ignors get_success_url
My BSModalDeleteView is just ignoring what I have entered into my get_success_url(self). Whatever I try, I'll be redirected to the url of the deleted element (http://127.0.0.1:8000/rentals/part/delete/34/) which leads logically to an error since the object was just deleted. Has anybody an idea of what is wrong? Everything works as expected (the reverse_lazy provides the expected url) views.py class ConstituentPartsDeleteView(LoginRequiredMixin, BSModalDeleteView): model = ConstituentParts success_message = 'Part deleted.' template_name = 'modal_delete.html' def get_success_url(self): return reverse_lazy('rentals:rental', kwargs={'pk': self.object.rental_unit.pk, 'tab': 'home'}) There is no get_abslute_url() in this model. Here is how it is called in the template script block: $(".bs-modal-part").each(function () { $(this).modalForm({ formURL: $(this).data('part-url'), isDeleteForm: true, }); }); Thank you in advance. -
How to send JSON to Django URL using AJAX? [duplicate]
I have the following data: data = [ { "topics": [ "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.19" ] }, { "filters": "[{"QType_id":"1","QSubType_id":"6","QCount":"10"}]" } ] I want to send it to Django URL. I tried the following java code: jQuery.ajax( { 'type': 'POST', 'url': "http://127.0.0.1:8001/recievejson", 'contentType': 'application/json', 'data': [ { "topics": [ "2.12", "2.13", "2.14", "2.15", "2.16", "2.17", "2.18", "2.19" ] }, { "filters": "[{"QType_id":"1","QSubType_id":"6","QCount":"10"}]" } ], 'dataType': 'json', 'success': "" } ); The following is django function to receive that request: def recievejson(request): if request.method == 'POST': print("SUCCESS") for key, value in request.POST.items(): print(key, value) return JsonResponse({"status": 'Success'}) I get nothing on receiving end Any recommended solution? -
Why cant i change the error_message of a form in Django?
class Rezervaciaform(forms.Form): keresztnev=forms.CharField(label="Meno:",error_messages={'required': 'Prosim vyplnte'},validators[validators.MinLengthValidator(2,'Prosim podajte cele meno')]) #the validator shows up,but the error_message doesnt change -
'Custom user with this Email address already exists' error when trying to update email using forms. Django
please read through my code, my question with screenshots and things i've already tried are after my code. managers.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_feilds): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_feilds) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_feilds): extra_feilds.setdefault('is_staff', True) extra_feilds.setdefault('is_superuser', True) extra_feilds.setdefault('is_active', True) if extra_feilds.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff = True')) if extra_feilds.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True')) return self.create_user(email, password, **extra_feilds) models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser, StripeConnectSetup from django import forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email', 'first_name', 'last_name') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email','first_name', 'last_name') views.py from django.shortcuts import render, redirect from .forms import CustomUserCreationForm, CustomUserChangeForm, StripeConnectSetupForm from .models import CustomUser from django.contrib.auth import login, logout from … -
how can i get the nearest prods depending on user's location?
i'm using geodjango .. i Installed Python 3 then GeoDjango Dependencies (GEOS, GDAL, and PROJ.4) , of course i had Set up a Spatial Database With PostgreSQL and PostGIS i want to get the nearest prods to my user's location ..this is the model class Prod(models.Model): userr = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name_business = models.ForeignKey(Page, on_delete=models.CASCADE, null=True, blank=True) description = models.CharField(max_length=5000, default="") disponibilite = models.BooleanField(default=True) prix = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True) Title = models.CharField(max_length=5000, default="") quantité = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) principal_image = models.FileField(blank=True) location = models.PointField(null=True,default=Point(0.0,0.0)) def __str__(self): return str(self.Title) class User(AbstractUser): geo_location = models.PointField(null=True,default=Point(0.0,0.0)) class Meta: db_table = 'auth_user' -
Django forms User form not summited
I need help with my code. I have read through the code several times and I didn't see anything wrong with it. The user is expected to submit a job application and redirect the user to the dashboard, but it did not submit the job application neither does it direct the user to the dashboard. here is my code: mode.py from django.db import models from django.contrib.auth.models import User class Job(models.Model): title = models.CharField(max_length=255) short_description = models.TextField() long_description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, related_name='jobs', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Application(models.Model): job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) content = models.TextField() experience = models.TextField() created_by = models.ForeignKey(User, related_name='applications', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import AddJobForm, ApplicationForm from .models import Job def job_detail(request, job_id): job = Job.objects.get(pk=job_id) return render(request, 'jobs/job_detail.html', {'job': job}) @login_required def add_job(request): if request.method == 'POST': form = AddJobForm(request.POST) if form.is_valid(): job = form.save(commit=False) job.created_by = request.user job.save() return redirect('dashboard') else: form = AddJobForm() return render(request, 'jobs/add_job.html', {'form': form}) @login_required def apply_for_job(request, job_id): job = Job.objects.get(pk=job_id) if request.method == 'POST': form = ApplicationForm(request.POST) if form.is_valid(): application = form.save(commit=False) application.job = job application.created_by = … -
How to make Django Form repeatedly submit in background while user is filling it in?
Background information about my project: I'm building a CV/Resume generator that automatically creates a CV/Resume based on the user filling out a form. I'm using a Django Crispy Form which has a submit button at the end that, when clicked, submits the user's input to a SQL database and redirects the user to their newly built CV/Resume (as a PDF). What I need help with: The goal is to have a form on the left side of the screen and a live view (HTML/CSS) of the CV/Resume on the right side, where the live view updates as the user is filling out the form. I've seen this kind of thing before, but never for a Django project (they tend to use JavaScript/React). What I'm thinking: Could I have a background process that does something like, when the user makes a change (e.g. is filling out the form), submit any new inputs to the SQL database every 5 seconds? Then the live view can extract any new inputs from the database and display it in real time? -
Hi! I'm not able to connect with "heroku redis" on django
I've followed all the steps in the following video: https://www.youtube.com/watch?v=fvYo6LBZUh8&t=166s However, I'm not able to connect with "heroku redis", I am using celery to implement periodic tasks. The error is the following: [2021-04-02 22:00:05,622: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-54-160-13-161.compute-1.amazonaws.com:12880//: Error while reading from socket: (10054, 'Se ha forzado la interrupción de una conexión existente por el host remoto', None, 10054, None). So, any idea of what could be happening would be great. ¡Thank you so much! -
How can I fetch attributes from User model using UserProfile's OneToOneField relationship?
I'd love to write a form where a user can change their data. So I have a User model and a UserProfile extension model, the last one looks like this: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) info = models.TextField('информация') def get_absolute_url(self): return reverse('user_profile', args=[str(self.user.username)]) How to generate a form where my user attribute would have all its parameters like username, email, first_name, last_name to be changed? So I could do something like this in the template: {% extends "layout.html" %} {% block content %} <h2>{{ title }}</h2> <div class="row"> <form method="POST" action="{% url 'profile_edit' user.username %}" class="col s12"> {% csrf_token %} {{ form.non_field_errors }} <div class="row"> <div class="input-field col s6"> {{ form.user.username }} {{ form.user.username.label_tag }} {% if form.user.username.errors %} <span class="helper-text">{{ form.user.username.errors }}</span> {% else %} <span class="helper-text">{{ form.user.username.help_text }}</span> {% endif %} </div> <div class="input-field col s6"> {{ form.user.email }} {{ form.user.email.label_tag }} {% if form.user.email.errors %} <span class="helper-text">{{ form.user.email.errors }}</span> {% else %} <span class="helper-text">{{ form.user.email.help_text }}</span> {% endif %} </div> </div> <div class="row"> <div class="input-field col s6"> {{ form.user.first_name }} {{ form.user.first_name.label_tag }} </div> <div class="input-field col s6"> {{ form.user.last_name }} {{ form.user.last_name.label_tag }} … -
how to display mapbox location in django template?
i created a django mapbox app my models.py class is : class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL ,blank=True,null=True) location2 = LocationField(map_attrs={"center": [51.42151,35.69439], "marker_color": "blue"},null=True, blank=True) and this is my views.py : def profile_page(request,id,slug): user_id=request.user.id profile = get_object_or_404(Profile,id=id,slug=slug) post = Post.objects.filter(profile=profile) mapbox_access_token = 'pk.eyJ1IjoibWlzdGVyZmgiLCJhIjoiY2tteHNmcjllMHJ4OTJwJ3-SkFRpWJtDDDwfrpg' context={ 'profile': profile, 'mapbox_access_token': mapbox_access_token } return render(request,'profile_page.html',context) and this is templates: <div class="col-12 col-xl-12 pr-0 pr-md-4 "> {{ profile.location2 }} <div class="border" id="map" width="100%" style='height:400px'></div> </div> <script> mapboxgl.accessToken = {{ mapbox_access_token }}; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10', center: [35.69439, 51.42151], zoom: 9, // bearing: 180 }); </script> mapbox location {{ profile.location }} shows like this (46.30637816268069, 38.065254395567706) in template but graphical mapbox doent show in template