Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
template does not save Image to database
I'm creating a website where projects can be uploaded, each with a name, description, image, and a deadline. When I press the "Save Project" button, i get redirected to the homepage as expected, but the image does not get saved even though everything else does. I don't receive any error message. My Question is, why doesnt it save images to the database, but everything else does? Screenshot of input form: (https://i.stack.imgur.com/ZUVrC.png) Screenshot of homepage after saving a project: (https://i.stack.imgur.com/wrb0o.png) Here is my code: In models.py: from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True,) deadline = models.DateTimeField(null=True, blank=True) def __str__(self): return self.project_name class Image(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_images') image = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return self.image.name In forms.py: from django import forms from django.forms import inlineformset_factory from .models import Project, Image class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['project_name', 'project_description', 'deadline'] widgets = { 'deadline': forms.DateTimeInput(attrs={'type': 'date'}), } ImageFormSet = inlineformset_factory(Project, Image, fields=('image',), extra=5, can_delete=True,) In views.py: from django.shortcuts import render, redirect, get_object_or_404 from .models import Project from .forms import ProjectForm, ImageFormSet def homepage(request): projects = Project.objects.all() context = { 'projects': projects, } return render(request, 'project.html', context) def … -
How to use Authentication in Next js with the help of Api with JWT token?
Hello friends I want the authentication of NextJS using Django API from Simple JWT authentication. Mainly, I want to know how to redirect to the login if not authenticated and if login direct to the homepage (Checking the Authentication). -
calendar icon is not displayed django admin page
I'm currently working on customizing my Django admin page, and I'm facing an issue where the date picker icon is not displayed in the date input field. class FactureAdmin(ImportExportMixin,admin.ModelAdmin): inlines = (AllocationFactureInline,) admin.site.register(Facture,FactureAdmin) I was expecting to see a date picker with icons to choose the date, similar to this example: Additionally, my browser's console is reporting the following error: -
How do I access my Django app hosted on EC2?
I am running a django-based application (Arches) in an AWS EC2 instance, and am unable to access it on either the Public IPv4 address, or the Public IPv4 DNS. I have tried virtually all combinations of parameters, as well as the steps described in the following discussions: How do I access my Django app running on Amazon EC2? Access Django app on AWS EC2 host Connecting to EC2 Django development server Without :8000 ec2-xxxxxxxx.eu-central-1.compute.amazonaws.com refused to connect. With :8000 This site can’t provide a secure connection ec2-xxxxxxxxx.eu-central-1.compute.amazonaws.com sent an invalid response. Terminal output Changing the protocol to http gives the following error OSError at / Error reading /home/ubuntu/suhozid/suhozid/webpack/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Request Method: GET Request URL: http://3.76.192.148:8000/ Django Version: 3.2.19 Exception Type: OSError Exception Value: Error reading /home/ubuntu/suhozid/suhozid/webpack/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Exception Location: /home/ubuntu/dev/lib/python3.10/site-packages/webpack_loader/loader.py, line 29, in load_assets Python Executable: /home/ubuntu/dev/bin/python Python Version: 3.10.6 Python Path: ['/home/ubuntu/suhozid', '/home/ubuntu/suhozid', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ubuntu/dev/lib/python3.10/site-packages', '/home/ubuntu/suhozid/suhozid'] Server time: Fri, 16 Jun 2023 04:50:13 -0500 I was hoping to be able to access my Django app by adding the addresses in settings.py ALLOWED_HOSTS = … -
access request object in custom function without passing as arg - django
Django issue: I’ve an issue accessing request object of api in a custom logger function where I save my logs to -> rabbitMQ and then Elastic for analysis. I need some of the information from request object and a userInfo(I add that key into request object at auth middleware), now when I create log schema I need some of the fields like request body, path , method, user info etc. to create user-specific logs. But I can’t pass request object directly to each function wherever I’m using my logger. Worst case: view -> function1 -> function2 -> function3…and so on. I need to pass request object to this nested chain where I’m logging in function_n. Is there any other way than passing request all through the chain. Any luck? Log Schema: <there have been multiple logs in a single api request at any point and of any type <info, error, warn or critical> { "tags": "LOG_TYPE_SHORTHAND", "custom": true, "req_id": "user_id:req_start_time", // nano seconds "timestamp": "TIMESTAMP", // for debugging and visual representations "message": "LOG_MESSAGE", // actual msg for that particular log "level": "LOG_LEVEL", // info, warn, err, debug, critical "service": "SERVICE_NAME", // router/main OR search - configurable once at api server … -
DRF best practice approach to handle custom errors in this code
I have a Django Rest project, and I'm looking for the best practice approach to handle custom errors and send them back to the user. Currently, there is a custom error being used in the API to respond to the user. However, this error is being used in another file that is not exclusively related to the API. I would prefer to capture the error within the view and display it to the user in that context. This way, the 'report.py' file can remain decoupled from the API and be used anywhere. Is this the best approach, and how can I effectively propagate the error upwards while still utilizing my custom error only within the view? In my report.py, I have this: if (self.total == 0): raise ValueError() but this is what I was doing before in report.py but I feel it is wrong as report.py is used not just on the API if (self.total == 0): raise MyAPIValueError() So can you do the following and is it the best approach or should I stick with above In the report raise normal ValueError class MyListView(BaseReportView): ……….. def get_queryset(self): queryset = super().get_queryset() try: return Report().data except (CustomAPIValueError) -
After the installation of SSL on my Django application, i encounter a 403 Forbidden error preventing access to CSS files. The domain is memcur.com
After the installation of SSL on my Django application, i encounter a 403 Forbidden error preventing access to CSS files. I am using nginx and ubunto. The /var/log/nginx/error.log shows the following continuously, though i have applied: sudo chown -R www-data:www-data /root/memcur/static/ sudo chmod -R 755 /root/memcur/static/ /var/log/nginx/error.log: "/root/memcur/static/libs/bootstrap/dist/js/bootstrap.bundle.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/bootstrap/dist/js/bootstrap.bundle.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/libs/metismenu/dist/metisMenu.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/metismenu/dist/metisMenu.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/libs/node-waves/dist/waves.min.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/libs/node-waves/dist/waves.min.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" "/root/memcur/static/js/app.js" failed (13: Permission denied), client: 103.180.203.6, server: memcur.com, request: "GET /static/js/app.js HTTP/1.1", host: "memcur.com", referrer: "https://memcur.com/account/login/?next=/" The domain is memcur.com. The css, js, and images are not loading. Pleas visit and give me a suggestion to fix it. -
OSError: Load averages are unobtainable
Our django celery server is running with concurrency value of 500 with eventlet as execution pool. Recently, we encountered this issue and restarting the server fixed it. I am attaching the traceback of the error. python package versions: Django 4.1.7 celery5.2.3 eventlet 0.33.3 I checked the soft and hard limits of the open files if these are of any use. soft limits: core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31071 max locked memory (kbytes, -l) 65536 max memory size (kbytes, -m) unlimited open files (-n) 2048 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 31071 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited hard limits: core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 31071 max locked memory (kbytes, -l) 65536 max memory size (kbytes, -m) unlimited open files (-n) 16384 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority … -
"GET /cart.json HTTP/1.1" 404
"GET /cart.json HTTP/1.1" 404 error show in the command prompt when I use runserver in my django app. The website works absloutly fine when the debug=True in the setting but when I turn it off it shows 500 internal error. I don't have cart.json in any part of my code, and I cannot really undrestand where it comes. How can I troubleshoot it? -
Django: How can i open an App with Django?
I am currently working on a Django project and have reached a point where I need to implement the final functionalities. However, I am encountering a problem in one specific area. When the app is opened on a smartphone, I want to open the scanner app of that specific smartphone with a button. I have tried using the URL scheme required for my smartphone provider, but that did not work. I have also made sure to allow all relevant permissions in the app settings. I am stuck and would appreciate any help. Below is the code snippet where the issue occurs: <span>@{{room.host.username}}</span> </a> </div> <div class="room__details"> {{room.description}} </div> <span class="room__topics">{{room.topic}} <a href="xmsf://scan/scanner">Open Scanner App</a> </span> </div> <div class="room__conversation"> <div class="threads scroll"> {% for element in liste %} <li>{{ element }}</li> {% endfor %} Thank you. -
Using `django_get_or_create` with onetoone related field
Given this django model from django.db import Model from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) some_other_field = model.CharField(...) I have created 2 factory for the user and the customer model: import factory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ('username',) first_name = factory.Faker("first_name", locale="fr_FR") last_name = factory.Faker("last_name", locale="fr_FR") username = factory.LazyAttribute(lambda m: f"{m.first_name[0]}{m.last_name[0]}".lower()) email = factory.LazyAttribute(lambda m: f"{m.first_name.lower()}.{m.last_name.lower()}@ielo.net") customer = factory.RelatedFactory(CustomerFactory, factory_related_name="user", user=None) is_staff = False class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = "customers.Customer" user = factory.SubFactory('myapp.tests.fixtures.UserFactory', customer=None) To avoid flaky tests, I have set the django_get_or_create, since most of the time I just want a user, and I create specific classes for specific cases (UserIsStaffFactory, UserSuperAdminFactory) I copied the RelatedFactory/SubFactory from https://factoryboy.readthedocs.io/en/stable/recipes.html#example-django-s-profile but If I run: u1 = UserFactory(username='foo') u2 = UserFactory(username='foo') # raise IntegrityError, UNIQUE constraint failed: customers_customer.user_i -
Is there any package like pm2 for django apps
Question: I have a Django app running on a server, and I want to use PM2 to manage the process. However, when I try to start the app with PM2, it gives me an error. Here is my command: pm2 start myapp And here is the error message: Error: script not found or unable to stat: myapp What am I doing wrong? How can I use PM2 to manage my Django app? -
How to configure Django app on AWS elastic beanstalk without "Invalid HTTP_HOST header" errors
Goal: To deploy an application to AWS Elastic Beanstalk but constantly receiving the error ERROR 2023-06-16 17:54:37,903 exception 92295 139827093698112 Invalid HTTP_HOST header [some IP address] despite several attempts. Current status: The site works perfectly on my localhost. The requirements.txt file is in the same directory as manage.py. All changes are committed to the git main before deployment to Elastic Beanstalk (EB). There is no .ebignore file, only a .gitignore file. The wsgi.py file is located one level under manage.py, at config>wsgi.py. This is implemented in the .ebextensions>django.config file as shown below: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application Two settings.py files are used: base.py and production.py. Following an existing Stack Overflow response, the production.py file is obtained from django-cookie-cutter and shown below: The production.py file: from .base import * # noqa from .base import env import os SECRET_KEY = env("DJANGO_SECRET_KEY") if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } # SECURITY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SESSION_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure CSRF_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/topics/security/#ssl-https # https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds # TODO: set this to 60 seconds first and … -
How to add jwt authentication to existing login page on django
So I am learning how to use Django and DRF and I created a Login and Register page on Django. Login and Register user view with their own html pages But, I don't want to use the normal authentication in Django and want to use Jwt token to authenticate I have already downloaded it and and can use api/token and api/token/refresh to get the access and refresh token but I cant seem to find a way to use it in my already built login and register page to authenticate -
Luxor Pool API (Create subaccount, delete subaccount)
Question: when create a subaccount on luxor pool it create the user but when i delete the same user by calling delete subaccount api. It does not give me access to create the same user subaccount with the same name. Error: {"errors":[{"message":"error: duplicate key value violates unique constraint \"users_username_key\"","locations":[{"line":3,"column":9}],"path":["provisionNewUser"]}],"data":{"provisionNewUser":null}} Subaccounts list: { "success": true, "message": "", "data": { "users": { "edges": [ { "node": { "username": "cxdevs" } }, { "node": { "username": "user-1" } } ] } } } Note: I have delete the account with the same name when i first created it. And after deleting it does give me access to create with the same name. (Luxor Pool APIs) -
I have upload a django project on server in public html folder
When creating a Python application on a server, I put the folder name or project name in the application root. However, the issue is that the folder is creating outside the public HTML folder. I want the folder to be created in the public HTML folder only. How can I ensure that the folder is created in the desired location? -
401 unauthorized on post request
serializer/login.py class LoginSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['user'] = UserSerializer(self.user).data data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data viewsets/login.py class LoginViewSet(ViewSet): permission_classes = (AllowAny,) serializer_class = LoginSerializer http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) return Response(serializer.validated_data, status=status.HTTP_200_OK) I cant login with right credentials using post request, it says 401 unauthorized. but when I try to register or refresh token using post request (using the same crediatials I tried to login with), it works fine. serializer/register.py class RegisterSerializer(UserSerializer): #making the pass min 8 charecter and max 128 #and can't be read password = serializers.CharField(max_length=128, min_length=8, write_only=True, required=True) class Meta: model = User fields = ['id', 'email', 'username', 'first_name', 'last_name', 'password'] # 'bio', 'avater', #used the create_user method that we wrote def create(self, validated_data): return User.objects.create_user(**validated_data) viewsets/register.py class RegisterViewSet(ViewSet): serializer_class = RegisterSerializer permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() refresh = RefreshToken.for_user(user) res = { "refresh" :str(refresh), "access": str(refresh.access_token), } return Response({ "user": serializer.data, "refresh":res['refresh'], "token":res['access'] }, status=status.HTTP_201_CREATED) viewsets/refresh.py class RefreshViewSet(viewsets.ViewSet, TokenRefreshView): permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, … -
React gets non responsive when data from Django is used to display a Nivo line chart
I have been trying to display a nivo line charts using data from my backend (Django). However, when the data is inserted into the nivo line chart, the react window gets unresponsive. The backend sends the timestamps and the values like this -- Example -- timestamp = "2023-05-12 16:10:53.000000000" Values -- "39.520004" class AddView(APIView): from django.views.decorators.csrf import csrf_exempt from rest_framework import status import json @staticmethod @csrf_exempt def post(request): from awsfetch.rpm import rpm timestamps, values = rpm() return Response({"timestamps": timestamps, "values": values}) This is the nivo charts component -- import { ResponsiveLine } from "@nivo/line"; const MyResponsiveLine = ({ data }) => ( <ResponsiveLine data={data} margin={{ top: 50, right: 160, bottom: 50, left: 60 }} xScale={{ format: "%Y-%m-%dT%H:%M:%S.%L%Z", type: "time" }} xFormat="time:%Y-%m-%dT%H:%M:%S.%L%Z" yScale={{ type: "linear", stacked: true, min: 0.0, max: 1.0 }} curve="monotoneX" axisTop={null} axisRight={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: "0.2", legend: "", legendOffset: 0 }} axisBottom={{ tickValues: "every 1 second", tickSize: 5, tickPadding: 5, tickRotation: 0, format: "%S.%L", legend: "Time", legendOffset: 36, legendPosition: "middle" }} axisLeft={{ tickValues: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], tickSize: 5, tickPadding: 5, tickRotation: 0, format: ".2", legend: "CPU", legendOffset: -40, legendPosition: "middle" }} enableGridX={false} colors={{ scheme: … -
Django REST framework prefetch not working on model with multiple foreign keys to the same target
I'm writing an endpoint to fetch data from the "Term" model in Django REST framework and I'm trying to reduce queries by prefetching data. Specifically there is a model "TermRelation", that saves vector relation scores between individual terms that I would like to prefetch data from. Simplified, the models look as follows: models.py class Term(models.Model): term = models.CharField(max_length=255, verbose_name=_('Term'), null=True, db_index=True) class TermRelation(models.Model): src_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Source term'), related_name='src_term_relation') trg_term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name=_('Target term'), related_name='trg_term_relation') vector_sim = models.FloatField(blank=True, null=True, default=0.0, verbose_name=_('Vector similarity'), help_text=_('Cosine vector similarity.')) And here's the simplified view: views.py class TermsList(generics.ListCreateAPIView): def get_queryset(self): queryset = Term.objects.prefetch_related( 'src_term_relation', 'trg_term_relation', 'note_set', 'usage_set' ).all() return queryset There are other models related to term such as "Note" and "Usage" for which prefetch is working, only for relations it still makes a bunch of queries. I've included a screenshot of the Django SQL debug results, or rather the first few lines as this goes on for a while with the same queries. You can see that Django does run the prefetch operation, but then still makes the same queries as if it didn't happen. What am I doing wrong? Could this be related to "TermRelation" having two ForeignKey fields pointing to … -
Implementation of the post filter page in django
I am trying to filter blog posts using this model: class Post(models.Model): is_podcast = models.BooleanField(default=False) category = models.ManyToManyField(Category) title = models.CharField(max_length=500) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) body = RichTextUploadingField() likes_count = models.IntegerField(default=0 , help_text="amount of likes") vip_members_only = models.BooleanField(default=False) def __str__(self): return self.title And I am using this view to filter the posts: def Index_view(request , slug=None): posts = Post.objects.filter() kind = request.GET.get('type') order = request.GET.get('order') author = request.GET.get('author') search = request.GET.get('search') if slug: cat = get_object_or_404(Category , slug=slug) posts.filter(category = cat) if search != '' and search is not None: posts.filter(Q(title__icontains = search)) if kind != '' and kind is not None: if kind == 'podcast': posts.filter(is_podcast=True) if kind == 'all': pass if kind == 'post': posts.filter(is_podcast=False) con = {'posts' : posts} return render(request , 'Weblog/posts.html' , con) Here is the urls.py too: path('posts/', Index_view), re_path(r'^posts/(?P<slug>[\w-]+)/$', Index_view), When I use this URL (http://127.0.0.1:8000/blog/posts/some-slug/?search=test), I receive all the posts and the filtering does not work. What is the problem? -
how do I call a djago admin delete fuction
I am trying to use the Django admin delete function to ensure that the corresponding quantity is deleted from the associated page when the delete function is clicked. For example, I have a class called RestockModel. When I add a new Restock item, the restock quantity can be automatically added in the StockListModel. However, when I need to delete the Restock item, the quantity in StockListModel is not deleted immediately. How can I call the django admin delete function to this statement? Here is the code that how I made the quantity can be added when I create a new restock item: class restockInfo(admin.ModelAdmin): list_display = ["product", "delivery_order_no","restock_quantity", "supplier_name", "created_date"] readonly_fields = ["created_date"] search_fields = ['created_date'] def save_model(self, request, obj, form, change): product = obj.product restock_quantity = obj.restock_quantity if restock_quantity and product.quantity_in_store: if restock_quantity >= 0: obj.product.quantity_in_store = product.quantity_in_store + restock_quantity # don't forget to save stock after change quantity obj.product.save() messages.success(request, 'Successfully added!') super().save_model(request, obj, form, change) else: messages.error(request, 'Invalid Quantity, Please Try Again!!!') return restockInfo This is my restock models: class restockList(models.Model): product = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True) delivery_order_no = models.CharField(max_length=255, null=True) restock_quantity = models.IntegerField(null=True) supplier_name = models.CharField(max_length=255, null=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=False) class Meta: db_table = "restocklist" -
Getting object index in django object list
I have a list in context of one of my pages called comments and when I'm iterating on it i want to know the index of item; i want to know the index of comment in this for loop: <!-- comment list section --> <div class="card shadow my-3 p-5"> <h3>Comments:</h3> <!-- checking if any comment exist on this post --> {% if comments.count < 1 %} No comments. write the first one! {% else %} <!-- iterating on comments and showing them --> {% for comment in comments %} <div id="comment-div"> <span id="Comment-name">by: {{ comment.name }}</span> <span id="Comment-date">{{ comment.datetime_created|date:'M d Y' }}</span> <p id="Comment-body">{{ comment.body }}</p> </div> {% endfor %} {% endif %} </div> view: class PostDetailView(FormMixin, generic.DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CreateComment def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) # get the default context data context['comments'] = Comment.objects.filter(accepted=True) # add extra field to the context return context model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') email = models.EmailField(max_length=35) name = models.CharField(max_length=50) body = models.TextField() datetime_created = models.DateTimeField(auto_now_add=True) accepted = models.BooleanField(default=False) -
White space stripped from Django Template tags in PrismJS code blocks
When I render Django template code in a prismjs block, it strips white space {{}} and {%%}. For example, pre-render, the code might be {% image self.search_image thumbnail-400x200 as img %} <img src="{{ img.url }}" alt="{{ img.title }}"> But the rendered code block will be {%image self.search_image thumbnail-400x200 as img%} <img src="{{img.url}}" alt="{{img.title}}"> It's not a case of css, the space is missing from the html. I can set the language to HTML, or even python etc, the same issue remains. Does anyone know of a way to prevent this? -
How Can I implement User Sent Message and Receive Message in Django
I am working on a Django project where I have three types of users: Landlord, Agent, and Prospect. I want the Prospect user to be able to contact the Property Owner by sending a message while on the Property Detail view, and the Property Owner to be able to reply back to the Prospect using the same view. I also want all these users to maintain an Inbox and Sent Message items. I'm struggling to figure out whether my logic is sound and how to implement the functionality using Django. Is there a library that will make user messaging within Django easier? In my code, I maintain different Models for these users with a OneToOneField and use signals for automatic profile creation upon registration. I also have a Profile Model connected through the same relationship, and Message Model. I tried passing the Property Owner ID as the Recipient ID and Property ID on url from the Property Detail view to the send_message function view, but I get the error "No 'User matches the given query'." Here are my views: def property_detail(request, property_id): user = request.user #Check if user is authenticated if not user.is_authenticated: logout(request) messages.warning(request, 'Session expired. Please log in … -
Annotating a value in Django using Extract and OuterRef (or F) leads to TypeError
I'm building an application where users can create posts. If the user don't post anything after some specific time of the day, the server will send a push notification to remember the user to post something. In order to create this query I planned to run a scheduled celery beat task to filter the posts created in the current day, list the user's id and use a simply exclude these IDs from the active users in order to get a queryset with the users that should be notified. The user has a timezone field, which is updated via a middleware that checks some headers frontend send, checks the user saved timezone and update it if necessary. This timezone is the result of running the tzname() method in the datetime that comes in this header. The issue is that the users are spread across multiple timezones, so I need to actually annotate the created_at field in Posts (which are saved taking in consideration the server timezone) with the User's timezone. In Django we have the Extract function that simply does exactly what I need. The issue here is that it would work perfectly if I could use a F expression or …