Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'myApp' deploying django on planethoster with n0c
I'm struggling with n0c and wsgi (with passenger), it works in developpment but not while deploying The error message /opt/passenger/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Traceback (most recent call last): File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/opt/alt/python310/lib64/python3.10/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 719, in _load File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/ambnvnpa/kriill/passenger_wsgi.py", line 1, in <module> import kriill.src.kriill.wsgi File "/home/ambnvnpa/kriill/kriill/src/kriill/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/opt/alt/python310/lib64/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'home' passenger_wsgi.py I added the multiple dots at the difference of the tutorial (https://kb.planethoster.com/guide/astuces-techniques/installer-django-sur-world/) because of my folder architecture. import kriill.src.kriill.wsgi … -
How to use Django backend templet variable in JS
I want to use backend data in the js file. return render(request, "class.html", {'all_classes':all_class}) I want to use it in the JS 'all_classes'. I know for the HTML - <select name="subject_class" type="text" class="form-control" required > {% for class in all_classes %} <option value="{{ class.class_name }}">{{ class.class_name }}</option> {% endfor %} </select> but please give me an idea for the javascript. -
Get all tags, if post has tags then mark as selected and remaining as not selected in django
While editing post to update i'm getting only selected tags for that post, how can i get all tags and with selected option for particular post. For example i have 4 tags and 1 tag is assigned to a post, when i edit that post to update i should get assigned tag as selected and remaining 3 tags as not selected. so that i can assign remaining tags to post if i wanted. And is there any way that i can create extra tags while updating post. For reference i've uploaded image below in that i got only selected tag i want to show remaining non selected tags also. models.py class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Card(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=150, unique=True) desc = models.TextField() img = models.ImageField(upload_to='uploads/') date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(blank=True, null=True) published = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title views.py @login_required(login_url = '/login/') def edit(request, pk): edit_list = Card.objects.get(id=pk) edit_tags = Card.objects.filter(id=pk) tag = Tag.objects.all() context = { 'edit_list': edit_list, 'edit_tags': edit_tags, 'tag':tag, } return render(request, 'edit-post.html', context) HTML <div class="container my-5"> <form action="{% url 'post_update' edit_list.pk %}" method="post" enctype="multipart/form-data">{% csrf_token %} <div … -
Signifianct Reduction in Performance after Installing Whitenoise
I installed and configured whitenoise to compress my static files, after which I ran collectstatic, and it appears everything ran successfully. It says 598 files have been post-processed. However, my CSS files are still the same size, and page load times have increased in production but are the same in development. Lighthouse scores have decreased from 95 to 87 after repeated tests. I must have configured something wrong, but I'm not sure what. Settings that probably aren't relevant have been removed for brevity. Settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "True") == "True" if DEBUG is True: ALLOWED_HOSTS = [] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } # HTTPS Settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS Settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', … -
Pass argument to view with reverse url django
url = reverse("school_management:student-list", args=(student.id,)) Hi, i am using django reverse url, here i am getting output as '/school/student/.2979' I am not getting why . is included here in output? -
how to display quarter column and its sub column after each quater based on month selection using xlsxwriter and django?
I want to display Quarter column (QTD) and its sub columns(BP,RE or RE(3+9) or RE(6+6) or RE(9+3),and Actuals) after each quarter based on month selection in date picker.Currently, QTD is displayed after each month.Now, I want to display it after every quarter instead of every month. For example, If we select April, May ,June ,I want to show QTD column and its sub columns after June month and if we select months April and May ,I want to show QTD column and its sub columns after May month. Also if we select April, May ,June,July, August months, I want to show first quarter QTD column and its sub columns after June month and second quarter column after August month. code: dat = report.objects.filter(date__gte=start_date, date__lte=end_date).values('date').distinct() date_list = [] for date_value in dat: month_year = str(date_value["date"].month) + "-" + str(date_value["date"].year) date_list.append(month_year) row_num = 2 header = ['Plant Locality', 'Plant Type', 'Market', 'Product', 'UOM', 'Previous Year FTM', 'Previous Year YTM'] for col_num in range(len(header)): worksheet.write(row_num, col_num, header[col_num], header_format) month_year_cell_start = 7 for date_year in date_list: worksheet.merge_range(0, month_year_cell_start, 0, month_year_cell_start + 8, date_year, merge_format) worksheet.merge_range(1, month_year_cell_start, 1, month_year_cell_start + 2, 'FTM', header_format) worksheet.merge_range(1, month_year_cell_start + 3, 1, month_year_cell_start + 5, 'YTD', header_format) if date_year.split('-')[0] … -
Django rest framework 'NoneType' object is not callable
I am new to django and drf. I've created a viewset for getting list of elements, adding new, updating and deleting, but I have some troubles when I try to create a viewset for getting detailed info about 1 element. Here is my urls.py urlpatterns = [ path('tasks', views.TaskViewset.as_view( { 'get':'list', 'post':'add', 'put':'update', 'delete':'delete' } )), path('tasks/<int:pk>', views.TaskDetailViewset.as_view( { 'get':'detail' } )) ] and here is my TaskDetailViewset from views.py class TaskDetailViewset(viewsets.ViewSet): def detail(self, request, pk, *args, **kwargs): #data = request.query_params task = models.Task.objects.get(id=pk) serializer = serializers.TaskSerializer(task) if serializer.is_valid(): return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) When I try to send request to http://127.0.0.1:8000/api/v1/tasks/1 I get 'NoneType' object is not callable and I don't understand where is the problem here -
VSCode showing choosing debugger instead of debug configuration when I try to create a launch.json file of django
I am currently following a tutorial for django and when I try and create a launch.json file through VSCode's debug, it only shows select debugger and prompts me to use Chrome or Edge as options for the debugger. I want to select django at the debug configuration menu, and I am wondering how I would get that to open/ -
django-unicorn resets mounted data after button click
I've built several small apps over the last weeks and stumbled every time over the same problem I couldn't figure out a solution with the docs or a google search. TL;DR I can't keep the results of a queryset initialized inside __init__ or mount() after clicking a button and changing any other value unrelated to the queryset. Is there a way to save/cache the results? Simple Example Initial position components/simple_unicorn.py from django_unicorn.components import UnicornView from any.app.models import MyObject class SimpleUnicornView(UnicornView): # Initialize my sample objects empty as I don't have any filter data, yet objects: MyObject = MyObject.objects.none() # A single filter value - In reality thos are multiple buttons filter_y: str = "" # any variable unrelated to the queryset show_button_x: bool = False def mount(self): self.load_data() def load_data(self): self.objects = MyObject.objects.filter(any_value=self.filter_y) # the execution of this query takes very long def updated_filter_y(self, value): # after changing varables related to the qs it is obvious the reload the data self.load_data() # this is where the problem pops up def toggle_button_x(self): # I'm only changing a variable not connected to the loaded data self.show_button_x = not self.show_button_x # Now I must execute the query again, otherwise self.objects is empty self.load_data() … -
Python regEx won't identify whitespace
I'm trying to replace some keywords in a document using Django Template, but unfortunately i'm dealing with normal user data, so my function receives a dictionary with keys that i'm pretty sure will contain a space. To deal with this risk i'm trying to do this workaround using regEx: from typing import Dict, List from django.template import Context, Template import docx from docxcompose.composer import Composer import re import django from django.conf import settings settings.configure(TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['.'], 'APP_DIRS': False }, ]) django.setup() def combine_documents(documents: List[dict], template_data: Dict): document_paths = [] placeholder = docx.Document() composer = Composer(placeholder) for i in range(len(documents)): document_paths.append(docx.Document(documents[i]["path"])) composer.append(document_paths[i]) composer.doc.add_page_break() context = Context(template_data, autoescape=False) document = composer.doc pattern = re.compile(r"\{{[\s\S]*\}}", re.IGNORECASE) for paragraph in document.paragraphs: for word in paragraph.text.split(): matches = pattern.finditer(word) # print(word) for match in matches: print(match.group()) if " " in match.group() and match.group() == word: print(match.group()) print("it's here") paragraph.text = paragraph.text.replace(" ", "_") template = Template(paragraph.text) print(template.render(context)) return "Ok!" combine_documents(documents = [{ "title": "Titulo", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }, { "title": "Outro título", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }], template_data={"Empresa": "FakeCompany", "Endereço Completo": "Rua 1", "Cidade": "São Paulo", "Estado": "São Paulo", "CEP": "12345678", "CNPJ": "317637667-0001", … -
Getting forbidden error when fetching endpoint when logged into account
Using React for the frontend and Django for the backend. I have a page in my website that displays all the user settings. When they load the page it fetches the data from the backend and fills out the form, when they submit the updated form it posts it to the backend. When I go to post this data when I'm logged into an account it gives me a forbidden error but when I'm logged out and post the form it goes through. Why would it be doing this? react post const onSubmit = async (e) => { e.preventDefault() const res = await fetch('/api/account/updatesettings', { method: "POST", headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ "test": "test" }) }) const data = await res.json() } api endpoint: class UpdateSettings(APIView): serializer_class = AccountSettingsSerializer def post(self, request, format=None): print("test") serializer = self.serializer_class(data=request.data) print(serializer.data) if serializer.is_valid(): pass -
Transcribe Streams of Audio Data in Real-Time with Python
I developed a web app using Django as a backend and a Frontend library. I have used django-channels, for WebSocket and I am able to record the audio stream from the front end and send it to Django over WebSocket and then Django sends it to the group. So I'm able to do live audio calls (let's say) but I have to transcribe the audio at the backend. (the main goal of the project) Things I'm looking forward to use this package to achieve transcription. I send base64 encoded opus codecs string from the front end to Django every second. It sends recorded audio every 1 second. My doubts - If we play Audio streams independently, we are only able to play the first string. We are not able to play 2nd, 3rd .... independently (padding issues or maybe more I'm not aware of), so I have used MediaSource at front end to buffer the streams and play. The question is can we convert this 2nd 3rd audio stream into text using the above-mentioned package? or I will have to do something else. (I'm looking for ideas here on how will this work) Also, the above-mentioned package uses a wav … -
Django click confirm pop then call function in views.py
I have a Django project ,now after clicking the url ,it will directly trigger the function in veiws.py. But I now want to add a JavaScript or bootstrap pop window, inside the window there is 2 buttons ,cancel or confirm, only when confirm button has been clicked ,the function in views.py will be called ,otherwise if cancel is clicked, just return to pervious page. url: path('wLoadr/', wLoadr_func, name='wLoadr_func'), template html: <li><a class="dropdown-item" href="{% url 'wLoadr_func' %}">wLoadr</a></li> views.py: def wLoadr_func(request): # there are some wLoadr_func code here .....omit code return render(request, 'wLoadr/wLoadr_base.html') Any friend can help ? -
Django Form fields disappearing after redirect to login page
I am using a Django form for a user login page. When the user has an incorrect login, it goes back to the login page. However, when it does this, the form input fields are gone, and the user can't enter anything, because the inputs just... aren't there. Note that it displays and functions correctly when I click on the login button in the navbar that goes to "\login". It's just after the postlogin view is run that the inputs disappear. After I run the postlogin view, it looks like this: what it looks like after I redirect to the login page It's supposed to look like this: what it is supposed to look like Here is my login and my post login view: def login(request): # Rendering login page assert isinstance(request, HttpRequest) return render( request, 'app/login.html', { 'title': 'Login', 'message': 'Login to your account', 'year': datetime.now().year, 'form':form } ) def postlogin(request): email=request.POST.get('email') pasw=request.POST.get('password') try: # if there is no error then signin the user with given email and password user = authe.sign_in_with_email_and_password(email, pasw) except: message="Invalid credentials!" # return to login page if password and email was invalid return render(request,"app/login.html", {'message':message, 'current_user': authe.current_user}) # set current session with user token … -
How do i pre-populate Django ModelForm fields
This form requires a student to login before filling it out. I want the input field with placeholder Enter Your Username to be pre-populated with the username of the individual filling it out. Here is my models.py class User_detail(models.Model): username = models.CharField(max_length=255, default="") first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") email = models.EmailField(max_length=255, default="") date_of_birth = models.DateField(null=False, blank=False, default="") gender = models.CharField(max_length=50, choices=GENDER, default="") tel = PhoneNumberField() def __str__(self): return self.email Here is my views.py from django.contrib.auth.decorators import login_required from .forms import * def signin(request): if request.user.is_authenticated: return redirect(profile) if request.method == "POST": form = Signin(request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect("profile") else: messages.error(request, "Invalid credentials") return redirect("signin") else: form = Signin() return render(request, "accounts/login.html", {"form": form}) @login_required(login_url="signin") def user(request): if request.method == "POST": form = Userdetail(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request, "You Have Successfully updated your details") return render(request, "thanks.html") else: form = Userdetail() return render(request, "accounts/User details.html", {"form": form}) Here is my Forms.py class Signin(forms.Form): username = forms.CharField( max_length=255, widget=forms.TextInput(attrs={"placeholder": "Enter Your Userame"}), ) password = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={"placeholder": "Enter Your Password", "id": "password"} ), ) class Userdetail(forms.ModelForm): class … -
Export data as excel from class based view
I have class based view and when request is post, self.readdb() will give dictionary result to self.db_result variable which will be populated as html table. This is working fine. I need to export this table as excel. My view.py class Download(View): def __init__(self, logger=None, **kwargs): self.logger = logging.getLogger(__name__) self.db_result = [] def post(self, request): if request.method == 'POST': form = DownloadForm(request.POST, request.FILES) if form.is_valid(): self.db_result = self.readdb() if self.db_result != False: return render(request,'download.html',{'present': self.db_result[0]}) <table class="presenttb"> <caption>Present in DB</caption> <tbody> {% for key, value in present.items %} <tr> <td> {{ key }} </td> <td> {{ value }} </td> </tr> {% endfor %} </tbody> <a href="{% url 'export_excel' %}">Download excel file</a> </table> {% endif %} I tried following which is generating excel file when click but it doesn't have any data. print(self.db_result) in get function is printing []. Looks like result from "post" is not available in "get". def get(self, request): if request.method == 'GET': if request.path_info == '/export/excel': print(self.db_result) response = self.export_users_xls() return response def export_users_xls(self): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachement; filename="report.csv"' print(self.db_result) writer = csv.writer(response) writer.writerow(['Command', 'XML data']) return response How can I access self.db_result from "post" function in "get" so that I can generate excel file. If … -
Output Blog Posts on Profile w/ Python & Django
I've been trying to output a specific user's blog posts to their profile page and can't seem to figure it out. I'm relatively new to Django and have yet to see an entry here with class-based views. Here is what I have so far: views.py class ProfilePageView(DetailView): model = Profile template_name = 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): #users = Profile.objects.all() user_posts = blogPost.objects.filter(author=self.request.user) page_user = get_object_or_404(Profile, id=self.kwargs['pk']) context = super(ProfilePageView, self).get_context_data(*args, **kwargs) context["page_user"] = page_user return context models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(blank=True, null=True, upload_to='images/profile/') twitter_url = models.CharField(max_length=255, null=True, blank=True) linkedIn_url = models.CharField(max_length=255, null=True, blank=True) github_url = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): #return reverse("details", args=(str(self.id))) return reverse('home') -
How to tell if the current user is authenticated in Firebase using Django
I'm using Django with Pyrebase to access Firebase for authentication and logins. I'm new to all of them so bear with me. I think I am able to successfully log the user in, but at that point I can't figure out how to change the html file to only show certain parts if the user is logged in. I've tried {% if user.is_authenticated %} as well as {% if current_user.is_authenticated %} as well as {% request.user.is_authenticated %} and {% request.current_user.is_authenticated %} but all of them act as if they've returned false even though the user is authenticated via user = authe.sign_in_with_email_and_password(email, password). Here's my views.py: def login(request): # Rendering login page assert isinstance(request, HttpRequest) return render( request, 'app/login.html', { 'title': 'Login', 'message': 'Login to your account', 'year': datetime.now().year } ) def postlogin(request): email=request.POST.get('username') password=request.POST.get('password') try: # if there is no error then log in the user with given email and password user = authe.sign_in_with_email_and_password(email, password) except: message="Invalid credentials." print("invalid") return render(request,"app/login.html",{'message':message }) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"app/home.html",{"email":email}) And my login.html: {% if request.current_user.is_authenticated %} <form id="logoutForm" action="/logout/" method="post" class="navbar-right"> {% csrf_token %} <ul class="nav navbar-nav navbar-right"> <li><span class="navbar-brand">Hello {{ user.username }}!</span></li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> </form> {% else %} <ul class="nav … -
(Django) Can't Update Post On My Blog (function based view)
After displaying my posts, I don't manage to Edit any of them. When I print the instance variable which is in views.py in my terminal, it displays only the title and the author like this title - author, which is the method defined in models.py. Help please! Views.py @login_required(login_url='login_view') def update_post_view(request, post_id, slug=None): instance = Article.objects.get(id = post_id) if request.method == 'POST': form = UpdatePostForm(request.POST, request.FILES, instance=instance) if form.is_valid(): form.save() return redirect('posts_view') else: form = UpdatePostForm(instance=instance) return render(request,'update_post.html', {'form':form}) forms.py class UpdatePostForm(forms.ModelForm): class Meta: model = Article fields = ('author',) title = forms.CharField(max_length=255, label='username', widget= forms.TextInput(attrs= {'placeholder':'Title...', 'class': 'title'})) body = forms.CharField(max_length=255, label='body', required=True, widget=forms.Textarea(attrs={'placeholder':'Start writing your post...'})) urls.py path('update_post/<int:post_id>/<slug:slug>', views.update_post_view, name='update_post_view') update_post.html {% extends 'base.html' %} {% block title %}Update Post{% endblock %} {% block content %} <h2>Update Posts...</h2> <form action="" method="POST"> {% csrf_token %} <div> <h3>{{form.title}}</h3> <small>{{form.author}}</small> <p>{{form.body}}</p> </div> <button class="btn btn-secondary">Update</button> </form> {% endblock %} -
TemplateDoesNotExist at / template not defined
I have tried to set-up my first simple CBV in Django but despite reading literally all related information and trying out all possible path options to my index.html I receive the same message from above. Last version follows: Python-Version: 3.9.13 Django: 4.1 **urls.py** from django.urls import path from core.views import Servicelist urlpatterns = [ path('', Servicelist.as_view(), name='service') ] **views.py** from core.models import Item from django.views.generic.list import ListView class Servicelist(ListView): model = Item template_name:'paraticosmetics/index.html' context_object_name = "items" I receive message that index is not defined Pylance(reportundefinedVariable) **setting.py** **setting.py** INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'core.apps.CoreConfig', ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR/'core/templates/paraticosmetics/'], "APP_DIRS": True, .... -
Django Folium Marker
I am newbie and I am making a map visualization in Django. I will use both heatmap and marker on my website. I have not encountered any error in my heat map but when I put on the folium markers, I encountered an error in the markers: 'tuple' object is not callable. How can this be fix? Is there a way? Views def index(request): data = IncidentGeneral.objects.all() data_list = IncidentGeneral.objects.values_list('user_report__latitude', 'user_report__longitude', 'accident_factor') address = IncidentGeneral.objects.values('user_report__address') latitude = IncidentGeneral.objects.values('user_report__latitude') longitude = IncidentGeneral.objects.values('user_report__longitude') coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1] map1 = folium.Map(location=[14.676208, 121.043861], tiles='CartoDB Dark_Matter', zoom_start=12) plugins.HeatMap(data_list).add_to(map1) plugins.Fullscreen(position='topright').add_to(map1) # folium.Marker(tooltip = 'Click for more', popup=address).add_to(map1) # map1.add_child(folium.Marker(location=[latitude, longitude],popup="Hi I am a Marker",icon=folium.Icon(color="green"))) for id,row in coordenadas(): folium.Marker(location=[row['latitude'],row['longitude']], popup=row['Confirmed']).add_to(map1) # folium.Marker(coordenadas).add_to(map1) map1 = map1._repr_html_() context = { 'map1': map1 } return render(request, 'index.html', context) Models class IncidentGeneral(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True) user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE) accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True) accident_subcategory = models.ForeignKey(AccidentCausationSub, on_delete=models.SET_NULL, blank=True, null=True) collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True) collision_subcategory = models.ForeignKey(CollisionTypeSub, on_delete=models.SET_NULL, blank=True, null=True) crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True) weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True) light = models.PositiveSmallIntegerField(choices=LIGHT, blank=True, null=True) severity = models.PositiveSmallIntegerField(choices=SEVERITY, blank=True, null=True) movement_code = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserReport(models.Model): PENDING … -
Django DeleteView only works on second attempt
Bit of a strange one and wondering if anyone else here has come across this. I have a standard DeleteView with the GET showing a confirmation page containing a form that posts to the delete view. Whenever I click confirm nothing happens - the post to the view occurs and it redirects as intended, however the object is not deleted. If I then perform the action a second time the object is deleted. class MetricDeleteView(DeleteView): template_name = "dashboard/administration/metric/delete.html" button_title = "Update metric" form_class = MetricUpdateForm model = dashboard_metric # Override post to test manually delete object but same thing happens def post(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() print(self.object) self.object.delete() return HttpResponseRedirect(success_url) @cached_property def dashboard_score(self): return self.get_object().score def get_success_url(self): return reverse_lazy("administration:dashboard:update_score", kwargs={ 'dashboard': self.dashboard_score.dashboard.id, 'pk': self.dashboard_score.id }) I can't for the life of me figure out why this is occurring across all some models on my site. -
How to access key values of ordered dict in django serializer query
I work with Django-Rest api and have serializer that returns me the data like this my_ordered = [OrderedDict([('idx', '1231233'), ('rock', None), ('Email', 'albundy@abc.com')]), OrderedDict([('idx', '1212333'), ('paper', None), ('Email', 'peggybundy@abc.com')])] type(my_ordered) <class 'collections.OrderedDict'> I tried to access its 'Email' key like this for trainer, training in my_ordered.items(): print(training['Email']) NameError: name 'OrderedDict' is not defined Also tried import collections my_ordered = [collections.OrderedDict([('idx', '1231233'), ('rock', None), ('Email', 'albundy@abc.com')]), collections.OrderedDict([('idx', '1212333'), ('paper', None), ('Email', 'peggybundy@abc.com')])] #my_ordered.keys()[2] for trainer, training in my_ordered.items(): print(training['Email']) my_ordered.keys()[2] AttributeError: 'list' object has no attribute 'items' but this also not helped. How to access key values in ordered dictionary -
Is it possible to use import_export Django lib to export data from more than one table in a same xls doc?
class OrderResource(resources.ModelResource): class Meta: model = Order class PaymentOrderAdmin( ImportExportMixin, admin.ModelAdmin): resource_class = OrderResource -
Using Django Template Tags in Markdown
I am using Markdown to format/style my blog posts in Django. The problem is that the Django template tags in Markdown don't seem to work for me. More details: Markdown module: Markdown==3.2.1 details.html (my blog posts template file) {% block content %} ... </p> {{ post.body|markdown }} <p> ... {% endblock %} Next, in the body of my blog post, I tried to add an HTML tag that includes a django template tag: <img src="{% static '/img/image.jpg' %}" alt="image"> and I see this in the result: Any ideas what I'm doing wrong?