Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When running my docker image for my Django project I'm getting a "ModuleNotFoundError: No module named 'try_django'" error
So long story short, I'm trying to use docker to take my Django project to production through Heroku. This is my first ever Django project, first time using Docker as well. Currently I'm getting an error when I try to run my image, this is my first attempt at testing that it runs just fine. I did check that it would run with gunicorn before I put it into the docker image. That worked just fine, although my website didn't look like what it was supposed to, but that's the whole point of docker right? As of right now my website looks just fine with the classic: (try_django) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 18:31:48 Django version 2.2, using settings 'try_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Now I'm just trying to get this project deployed. I can see that the image is created just fine: simple-dj-docker latest 11554361b373 17 minutes ago 1.24GB My next step is to run: docker run -it -p 80:8888 simple-dj-docker In return I get: [2020-10-15 18:13:15 +0000] [6] [INFO] Starting gunicorn 20.0.4 [2020-10-15 … -
How to make my admin_order_pdf function better
I have this function to have a pdf file with orders details but it is not showing all details required in template so I am trying to write the admin_order_pdf function in a better way as it is not generating the full context of the order context. I am not sure whether converting it to a class based view will make it better and even how to do that. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing----------------> <<-------------------------From here nothing is showing--------------------------> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> {{ order_item.item.title }}</td> <td> {% if order_item.item.discount_price %} <del>${{ order_item.item.price }}</del> {{ order_item.item.discount_price }} {% else %} ${{ order_item.item.price }} {% endif %} </td> <td>{{ order_item.quantity }}</td> <td>{% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} … -
__str__ returned non-string (type Product)
I'm getting __ str __ returned non-string (type Product) when I try to add OrderItem in my Django project models.py: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date_ordered = models.DateField(auto_now_add=True, blank=True, null=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return self.transaction_id class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.product class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.name) @property def imageUrl(self): try: url = self.image.url except: url ='' return url admin.py: admin.site.register(Customer) admin.site.register(Product) admin.site.register(Order) admin.site.register(Tag) admin.site.register(OrderItem) I get the same error when I try this: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() image = models.ImageField(null=True, blank=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return 'test' Sometimes I get this error when I try to add/delete items (in Orders, OrderItems, Products) -
Django F Date Expresion generated from static field
I am trying to get a series of ages from a persons list, but the age generated change with each query because is the age in a specific event so i can accomplish this with a simple loop, extracting the timedelta from the diference: [ (event_date - user.birth_date).days/365.25 for user in User.objects.all() ] event_date is always a datatime.date object anr user.birth_date too. I consider it a "Static" field or constant because it is outside the database. This gives me the correct results, but since I am doing this many times and i have other calculations to do I wanted to generate the ages from the database using the F() expresion. ``from django.db.models import ExpressionWrapper, fields diference = ExpressionWrapper( event_date- F('birth_date'), output_field=fields.DurationField()) qs_ages= self.annotate(age_dist=diference) this should give me a field named age_dist that will be a timedelta contains the total days between the two dates, so now I should do this and should give me the same result as above. [ user.age_dist.days/365.25 for user in User.objects.all() ] But this does not work, the result is a time delta of microseconds What i am doing wrong? and how should I include the static value of event_date to the expression? And... going beyond. … -
How to filter and get an "object" instead of a "quesryset" in Django Rest Framework
I am trying to filter the users by passing the email_id through URL by passing email_id and getting that particular user. I tried doing this using django-filters but I got a queryset with one object inside it but instead I need the object itself. here's the model - class User(models.Model): """This is the Users model where all users data will be saved""" first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100, default="") city = models.CharField(max_length=20, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=20, blank=True) zip_code = models.CharField(max_length=6, blank=True) mobile_number = models.CharField(max_length=10, blank=True) birthdate = models.DateField(blank=True, null=True) photo_url = models.URLField(max_length=255, blank=True) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, related_name='user_gender') joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I tried using this viewset but it gives me a queryset instead of an object and I coudn't put my mind around on it. class UserFilter(filters.FilterSet): class Meta: model = User fields = { 'email_id': ['iexact'] } class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [DjangoFilterBackend] filterset_class = UserFilter This is the url I am currently passing - http://127.0.0.1:8000/api/v1/users/?email_id__iexact=somemail@gmail.com -
How best to store predictions from machine learning model in Django?
I know Django is well suited for deploying a machine learning model. But all of the tutorials on deploying a machine learning model do not use the standard Django models. When we need to get a prediction, we simply refer to the model as if it were a function, and then we pass the data to the client as a json file. I am satisfied with this option for providing data, if not for a few shortcomings. I will list them below. Let's say that I want to provide the user with filtering data by some parameter. Django provides a model-based filtering mechanism only (tell me if it doesn't). I have no idea how I can filter out a json response that doesn't use serializers and models. My site page should display 200 predictions. These predictions must change every day, but during the day they are unchanged (they depend on today's date). How good is it for performance if every user GET request to that page leads to the machine learning model algorithm being called 200 times? Is there some kind of solution that will allow me to solve these two problems? -
In a Django Rest Framework APIView, using nested serializers for grouping, how can I get only the results that meet all filter criteria?
I have a model of Documents, a model of Authors and a model of Groups. A document must belong to an author and also to a group. So the document model has foreign key constraints to the other two tables. Document model class Document(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='documents') group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=240, unique=True) description = models.TextField(max_length=999, blank=True) body = models.TextField() active = models.BooleanField(default=True) publication_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Author Model class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.TextField(max_length=999, blank=True) Group Model class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=60, unique=True) description = models.CharField(max_length=240, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Then I have my serializers: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = "__all__" read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author class DocumentSerializer(serializers.ModelSerializer): active = serializers.BooleanField(initial=True) author_name = serializers.StringRelatedField(read_only=True, source='author') class Meta: model = Document fields = "__all__" And of course DocumentsByAuthorSerializer which groups Documents by Authors: class DocumentsByAuthorSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Author fields = ['id','name', 'documents'] read_only_fields = ['user'] def create(self, validated_data): author = Author.objects.create(user=self.context['request'].user, **validated_data) return author Finally, I have my view … -
Django checkbox for filter
Im having some problem when I want to keep a checkbox checked. When I send the form all the checkbox are checked. so idk how to change the if statement for that :( <div class="form-group"> <label >Marca</label> {% for brand in q %} <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="test" value="{{brand.brand}}" {% if marca %} checked="checked" {%endif%}> <label class="custom-control-label" for="{{brand.brand}}" style="cursor: pointer;">{{brand.brand}}</label> </div> {% endfor %} </div> And here is the view: marca = request.GET.get('test') if marca : products = products.filter(brand__name__in=request.GET.getlist('test')) All the other things are fine. It shows me the brands that I choose. So I just want to keep the checkbox that I checked :( and I think the problem is that If statement in the template -
Uploading image in Django returns error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte"
So I have a nested serializer and I'm trying to upload an image, the image there but when I try to set it to use it on the serializer I'm getting the error. My code: models.py class Pet(models.Model): pet_id = models.UUIDField('pet uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) name = models.CharField('Pet name', max_length=255, null=False, blank=False) class Attachment(models.Model): attachment_id = models.UUIDField('attachment uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) pet_id = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.FileField(upload_to='photos/', null=False, blank=False) upload_at = models.DateTimeField('Time it was uploaded', max_length=50, null=False, blank=False ) serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ('name','upload_at') class PetSerializer(serializers.ModelSerializer): attachments = AttachmentSerializer(many=True) class Meta: model = Pet fields = ('pet_id','name', 'attachments') def create(self, validated_data): attachments = validated_data.pop('attachments') pet = Pet.objects.create(**validated_data) for att in attachments: Attachment.objects.create(pet_id=pet, **att) return pet views.py parser_classes = (MultiPartParser, FormParser) def create_pet(self, request): img = BytesIO(request.FILES.get('file_1').read()) img.seek(0) data = Image.open(img) new_data = request.data.copy() new_data['attachments'] = [{'name':data, 'upload_at':datetime.now()}] serializer = self.get_serializer(data=new_data) if not serializer.is_valid(): return Response({'error':serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response({'data':serializer.validated_data}, status=status.HTTP_201_CREATED) but I'm getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Any thoughts about this? Thanks in advance. -
concatenating string variables to obtain value
How would I concatenate these two string variables in Django templates? At the moment question.correct_answer is the position the correct answer should be (so if there were 4 potential answers and the first answer was correct, question.correct_answer would return 1 instead of the value the answer holds. I have tried the below code, but it shows a string of 'question.answer_1' <h5 class="homework_desc"> {{ question.answer_4 }}</h5> <br> <h4 class="homework_correct hidden" id="{{question.id}}"> {{'question.answer_'|add:question.correct_answer}} </h4> -
What code should we write in "Templates" to display "zhanr" (in Post model)?
I want create a blog application and write in "templates/blog/detail.html": <a href='#'>{{ post.zhanr.genre }}</a> but it doesn't show in browser, i don't know why. you sure about "Mozu in model", I added information about "genre" in database. my model: in Post model i use ManyToManyField for Mozu model from django.db import models class Mozu(models.Model): genre = models.CharField(max_length=250, help_text='نوشتن موضوع') def __str__(self): return self.genre class Aks(models.Model): img = models.ImageField() class Post(models.Model): title = models.CharField(max_length=250) zhanr = models.ManyToManyField(Mozu, help_text='موضوع انتخب کنید') image = models.ManyToManyField(Aks ,null=True, blank= True) video = models.FileField(null=True, blank= True) desc = models.TextField() date = models.DateTimeField() how_time = models.IntegerField(null=True, blank= True) def __str__(self): return '{}-{}'.format(self.title, self.date) my view: i want using Zanr in detail.html from django.shortcuts import render, get_object_or_404 from .models import * from django.views import generic from django.contrib.auth.decorators import login_required, user_passes_test class IndexView(generic.ListView): template_name = 'blog/index.html' context_object_name = 'posts' def get_queryset(self): return Post.objects.all().order_by('date') class DetailView(generic.DetailView): model = Post template_name = 'blog/detail.html' -
django form queryset for image URL
I have a form that links an image model to another model. I'm trying to preview the images in the form, not like the default dropdowns menu, but I'm struggling with the image URL. I tried image.urlbut it's not working my models.py class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) images = models.ForeignKey('luach.Images',related_name='images',on_delete=models.CASCADE) def get_absolute_url(self): return reverse("dayimage_detail",kwargs={'pk':self.pk}) my forms.py class DayImageForm(forms.ModelForm): class Meta: model = DayImage fields = ('images',) my views.py def create_day_image_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': form = DayImageForm(request.POST) if form.is_valid(): dayimage = form.save(commit=False) dayimage.date = date dayimage.save() return redirect('date_detail',pk=date.pk) else: form = DayImageForm() context = {'form': form,'date': date,} return render(request,'luach/dayimage_form.html',context=context) my dayimage_form.html <form method="POST"> {% csrf_token %} <select class="image-picker"> {% for image in form.images %} <option data-img-src="{{image.value.images.image.url}}" value="{{forloop.counter}}">{{image.label}}</option> {% endfor %} </select> <button type='submit' class='btn btn-success'>save</button> <a class="btn btn-danger" href="{% url 'date_detail' pk=date.pk %}">cancel</a> </form> -
Model inheritance many to one, and return view to template
Struggling again. I would like to apply model inheritance to a template. I have 2 models. Customerprofile and Customerquote. I would like the customerquote to inherit the data records from customerprofile. The model has done this in the backend setup as the models below. The issue is I have 3 seperate fields in the customerquote template for title, firstname and surname with fields. Title, firstname and surname. I would like that I setup a dropdown in the customerquote that when I select firstname all the firstname records appear in the dropdown, when I select the firstname option, Surname and title fields are automatically populated based on inheritance of customerquote and the associated record linked to address 1, is this possible. I have included the template setup below, which in it's basic form is not working even for firstname, before looking at the next steps/ Please see curent setup, is their a way that I can do this and save to new model customerquote, the new instance? Create your models here. class Customerprofile(models.Model): Title = models.CharField(max_length=5, blank=True) Firstname = models.CharField(max_length=100, blank=True) Surname = models.CharField(max_length=100, blank=True) Mobile = models.CharField(max_length=11, validators=[int_list_validator(sep=''), default='12345678901') Email = models.EmailField(max_length=100, blank=True) Datecreated = models.DateField(default=now) Profilefield = models.IntegerField(default="12345678", blank=True) … -
Django rest Framework - Custom Json Response
i'm new into Python and Django Rest Framework. I'm trying to return a "custom" json response but i can't figure it out how to achieve the result i want. I'm building an Ecommerce api where i have "boxes" with "products", this BoxProduct model was created because i need a relation between Products and Boxes, but the same product can be in different boxes, ex: Product.id=1 is in box_id=2 and box_id=4. That's why i created this middle model. BoxProduct Model class BoxProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, null=True, related_name='box_product') box = models.ForeignKey(Box, on_delete=models.DO_NOTHING, null=True, related_name='box_box') product_price = models.DecimalField(max_digits=8, decimal_places=0, null=True, blank=True) I tried to link the serializers of Product and Box but i didn't get wat i want. BoxProduct Serializer class BoxProductSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=True) box = BoxSerializer() class Meta: model = BoxProduct fields=['box', 'product'] The idea is to have a returned json like this: { "box_id": 232323, "box_name": "Box name Test", "products": [ { "name": "product name 1", "type": "product_type" }, { "name": "product name 2", "type": "product_type" }, { "name": "product name 3", "type": "product_type" } ] } What would be the best approach to do this? Thanks for your help! -
hi i am getting "CSRF Failed and CSRF cookie not set." error
{"detail": "CSRF Failed: CSRF cookie not set."} error in postman , i am using django rest_framework for developing ios android backend . when i first time clear all cookies and use my login api is working fine this will give me all info about user as per my code but after that when i try to hit any api using post method its always give crsf failed. i also use csrf_exempt decorator in view and urls.py and also tried CsrfExemptMixin from brace package. my login code is from django.contrib.auth import login,logout from django.shortcuts import render,redirect # local py files from .models import * from .serializers import * from app_apis.models import * # third party from rest_framework import (generics, permissions) from knox.views import LoginView as KnoxLoginView from rest_framework.response import Response from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.models import AuthToken from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from braces.views import CsrfExemptMixin from django.middleware.csrf import get_token # Register API class RegisterView(CsrfExemptMixin,generics.GenericAPIView): serializer_class=RegisterUserSerializer @method_decorator(csrf_exempt) def post(self,request,*args, **kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() print logout(request) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(CsrfExemptMixin,KnoxLoginView): permission_classes = (permissions.AllowAny,) def get(self,request): example={ "username":"user_name", "password":"Your Password" } return Response(example) @method_decorator(csrf_exempt) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) … -
How to customize Image Chooser in Wagtail?
How do I customize the Image Chooser in Wagtail? I need to block the user from having the ability to upload GIFs > ~1 MB in size. Uploading a 3 MB GIF crashes the server right now, and even a 1.5 MB GIF timed out on production. I'm using wand and ImageMagick for the GIFs, I altered the disk quota for ImageMagick but it's not a viable solution on the server, the compression takes forever. So my next step is to totally block large GIFs from being uploaded. I want to set a limit of about 1 MB for GIFs. I don't want to fork the Wagtail framework to do this. Are there any alternative suggestions to get around this GIF problem? -
Django model inline with multiple FK's for both keys to the same model under one inline
I have a situation where I have a model related by two possible foreign keys to another, and I would like to display using a single inline, all the related model fields including both possible FK's. In the example below I have the models of an account and a transaction. All transactions are credit/debit pairs, which indicate the source and destination account using the two FK's, credited_account, and debited_account. class Account(models.Model): owner = models.ForeignKey(User) account_type = models.ForeignKey(AccountType) class Transaction(models.Model): created = models.DateTimeField(auto_now_add=True) amount = models.PositiveIntegerField() credited_account = models.ForeignKey(Account, related_name='credit_transactions', on_delete=models.PROTECT) debited_account = models.ForeignKey(Account, related_name='debit_transactions', on_delete=models.PROTECT) In the AccountAdmin I would like to display all the transactions where the account is either credited or debited, using a single Inline, under a single Transactions header. I know, as per the docs, that I am able to specify them independently by indicating the foreign key and using two different inlines, like so: class DebitInline(admin.TabularInline): model = Transaction fk_name = 'debited_account' class CreditInline(admin.TabularInline): model = LedgerTransaction fk_name = 'credited_account' class AccountAdmin(admin.ModelAdmin): inlines = [CreditInline, DebitInline] The problem I'm having here is that the credit and debit transactions are separated under two different inlines, of the same header, and I would like them ordered by … -
Django Form Fields not Displaying
So I am trying to basically have a check box on an image page which lets me set a boolean field true/false if I want this image to be deemed the "profile image." The problem is that the form field options are not showing up in the template. Any suggestions? single_image.html <form method='POST' action="{% url 'set_profile_image' plant_pk=plnt.pk image_pk=img.pk %}"> {% csrf_token %} <hr> {{ form.as_p }} <hr> <input type="submit" value="Submit"> forms.py class SetProfileImageForm(forms.ModelForm): """A form to set profile image.""" image_main = forms.BooleanField(required=True) class Meta: model = Image fields = ["image_main","image_url",] views.py def set_profile_image(request, plant_pk, image_pk): """A custom view function to set profile image.""" # find the plant for whom we are setting the image plant = Plant.objects.get(pk=plant_pk) if request.method == 'POST': if "cancel" in request.POST: return redirect('display_plant', pk=plant.pk) form = SetProfileImageForm(request.POST or None, request.FILES or None) if form.is_valid(): plant.set_profile_image(image_pk) return redirect('display_plant', pk=plant.pk) else: print("Error: the form was not valid.") else: return reverse('gallery', kwargs={'pk':plant.pk}) -
django only listening at 127.0.0.1
No matter what ip I put in it always listens on 127.0.0.1 This is what I enter to start django python manage.py runserver 0.0.0.0:8000 I am running it on windows WSL ( windows subsystem for linux ) ,this is my first time doing so . Now the wierd part : If I remove '127.0.0.1' from 'allowed_host' in settings it won't start and will ask me to put '127.0.0.1' in 'allowed_host'. The starting message is Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 16:18:59 Django version 3.1.2, using settings 'document_manager.settings' Starting development server at http://0.0.0.0:8000/ however when I make any request to http://0.0.0.0:8000/ it dosen't work ,but if I make a request on 127.0.0.1 it works . -
URL Based Language Setting Instead of Browser Language Preferences
I am trying to have both Persian (RTL) and the English version of the website in separate URLs like: www.domain.com/en-us www.domain.com/fa-ir This is the first time I am doing this. Therefore, I am kind of confused about that. What I actually did was getting help from this tutorial: https://monicalent.com/blog/2014/08/10/internationalization-with-django-backbone-underscore-template-and-sass-ltr-and-rtl-language Yet, I have no idea how should I make separate URLs for each language. Settings.py: USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_PATHS = ( '/locale/' ) LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en-us', 'English'), # You need to include your LANGUAGE_CODE language ('fa-ir', 'Farsi') ) Views.py of my home app: from django.shortcuts import render # Create your views here. def home(request): if hasattr(request.user, 'lang'): request.session['django_language'] = request.user.lang return render(request, 'index.html') Urls.py : from django.contrib import admin from django.urls import path import home.views urlpatterns = [ path('admin/', admin.site.urls), path('', home.views.home, name='index') ] index.html: {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kilka Shafagh</title> </head> <body> <span>{% trans "Test" %}</span> </body> </html> However, Even when I set language preferences to persian, the translation does not occur. I would be grateful if anyone guide me through this as the related topics on stackoverflow could … -
Running a JS module in a Django project
I am a beginner and would like to use this Javascript module (meant for Node) in my Django project in which I'm using Django's template system for the front-end: https://github.com/jshemas/openGraphScraper What is the best way to do this? Do I have to run Node alongside Django separately? -
unable to deserialize self referential foreign key with custom serializer
I am using django and django-rest-framework to create APIs I have a model like this class Version(models.Model): version_tag = models.IntegerField(verbose_name=_("Version")) data = models.TextField(verbose_name=_("Data")) cloned_from = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True ) endpoint = models.ForeignKey( ManagedEndpoint, verbose_name=_("Endpoint"), related_name="versions", related_query_name="version", on_delete=models.CASCADE, ) and a serializer like this class VersionSerializer(serializers.ModelSerializer): data = serializers.JSONField() version_tag = serializers.IntegerField(required=False) cloned_from = ClonedFromSerializer(required=False) resource_purpose = serializers.CharField( source="endpoint.resource_purpose", required=False ) class Meta: model = models.Version fields = [ "resource_purpose", "version_tag", "data", "cloned_from" ] and i have custom serializer ClonedFromSerializer like this class ClonedFromSerializer(serializers.Field): def to_representation(self, value): if value.endpoint is None: return "" return "%s : %s" % (value.endpoint.resource_purpose, value.version_tag) def to_internal_value(self, data): resource_purpose, version_tag = data.split(":") try: endpoint = models.ManagedEndpoint.objects.get( resource_purpose=resource_purpose.strip() ) return models.Version.objects.get( endpoint=endpoint, version_tag=version_tag.strip() ) except models.ManagedEndpoint.DoesNotExist: raise serializers.ValidationError( "invalid clone_from value passed" ) What I wanted to do is, cloned_from should output a string with resource_purpose and version_tag which is working correctly. What is not working is that when I make a post call i.e. when i want to create a new version with cloned_from is passed as a string, it is creating with clone_from=None. I don't have a clue why it is still None when am returning Version object. can anyone help ? -
How to show the total count of online users in the template (django)?
This is my user model- class CustomUser(AbstractUser): user_id = models.UUIDField(default=uuid.uuid4,editable=False,primary_key=True) username = models.CharField(max_length = 100,unique = True) friends = models.ManyToManyField('CustomUser',related_name="friend", blank= True) user_last_seen = models.DateTimeField(auto_now_add=False) I am able to track the time when a user was last seen (whether they log out or not) using the following middleware: class ActiveUserMiddleware(MiddlewareMixin): def process_request(self, request): current_user = request.user if request.user.is_authenticated: now = datetime.datetime.now() current_user.user_last_seen = now current_user.save(update_fields=['user_last_seen']) And also able to show in my template that whether they are active at the current moment, or when they were last seen - {%if i.user_last_seen|timesince|upto:',' < "1 minutes" %} <td style="font-size:small; color:green;text-align:right;"> Active Now </td> {%else%} <td style="font-size:small; color:gray;text-align:right;"> {{i.user_last_seen|timesince|upto:','}} ago </td> {%endif%} Along with this, I want to show the total number of users that are active right now. But I am having a hard time to understand how to do that exactly. I am still a beginner when it comes to Django, any suggestions or ideas would be really helpful. -
Django postgres connection, SET timezone for psycopg2
In django settings.py I have TIME_ZONE = 'Asia/Tbilisi' I have same timezone for postgres also and separately, both works correctly. Though, in Django, when I run raw queries like: from django.db import connection ... cursor = connection.cursor() cursor.execute("select localtimestamp(0)") res = cursor.fetchall() This shows datetime with UTC time zone. Probably this is caused by psycopg2 connection settings? because this: print( connection.cursor().connection.get_parameter_status("TimeZone") ) shows: UTC. Question: How can I change this connection settings and SET needed timezone? -
Django hosting raw HTML files behind authentication
I inherited an NGINX/Gunicorn/Django (1.11) server. I've only been poking around with Django for a little while. We have a piece of software that not everyone has a license for. It can dump out its data in a series of linked HTML files: index.html models/model_a.html models/model_b.html models/model_b/model_1.html models/model_b/model_2.html And so on. They're all linked together and navigable from the top-most file, index.html. I created a menu button and I linked it to a location where the HTML model is stored. Users can navigate to it and browse around, exactly as expected. Here's my problem. We're using SAML authentication. To use the menu button in Django, you obviously have to be logged in. But once you are sent to the link, you can reuse it forever. A user can send out the URL and and anyone using the link will bypass logging in completely. The URL would look like this: https://example.com/models/model_b/model_1.html Again, anyone with that URL can get to the information. I want to ensure anyone trying to access that HTML render of the software's model has to authenticate first. Any ideas? (Sorry if it's a basic question. I'm new at this and I'm not very smart in general. So there's …