Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert doc to pdf supported by all the operating systems using python
I want to convert my word doc file to pdf using Python. Most of the modules I tried creates pdf on win and mac machines but not on linux. What module should I use which will convert doc to pdf supported on all the platforms? -
django app static files are not loading on shared hosting (cpanel)
static files or my django project are not working when i try to access via domain name I'm using Linux based shared hosting cpanel. Here is the settings.py for static files. I run collectstatic command and now all site statics are collect in home/username/project_static but those files are not working on my site. Please help me in this regard or guide me correct process of static files for production STATIC_URL = 'domain.net' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'home/username/project_static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_URL = '' STATICFILES_DIRS =[ BASE_DIR/ 'static', "home/username/project_static/", ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
AttributeError: module 'authentication.views' has no attribute 'ajax_load_messages'
I am creating a clone twitter application for a project, very basic. no styling. As i started to implement a Direct Messaging. i encounter a problem. with the urls.py file. it seems to want a view of my ajax_load_messages from within authentication but i put that view within the chat app itself. i am unable to run server. what can i do to solve this? Image of urls.py file with error msg and directory visible -
How to set a loading page while Django views are loading
I have a Django app which has a view that pulls data from Bigquery before I render the data to the Frontend. This process of pulling data takes quite some time and it will load the frontend once the view is finished loading the data. Is there a way I could show a loading page while the Django Views are pulling the data then make it disappears once everything is ready? I tried using the code below: function onReady(callback) { var intervalId = window.setInterval(function() { if (document.getElementsByTagName('body')[0] !== undefined) { window.clearInterval(intervalId); callback.call(this); } }, 1000); } function setVisible(selector, visible) { document.querySelector(selector).style.display = visible ? 'block' : 'none'; } onReady(function() { setVisible('#app', true); setVisible('.loading', false); }); But it seems that it still waits for the data to load, then shows the loading page for 1-2 seconds then immediately loads the frontend. -
Django - Full test suite failing when adding in TestCase class, but full test suite passes when it is commented out and all individual TestCase pass
So this seems to be an issue talked about here and there on StackOverflow with no real solution. So I have a bunch of tests that all pass when run individual. They even pass when run as a full test suite, EXCEPT when I add in my TestCase ExploreFeedTest. Now ExploreFeedTest passes when run by itself and it actually doesn't fail when run in the full test suite as in running python manage.py test, it causes another test HomeTest to fail, which passes on it's own and passes when ExploreFeedTest is commented out from the testsuite. I hear this is an issue with Django not cleaning up data properly? All my TestCase classes are from django.test.TestCase, because apparently if you don't use that class Django doesn't teardown the data properly, so I don't really know how to solve this. I'm also running Django 3.2.9, which is supposedly the latest. Anyone have a solution for this? ExploreFeedTest.py from django.test import TestCase from django.urls import reverse from rest_framework import status class ExploreFeedTest(TestCase): -
No input passed from django form in modal to model
I want to write a mock payment function and database that receives card information from Django and proceeds with payment. So, I wrote the code as follows, and even if I input information in the modal and press the charge button, the instance does not enter the Payments model. html <!-- Modal --> <div class="modal fade" id="myFullsizeModal" tabindex="-1" role="dialog" aria-labelledby="myFullsizeModalLabel"> <div class="modal-dialog modal-fullsize" role="document"> <div class="modal-content modal-fullsize"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Payment</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for cart_item in cart_items %} <div> <h2>주문내역</h2> Title : {{ cart_item.timetable.movie.title_eng }} <br> Qty : ${{ cart_item.timetable.ticket_price }} x {{ cart_item.quantity }} <br> Your total is : <strong>${{ total }}</strong> <br> </div> {% endfor %} <br> <br> <br> <form action="{% url 'cart:charge' %}" method="post">{% csrf_token %} <div> <h2>Card Number</h2> <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" maxlength="4" placeholder="****"/> </div> <br> <div> <h2>Validity</h2> <!-- maxlength의 값을 5로지정하여 다섯자리 이상의 값이 등록되는것을 막는다. --> <input type="text" class="validThru" onKeyup="inputValidThru(this);" placeholder="MM/YY" maxlength="5"/> </div> <br> <h2>CVC</h2> <input type="text" maxlength="3" placeholder="***"/> <br> <h2>Password</h2> <input type="text" maxlength="2" placeholder="**"/> <div> <input type="submit" value="charge"> </div> </div> </form> <div class="modal-footer"> <button type="button" class="btn … -
Deploy Django with SSL without Nginx
Is it possible to deploy a django project without using third party tools like nginx or apache just to serve up https:// webpages? Being forced to setup a reverse proxy or some other web server just to serve https seems a bit overkill. -
Highlight item of navigation lost after ajax call
I make highlight item on navigation by: {% if "/people/" in request.path %}class="active"{% endif %} It worked on the first time page loading. request.path = "/people/" After, i call a ajax function, certainly not re-render navigation, but highlight is lost. request.path = "/people/update/" -
Django adding data into db thru form doesn't including primary key
I'm new to Django and was building a project with it right now. I faced a problem while adding a new data thru form into db but it doesn't autofield with a new primary key and replace with a null instead. here is my code: models.py from django.db import models class recipe_models(models.Model): PKG_type_choice = ( ('BGA', 'BGA'), ('POP', 'POP'), ('Avalon', 'Avalon'), ('mNAND', 'mNAND'), ('NAND', 'NAND'), ) PKG_type = models.CharField(max_length=100, blank=True, null=True, choices=PKG_type_choice) Recipe_name=models.CharField(max_length=100, blank=True, null=True) DID=models.CharField(max_length=100, blank=True, null=True) Lead_count=models.IntegerField(blank=True, null=True) Die_qty=models.IntegerField(blank=True, null=True) Package_Width=models.FloatField(blank=True, null=True) Package_Height=models.FloatField(blank=True, null=True) Z_height=models.FloatField(blank=True, null=True) HVM_Status_choice = ( ('YES', 'YES'), ('NO', 'NO'), ) HVM_Status=models.CharField(max_length=100, blank=True, null=True, choices=HVM_Status_choice) # HVM_Status=models.CharField(max_length=100) Machine_choice = ( ('AIHEXAM-0005', 'AIHEXAM-0005'), ('AIHEXAM-0011', 'AIHEXAM-0011'), ('AIHEXAM-0012', 'AIHEXAM-0012'), ('AIHEXAM-0013', 'AIHEXAM-0013'), ('AIHEXAM-0014', 'AIHEXAM-0014'), ('KT390-0002', 'KT390-0002'), ('KT390-0002', 'KT390-0003'), ('KT390-0005', 'KT390-0005'), ('KT390-0006', 'KT390-0006'), ('KT390-0007', 'KT390-0007'), ('KT390-0012', 'KT390-0012'), ('KT390-0013', 'KT390-0013'), ('KT390-0016', 'KT390-0016'), ('KT390-0014', 'KT390-0014'), ('KT390-0020', 'KT390-0020'), ('KT390-0026', 'KT390-0026'),) Machine=models.CharField(max_length=100, blank=True, null=True, choices=Machine_choice) Owner=models.CharField(max_length=100, blank=True, null=True) Workweek=models.CharField(max_length=100, blank=True, null=True) Note=models.CharField(max_length=2000, blank=True, null=True) class Meta: db_table = 'avi_recipe' def __str__(self): return self.Recipe_name + ' ' + self.Machine forms.py from django import forms from .models import recipe_models from django.db import models class RecipeForm(forms.ModelForm): class Meta: model = recipe_models fields = ['PKG_type', 'Recipe_name', 'DID', 'Lead_count', 'Die_qty', 'Package_Width', 'Package_Height', 'Z_height', 'HVM_Status', 'Machine', 'Owner', 'Workweek', 'Note'] Any … -
Django filtering relation in ListView
Given the models class TaskGroup(models.Model): name = models.CharField(max_length=256) class Task(models.Model): name = models.CharField(max_length=256) group = models.ForeignKey(TaskGroup, on_delete=models.CASCADE) completed = models.BooleanField(default=False) completed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) and the list view class TaskGroupListView(ListView): model = TaskGroup I'd like to display the list of task groups with corresponding tasks. The catch is - I only want to show the tasks that have not been completed or have been completed by the user, or if the user as the attribute user.type == "ADMIN" set show all groups and all tasks. Right now I have a template that looks like: {% for taskgroup in object_list %} <h1>{{ taskgroup.name }}</h1> <ul> {% for task in taskgroup.task_set.all %} <li>{{ task.name }}</li> {% endfor %} </ul> {% endfor %} I know that I can modify the queryset of a list view by overriding get_queryset like: def get_queryset(self): if self.request.user == "ADMIN": return TaskGroup.objects.all() else: ... but I'm not sure how to go about filtering the Task relations on the TaskGroups in the else clause. I've thought about creating a manager subclass for Task that can filter based on .completed and .completed_by that I can use in the template but that seems against the philosophy of Django - I'd … -
Can I use PHP-hashed password with Django?
I am working on building an Android App, which uses PHP backend. So everytime a user registers and enters password, it is hashed using bcrypt. Subsequently, I am building a Django based admin panel for the same on the web. What can be the best approach to build/customise the authentication system in Django, so that it can authenticate with the passwords generated through bcrypt? Important: I do not have the option to change the PHP backend of my Android app. -
Updating fiield in PostgreSQL table using .update() not working in django
I've been trying to update the invo_payment_method value from a table called Invoices. This is the code that I currently have to try to achieve this: if total_payments_for_invoice.all().count() == 1: invoice_object = Invoice.objects.get(slug=slug) invoice_object.invo_payment_method = request.POST.get('payment_method') invoice_object.save() So what I'm trying to do is if it's the first payment for the invoice I want to get invoice_object which has the slug of the invoice that just got a payment and update the invo_payment_method field in the table and save the changes. But that's not working. I also tried doing the following: if total_payments_for_invoice.all().count() == 1: Invoice.objects.filter(slug=slug).update( invo_payment_method=request.POST.get('payment_method')) And it's not working either. After that I tried adding a the following to the code above: if total_payments_for_invoice.all().count() == 1: Invoice.objects.filter(slug=slug).update( invo_payment_method=request.POST.get('payment_method')).save() And this one actually updated the value in the database, but it made the webpage crash because of the following exception: AttributeError: 'int' object has no attribute 'save'. In case more information is needed, if I print the value of Invoice.objects.get(slug=slug) I get the following: INV-bb1c 21. And if I print the value of Invoice.objects.filter(slug=slug) I get the following: <QuerySet [<Invoice: INV-bb1c 21>]>. In both cases I'm getting the invoice number which is INV-bb1c and the invoice pid which is … -
How to manage & register different types of users with different fields and Profiles in Django?
【BACKGROUND】 I am working on a project integrating Django and NextJS using Django REST-API Framework. I configured the default user model by creating Custom User Model where email address is the unique and primary field. In my project, there are 3 different types of users : Client, Student & Teacher. In my custom user account models file, I have set a is_usertype flag for each user type; for example: is_client, is_student, is_teacher. Each user types (Client, Student, Teacher) have different profiles containing different fields. The extra fields for each user types are as follows: Client Profile: country Student Profile: interests Teacher Profile: bio I have one common user registration API Endpoint for all types of users which is http://127.0.0.1:8000/user-api/register. At the time of registering user, the specific user type is set to True. For example, if I am trying to register a Client user type, I need to set is_client flag to True, for a Student user type, I need to set is_student flag to True and for a Teacher user type, I need to set is_teacher flag to True. When I am trying to register a specific user type, the user type is not getting registered. I am using … -
django channels. subscribe channel of certain user in receive_json
in JsonWebsocketConsumer i using this code for subscribe socket of certain user (which is not current socket) for messages from new dialog def receive_json() # ... async_to_sync(self.channel_layer.group_add)(f'dialog-{dialog_id}', f'user-{dialog.answerer.id}') # ... but it not works because, i can't just set channel_name like that: def connect(self): self.channel_name = f'user-{self.scope["user"].id}' can i somehow subscribe socket of other user to group, having user_id? -
How do I use a html file to link to another html file?
homepage_template.html <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="keywords" content="HTML, CSS"> <meta name="description" content="My programing resume in the form of a django project built from scrarch"> <title>Resume Homepage</title> </head> <body> <h1>Welcome To My Django Resume Webpage !&copy;</h1> <img src="main_photo.jpg" alt="Image Unable To Be Displayed"> <p </p> <h2>Coding Projects </h2> <a href="homepage_photos/test.html"> text!</a> </body> </html> The above html file is located in a folder named templates. In templates I have another folder named homepage_photos. In homepage_photos I have a html file called test.html Consider when I'm viewing homepage_template.html (on my website) that my URL looks like this - "mywebsite" Whenever the link is clicked the URL would go to mywebsite/homepage_photos/test.html instead of just going to the file itself Side note: I'm using Django -
Django admin display many-to-many field as links
Trying to get my Django admin to display a list of related objects as links to those objects. These objects are related through a many-to-many relationship. Using a combination of this answer and this answer, I came up with: class MyObject(models.Model): related = models.ManyToManyField(RelatedObject) class RelatedObject(models.Model): name = models.CharField(max_length=191) class MyAdmin(admin.ModelAdmin): list_display = ("rel") def rel(self, obj): return[self.link_to_object(related_object) for related_object in obj.related.all()] def link_to_object(self, obj): link = reverse("admin:<app>_relatedobject_change", args=[obj.id]) return format_html(f"<a href={link}>{obj.name}</a>") However, this gives me a list of hrefs, not a list of links. If I instead change: def rel(self, obj): return self.link_to_object(obj.related.get(pk=1)) It returns a nice link where that relationship exists (i.e. related.get(pk=1) in obj.related.all()). Is there a way to get admin to return a list of links? I'll note that there's also this linkify method floating around, but it only works for a ForeignKey, not many-to-many, and I don't see how to adapt it. -
Assign permission to all objects of a type using django-guardian
I'm trying to make a group with django-guardian that has access to all objects of a type instead of a single object, like such: from guardian.models import UserObjectPermission from django.contrib.contenttypes.models import ContentType from apps.myapp.models import Website # Create groups that can edit websites (admin can edit every website, the other group only a specific website) admins = Group.objects.create(name='admins') website_44_editors = Group.objects.create(name='website_44_editors') # This works, assigning permission to edit website 44 to the correct group website_44 = Website.objects.get(pk=44) UserObjectPermission.objects.assign_perm('change_website', website_44_editors, obj=website_44) ####### This doesn't work, as an object is needed ####### UserObjectPermission.objects.assign_perm('change_website', admins) Any way to do this? Google / StackOVerflow Searches only yield unrelated results -
How to configure SSL with docker-compose & github actions?
I'm trying to figure out how could I deploy to server my Django app using docker-compose & github actions. I've made some progress, in fact, the project works on http. But I need to make it work with SSL (https://). I tried to use certbot, but couldn't make it work :( This is my docker-compose file version: '3.8' services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env web: image: madrider/yamdb_final restart: always volumes: - static_value:/code/static/ - media_value:/code/media/ depends_on: - db env_file: - .env nginx: image: nginx:1.19.3 ports: - "80:80" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_value:/var/html/static/ - media_value:/var/html/media/ depends_on: - web volumes: static_value: media_value: And this is nginx/default.conf server { listen 80; server_name 127.0.0.1; location /static/ { root /var/html/; } location /media/ { root /var/html/; } location / { proxy_pass http://web:8000; } } And, finally, my Github actions yml-file name: Django-app workflow on: [push] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort pip install -r requirements.txt - name: Test with flake8 run: | python -m flake8 - name: Test with pytest run: … -
Django TemplateResponse is messing with File URL
Let me start by saying my file URLs are working as intended. When I render out my template I can click on the link and load the correct PDF. With that being said I have been experimenting with trying to dynamically refresh or load table rows so that it's a better user experience. To do this I have used HTMX and plain old JS. I also created a view function that allows me to render HTML snippets which are then inserted into the DOM. This function looks like this: @login_required def api_list_invoices(request): if (request.method == 'GET'): search_fields = ['pk','invoiceDate', 'vendorName', 'invoiceTotal', 'pdf'] invoices = request.user.location.invoices.values(*search_fields).order_by('-invoiceDate') \ .annotate(item_count=Count('items')) return TemplateResponse(request, 'invoice/invoice_table.html', {'invoices': invoices}) This works fine, except for one thing. It totally messes with the generated links for pdf. Getting invoice.pdf.url generates nothing in the outputted HTML and invoice.pdf will generate an incorrect link. To be exact it will come out looking like /invoice/api/pdfs/filename.pdf basically, to be correct, the link would need to be something like /media/pdfs/filename.pdf. Interestingly enough I DO NOT notice this side effect with the avatar URL generation so I have no idea why it's an issue for the FileField. Any insight would be appreciated. Also, if someone … -
Redirect and reverse diffrences in Django
I have a question about what are differences of redirect and reverse. Does it have influence on performance. And someone could me explain the differences between these 3 examples of code? What is the purpose of them and how can I efficently apply them. if 'comment' in request.POST: form = CommentCreationForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_user = request.user comment.comment_item = Item.objects.get(id=pk) comment.save() //1 return redirect('detail-page', pk=item.id) //2 return redirect(reverse('detail-page', kwargs={'pk': item.id})) //3 return reverse('detail-page') (I can not add any argument to the third one that`s the only difference I noticed). -
NoReverseMatch Django Exception
so I encountered a NoReverseMatch exception in my Django app. It shows me this type of exception: Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$'] feed_component.html code: <div> {% for room in rooms %} <div> {% if request.user == room.host %} <a href="{% url 'update-room' room.id %}">Edit</a> <a href="{% url 'delete-room' room.id %}">Delete</a> {% endif %} <a href="{% url 'user-profile' room.host.id %}">@{{room.host.id}}</a> <h5>{{room.id}} --> <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} So my biggest surprise is that in: <a href="{% url 'user-profile' room.host.id %}">@{{room.host.id}}</a> @{{room.host.id}} render excatly what i want on page - id. But this part: {% url 'user-profile' room.host.id %}" Throws exception... and when i change it to: <a href="{% url 'user-profile' room.host %}">@{{room.host.id}}</a> There is no exceptions, it works ok but i really need that id... urls.py path('profile/<str:pk>/', views.userProfile, name="user-profile"), views.py def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics} return render(request, 'baseapplication/profile.html', context) models.py class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) … -
Why it can't find the url
I've been trying to set up channels for our app, but I think that I am getting over my head. I tried following a youtuber's tutorial along with the official one. Everything seemed to go fine until I made the first ws request which led to the following error backend: Not Found: /ws/live frontend: VM160:4 WebSocket connection to 'ws://localhost:83/ws/live/' failed: Due to other dependencies, I have to use Django 2.2 therefore I think that I have messed up somewhere but do not where. here is the code asgi.py: import os import django from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import homepage.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') django.setup() application = ProtocolTypeRouter({ "http": AsgiHandler(), "websocket": AuthMiddlewareStack( URLRouter( homepage.routing.websocket_urlpatterns ) ), }) routing.py from django.urls import path from .consumers import WSConsumer websocket_urlpatterns = [ path('ws/live/', WSConsumer.as_asgi()) ] consumers.py import json from random import randint from time import sleep from channels.generic.websocket import WebsocketConsumer class WSConsumer(WebsocketConsumer): def connect(self): self.accept print('accepted') def disconnect(self, close_code): print('closed') docker-compose.yml version: "3" networks: data-net: driver: bridge http: driver: bridge backend: driver: bridge services: db-0: image: "bitnami/postgresql-repmgr:11" env_file: - ".env" restart: unless-stopped shm_size: "20gb" networks: - data-net volumes: - "postgresql_data:/bitnami/postgresql" web: build: . command: … -
External CSS Stylesheet and Images not showing up in Django Web Application when DEBUG=False
I have a basic Django Web Application that uses an external CSS style sheet in the static/css folder, font-awesome-fonts in the static/fonts folder, and user-uploaded images in the media/images folder. Whenever I set DEBUG = False the image and CSS Style sheets are ignored and just the HTML Template is displayed. My directory structure is as follows: app/ ├── myapp/ ├── media/ ├── static/ └── templates/ settings.py BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates/")], '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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I found out how to display media in the main projects URLs.py by adding the if else statements but even when I add the + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to the end of the urlpatterns[] it does not display when DEBUG = False urls.py from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', include('myapp.urls')), path('admin/', admin.site.urls), ] # Serving the media files in development mode if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += … -
Django Multiple User Timezone
I'm new to django and is working on an application that can store user notes and reminder time. I have followed the Django document(https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/) and added TimezoneMiddleware to middleware, set_timezone method, and timezone template. But still not able to get the correct user timezone, it always shows as UTC. I'm not sure if there anything need to be add in frontend part? because as in code: class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) it seems should get timezone information from session data, but I have checked and there no timezone information there. Would anyone suggest what I might missed? Thank you. -
Django how can I get this translated markdown to render correctly on a website?
I've taken text from my models and used markdown python extension to turn it into html... but it renders as html as a string on my site like this: bot: <p><code>62%</code> Not quite. You got this! Appreciate your efforts</p> kaik: <p>ss</p> Rather than showing the html as a string, I'd like it to format it as html. My views.py currently: from django.shortcuts import render from .models import ChatStream from django.http import HttpResponseRedirect import random import markdown from django.template import RequestContext def send(request): message = request.POST.get('userMessage', False) ip = visitor_ip_address(request) response = routes(message, 'website_' + str(ip)) chatItem = ChatStream(ss= markdown.markdown(response), user= markdown.markdown(message), name=ip) chatItem.save() return HttpResponseRedirect('/chattr/') I'm using markdown to convert the text in my models ChatStream into nicely website formattable text, but rather than formatting as html it just prints the html as a string onto the site. my chattr.html: {% for chat_stream in chat %} <p> {% if forloop.last %} {% else %} <b>bot:</b> <br> {{chat_stream.ss}} <br> <b>{{user}}:</b> <br> {{chat_stream.user}} <br> {% endif %} </p> {% endfor %} It should look like this in the website: bot: 62% Not quite. You got this! Appreciate your efforts kaik: ss