Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django - Is it possible to find the mobile device name of users?
As the title suggests, is there any way to obtain the mobile device name (like Samsung Galaxy S10) of the client user? The best I have across is - Django-user_agents but it doesn't fetch that information - 
        
Problems to display django chart with chartit in right order
When I use Chartit PivotDataPool the month number is not in the right order. Chartit PivotDataPool graph is in this order 1, 10, 11, 2, 3, 4, 5, 7, 8, 9. I want to have right order like 1, 2, 3, 4 , 5, 6, 7, 8, 9, 10, 11. ![Graph image][1] ![1]:(https://imgur.com/UPBZY8G) ds = \ PivotDataPool( series= [{'options': { 'source': DerangementAdsl.objects.filter(annee=year), 'order_by': ['mois'], 'categories' : ['mois'], 'legend_by': ['sous_traitant'], }, 'terms': { 'total': Count('id') } } ]) pivcht = PivotChart( datasource=ds, series_options=[{ 'options': { 'type': 'column', 'stacking': True, 'order_by': 'mois', }, 'terms': ['total'] }], chart_options={ 'title': { 'text': 'Répartition dérangements relevés / structure' }, 'xAxis': { 'title': { 'text': 'Semaine' } } } ) - 
        
How to add button on django model in django admin panel
I want to add two buttons in model objects in Django. I haven't tried anything. the buttons are "Approve" and "Deny". enter image description here - 
        
How make a simple rest-framework example?
I'm trying to make a hello world in Django and rest-framework, but when acess the url: http://localhost:4444/products to get all products the terminal is giving me this error: Traceback (most recent call last): File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/mixins.py", line 45, in list serializer = self.get_serializer(queryset, many=True) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/generics.py", line 110, in get_serializer return serializer_class(*args, **kwargs) TypeError: object() takes no parameters [06/Dec/2019 11:49:35] "GET /products HTTP/1.1" 500 17530 I use Django, but i dont know how start a project from 0. Here is my code: view.py: from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from rest_framework.response import Response from .models import Product from .serializers import ProductListSerializer class ProductViewSet(viewsets.ModelViewSet): lookup_field = 'pk' model = Product queryset = … - 
        
Passing a value from html template to views.py in Django using AJAX
can someone please assist me with this issue? I am new to Django and I've been trying to create a web-based application which gets the user location and displays the shops around them from the tutorial I followed online. However, the initial values were hard-coded in the views.py in order to change the user's location. I've asked a question before in order to find the best solution to this, and the kind people advised to use AJAX. I've been trying to come up with a solution for few hours now and its driving me insane. I have never used AJAX before so I apologize for this. This is what I have so far, no issues or errors when running the application, however, the values are not changing for user's location Please see attached code views.py user_location = Point(0, 0, srid=4326) def process_loc(request): lat = float(request.GET.get('lat')) lon = float(request.GET.get('lon')) global user_location user_location = Point(lat, lon, srid=4326) return render(request, 'shops/index.html', {'lat': lat, 'lon': lon}) class Home(generic.ListView): model = Shop context_object_name = 'shops' queryset = Shop.objects.annotate(distance=Distance('location', user_location) ).order_by('distance')[0:15] template_name = 'shops/index.html' As it can be seen I'm declaring the user_location is located outside the function and then changing it inside the function, so … - 
        
Django Admin - Filter inline content depending on parent value
I have to models: "Order" and "Product"; the "Order" contains a "Customer" as foreign key. I create an admin page where Order is the parent and products are shown as inline. When I add a new istance of products I want that a dropdown is filtered based on the value chosen in the parent "Customer" field. I've already tried the chained dropdown list with no success; I've also overriden the init method of the inline form but the result is the same. I can't understand what is the metod triggered when I click the "add new" link in inline formset. Do you have any suggestion on how to achieve the result? - 
        
Any way to schedule an event similar to MySQL Events in Django?
I have a database event working with my Django application (hosted on apache2) to update a Date field in one of my tables. This date field influences another column in the table Inspection_Due? which returns Yes or No depending on what Date is in the row. I'd like to do more than just update the table here though which is why I'm wanting to move away from SQL Events. I want to be able to send off emails, texts, notifications etc whenever this is changed. So I wanted to know if there was any existing method of creating a background event in Django without me opening any views to achieve this whenever the Date column in the database is altered. - 
        
Why is this happening?(Weird thing occuring with django models)
This is really weird and to me makes no sense (at least at the moment). I have the following code in models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.db.models import Max,Count from django.apps import apps # Create your models here. class Player(models.Model): player_name = models.CharField(max_length=150) current_level_no = models.IntegerField(null=True) no_of_moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players' def __str__(self): return self.player_name class PlayerStats(models.Model): player_name = models.ForeignKey(to=Player, on_delete=models.CASCADE) level_no = models.IntegerField(null=True) moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players Stats' # It works! TotalLevels = 25 MaxCurrentLevels = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels'] playerscount = PlayerStats.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players'] print(playerscount) def create_player(sender, instance, created, **kwargs): if created: new_username=instance.username Player.objects.create(player_name=new_username, current_level_no=None, no_of_moves=None) def delete_player(sender, instance, **kwargs): deleted_username=instance.username Player.objects.filter(player_name=deleted_username).delete() def create_player_stat(sender, instance, **kwargs): for x in range(1, TotalLevels+1): PlayerStats.objects.create(player_name=instance, level_no=x, moves=None) post_save.connect(create_player, sender=User) post_delete.connect(delete_player, sender=User) post_save.connect(create_player_stat, sender=Player) I have no idea why querying for Max value of the Level field of the model PlayerStats gives me no errors but Count of distinct Player names field of the same model give me an error that Models aren't loaded yet. It should give me the same error if the Model hasn't loaded yet when querying for max value but it doesn't. If I comment … - 
        
How to join multiple related models using select_related or prefetch_related in Django?
I have 5 related models that I want to show in my template. For every Collection I want to show all Product that belong to corresponding collection (ProductCollection). The informations I need for every product are: name (ProductAlias) and image (ProductImage). The raw query should be like: SELECT c.name, pa.name, pi.image FROM Collection c JOIN ProductCollection pc ON c.collection_id = pc.collection_id JOIN Product p ON pc.product_id = p.product_id JOIN ProductAlias pa on p.product_id = pa.product_id JOIN ProductImage pi on p.product_id = pi.product_id WHERE pi.default = 'True' and pa.market_id = 1 models.py: class Collection(models.Model): name = models.CharField() class Product(models.Model): video = models.URLField() class ProductCollection(models.Model): collection = models.ForeignKey(Collection, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ProductAlias(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) name = models.CharField() class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField() default = models.BooleanField() I seperate name of the product into another model because 1 product has many names depending on the region they're marketed at. A product also has many images. My current attempt on views.py with function-based view (without applying the filter yet because I already got ValueError during template rendering): def collection_view(request): # tried to chain the prefetch_related on multiple models but failed. collections = … - 
        
Accessing value of a Django model which has foreign keys, the foreign keys model also has foreign keys
I have Django models which have foreign keys, the foreign keys model also has foreign keys. How do I access all these values and return to the user? Below is a sample representation of my models: assessmentDeadlineMapping has foreign key to -> assessmentMaster which has foreign key to -> assessmentClassesMapping which has foreign key to assessment Below are the models: models.py class Assessment(models.Model): index = models.IntegerField(primary_key=True) name = models.CharField(blank=True, null=True, max_length=100) number = models.IntegerField(blank=True, null=True, default=None) class Meta: db_table = 'assessment' verbose_name = ("Assessment") verbose_name_plural = ("Assessments") def __int__(self): return self.index def __str__(self): return self.name + ' - ' + str(self.number) class AssessmentClassesMapping(models.Model): index = models.IntegerField(primary_key=True) classesSubjectMapping = models.ForeignKey(ClassesSubjectMapping, on_delete=models.CASCADE) assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) class Meta: db_table = 'assessment_classes_mapping' verbose_name = ("Assessment to Classes Mapping") verbose_name_plural = ("Assessments to Classes Mapping") def __str__(self): return str(self.assessment) + ' - ' + str(self.classesSubjectMapping) class AssessmentMaster(models.Model): assessment_code = models.IntegerField(primary_key=True) start_date = models.DateTimeField(blank=False, null=False) end_date = models.DateTimeField(blank=False, null=False) academic_year = models.CharField(blank=True, null=True, max_length=50) mapped_Assessment = models.ForeignKey( AssessmentClassesMapping, on_delete=models.CASCADE) session = models.CharField(blank=True, null=True, max_length=50) class Meta: db_table = 'assessment_master' verbose_name = ("Assessment Master") verbose_name_plural = ("Assessments Master") def __str__(self): return str(self.academic_year) + ' - ' + self.session + ' - ' + str(self.mapped_Assessment) class AssessmentDeadlineMapping(models.Model): … - 
        
How to post data to the tables in database having associations in django?
I am a learning django and I want to replicate this application https://www.modsy.com/project/room storing all the card details clicked by the user in every step in the database. How can I do this as of now I am having class rooms(models.Model): id = models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') class goals(models.Model): id=models.IntegerField(primary_key=True) goal = models.CharField(max_length=50,default='0000000') class designs(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') class users(models.Model): room_id = models.IntegerField(default=0) email = models.CharField(max_length=50,default='0000000') password = models.CharField(max_length=50,default='0000000') rooms,goals,designs for displaying those data in database and users table can you please suggest what can be the associations for this app and how can we store that in tables having associations. - 
        
How to use GraphQL customized Authentication class?
With Django REST Framework(DRF) I can customize Authentication class and Permission class simply like this from django_cognito_jwt import JSONWebTokenAuthentication from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated class CognitoQuestionViewSet(viewsets.ModelViewSet): authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Question.objects.all() serializer_class = QuestionSerializer In the GraphQL docs. It is using standard Django login which is different from my project. I had checked with source LoginRequiredMixin but no luck. I don't see Authentication class there then I can override it Problem: How to customize GraphQL Authentication class and Permission class like one I did in DRF - 
        
Django Rest Framework: Allow child models to be created either within a parent or seperately
Say I have a set of nested serialisers like: class ChildSerializer(serializers.ModelSerializer): class Meta: model = models.Child fields = ['id', 'name'] class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) class Meta: model = models.Parent fields = ['id', 'name', 'children'] def create(self, validated_data): children = validated_data.pop('children') parent = super().create(validated_data) for child in children: child['parent'] = parent self.fields['children'].create(children) return parent If I send the payload to the ParentViewSet: payload = { 'name': 'parent', 'children': [ { 'name': 'child', } ], } It creates both models fine, but if I send the following payload to the ChildViewSet: payload = { 'name': 'child', 'parent': parent.pk, } It will fail because it parent isn't included in the Child serializers field attribute. If you include the attribute, the reverse is true. The second payload works, but the first one fails because you aren't including the parent field (since you're creating the two models at the same time). Is there a way around this behaviour? I'd like to have create methods for both Parent and Child, but I can't seem to configure my serialisers to do this. - 
        
Jupyter Notebook + Django with web interface
I don't know if this is possible but, I know you can install juyter notebook in a virtual env and call upon the notebooks via Django Rest API (https://www.deploymachinelearning.com/) but that's not what I want. I would like to run Jupyter notebook in the background of the Django server while it displays a web interface for the notebook while a user is currently looking at. I know you can export your notebooks with nbinteract (https://www.nbinteract.com/) but that way is pretty messy and not really Interactive... it leans more towards the static side of things. It makes a bootstrap page with graphs and sliders that change values depending on what the user does with the slider or graph. and the HTML document that nbinteract generates is around 14k lines of messy code per notebook. I would love it if I can find a way to have an interface of jupyter within my website so that users can see the notebook and make changes to it but if they leave the page the notebook doesn't save the changes that the user made. Any ideas would be welcomed! Thank you in advance EDIT I've been searching for a way to this for about … - 
        
TypeError: expected string or bytes-like object Django's Model problem when i migrate
I'm looking for the answer for 5 days now and i can't resolve it ! Basically i try to implement a model for my project in Django. The problem is that i have the same mistakes when i put all the date in comment and when i'm not (TypeError: expected string or bytes-like object). Here is the code : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from datetime import datetime class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, default='') role = models.CharField(max_length=50) status = models.CharField(max_length=50) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.Profile.save() def __str__(self): return self.user #Matrix_template's definition class Matrix_Template(models.Model): #initialize Choices for templates STATUS_CHOICE=( ('New','New'), ('Pending','Pending'), ('Finished','Finished'), ('Ignored','Ignored') ) id = models.AutoField(primary_key=True,auto_created=True, default='') #Foreign key with a delete on cascade (Cf class diagram) User_id = models.ForeignKey('Profile',on_delete = models.CASCADE, default='') name = models.CharField(max_length=50) num_cols = models.IntegerField(default=0) num_rows = models.IntegerField(default=0) col_headers = models.CharField(max_length=200) row_headers = models.CharField(max_length=200) influence_set = models.CharField(max_length=2, default='') influence_desc = models.ImageField() conviction_set = models.CharField(max_length=2, default='') conviction_desc = models.ImageField() coloration_rules = models.CharField(max_length=200) date_creation = models.DateTimeField(auto_now=True) date_update = models.DateTimeField(auto_now=True) description = models.CharField(max_length=200, default='') status = models.CharField(max_length=50,choices=STATUS_CHOICE,default='New') def get_id(self): return id def … - 
        
Remove none fileds from django templates
I created a django template with the following model Models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') product1 = models.CharField(max_length=500,default=0,blank=True,null=True) product1_quantity = models.IntegerField(default=0,blank=True,null=True) product2 = models.CharField(max_length=500,default=0, blank=True,null=True) product2_quantity = models.IntegerField(default=0,blank=True,null=True) product3 = models.CharField(max_length=500,default=0, blank=True,null=True) product3_quantity = models.IntegerField(default=0,blank=True,null=True) product4 = models.CharField(max_length=500,default=0, blank=True,null=True) product4_quantity = models.IntegerField(default=0,blank=True,null=True) product5 = models.CharField(max_length=500,default=0, blank=True,null=True) product5_quantity = models.IntegerField(default=0,blank=True,null=True) product6 = models.CharField(max_length=500,default=0, blank=True,null=True) product6_quantity = models.IntegerField(default=0,blank=True,null=True) product7 = models.CharField(max_length=500,default=0, blank=True,null=True) product7_quantity = models.IntegerField(default=0,blank=True,null=True) product8 = models.CharField(max_length=500,default=0, blank=True,null=True) product8_quantity = models.IntegerField(default=0,blank=True,null=True) and I tried displaying this data on the template using this view def load_salesorder(request): so_id = request.GET.get('sales_order') s_o = MaterialRequest.objects.filter(pk=so_id) print("kits=========",s_o) return render(request, 'allotment_so.html', {'sales_order': s_o}) HTML <table class="table table-bordered"> <thead> <tr> <th>Product Short Codes</th> <th>Product Quantity</th> </tr> </thead> <tbody> <div class="table-container"> {% for i in sales_order %} <tr> <td class="align-middle">{{ i.product1 }}</td> <td class="align-middle">{{ i.product1_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product2 }}</td> <td class="align-middle">{{ i.product2_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product3 }}</td> <td class="align-middle">{{ i.product3_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product4 }}</td> <td class="align-middle">{{ i.product4_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product5 }}</td> <td class="align-middle">{{ i.product5_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product6 }}</td> <td class="align-middle">{{ i.product6_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product7 }}</td> <td class="align-middle">{{ i.product7_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product8 }}</td> <td class="align-middle">{{ i.product8_quantity }}</td> </tr> … - 
        
Customize schema of dango REST's framework for documentation
I am trying to document my APIs with the inbuilt REST documentation for APIs. I get it to render all my endpoints which is great. Now I want to customize the schema but I am unsure how to achieve that. I know that swagger has a schema generator but I would like to tweak what django already provides me. I am going this so far by doing: API_TITLE = "title" API_DESCRIPTION = "description" urlpatterns = [ path('docs/', include_docs_urls( title=API_TITLE, description=API_DESCRIPTION, permission_classes=[IsAdminUser]) ), that renders me all my endpoint. I add a screenshot. I would like for instance to fill the description for the thus far empty fields. I also would like to delete some stuff. I am not really clear on how to use schemas and how manipulate them and use them in django. I also can't find docs that are comprehensible to me. I know they are in .yml format but how can I get them and manipulate them? Or how can I build my own? Can someone help me with this? Thanks in advance, very much appreciated! I would like to delete for example the grey boxes and fill the blanks in the description. - 
        
How do I return a list in a Django Annotation?
Right now I have the following, very slow but working code: crossover_list = {} for song_id in song_ids: crossover_set = list(dance_occurrences.filter( song_id=song_id).values_list('dance_name_id', flat=True).distinct()) crossover_list[song_id] = crossover_set It returns a dictionary where a song ID is used as a dictionary key, and a list of integer values is used as the value. The first three keys are the following: crossover_list = { 1:[38,37], 2:[38], .... } Does anyone here know of a succinct way to wrap this up into a single query? The data exists in a single table that has three columns where each song_id can be associated with multiple dance_ids. song_id | playlist_id | dance_id 1 1 38 1 2 37 2 1 38 Ideally, what I am trying to figure out how to return is: <QuerySet[{'song_id':1, [{'dance_id':38, 'dance_id':37}]}, {'song_id':2, [{'dance_id':38}]}]> Any ideas or help is appreciated. - 
        
My django template navbar is not working properly
Here I have two template called base.html and contact.html.contact.html extends the base.html.I only have these two templates.When i click blog or about it scrolls me to the about section or blog section. But the problem is while going to the contact page and when I try to click the any of the url in nav bar home or about from contact page it doesn't go anywhere.How can I solve this? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('contact/', views.contact, name='contact'), views.py def home(request): abt_me = Me.objects.order_by('-created').first() return render(request,'base.html',{'abt':abt_me}) def contact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact = form.save() messages.success(request, 'Hello {}!. Your message has been sent successfully'.format(contact.full_name)) return redirect('contact') return render(request,'contact.html',{'form':form}) base.html <nav class="site-navigation position-relative text-right" role="navigation"> <ul class="site-menu main-menu js-clone-nav mr-auto d-none d-lg-block"> <li><a href="#home" class="nav-link">Home</a></li> <li><a href="#blogs" class="nav-link">Blog</a></li> <li><a href="#about" class="nav-link">About</a></li> <li><a href="{% url 'contact' %}" class="nav-link">Contact</a></li> </ul> </nav> <div class="site-section" id="about"> <div class="container"> <div class="row "> contact.html {% extends 'base.html' %} {% load static %} {% block content %} <section class="site-section"> - 
        
Create an event to update a table depending on entries from 2 other tables
Ok so I have these three tables created by my Django models in MariaDB: I want to create a daily event to update "LastInspected" in moorings_part whenever someone adds an inspection item. This should be the latest moorings_inspectionreport.Date available with an InspectionID_id which relates to the relevant moorings_inspection.PartID_id. It's really confusing me with not only the ordering by dates but trying to juggle 3 tables for this too. - 
        
Django Rest Framework Not Null Error when creating from payload
I'm trying to write a test to check that the create method of my Viewset works ok: @pytest.mark.django_db def test_create(admin_user): parent = factories.ParentFactory() payload = { 'name': 'child', 'parent_id': parent.pk, } view = views.ParentViewSet.as_view({'post': 'create'}) request = factory.post('/', payload, format='json') force_authenticate(request, user=admin_user) response = view(request) assert response.status_code == status.HTTP_201_CREATED assert models.Child.objects.count() == 1 child = models.Child.objects.first() assert child.name == 'child' However, I get the following error when I run the code: psycopg2.errors.NotNullViolation: null value in column "parent_id" violates not-null constraint But the test for the Parent create method runs fine: def test_create(admin_user): payload = { 'name': 'parent', 'children': [ { 'name': 'child', } ], } view = views.ParentViewSet.as_view({'post': 'create'}) request = factory.post('/', payload, format='json') force_authenticate(request, user=admin_user) response = view(request) assert response.status_code == status.HTTP_201_CREATED assert models.Parent.objects.count() == 1 season = models.Parent.objects.first() assert season.name == 'parent' assert season.children.count() == 1 Can someone tell me the correct way to write the payload for the child test create? - 
        
Django-ORM select columns from two tables
I have two models and one model has generic foreign key relation I want select the columns from both the tables. Can anyone help - 
        
Django - Import_Export Custom Validation
Im using django import_export to upload data from excel. I want to customise the validation errors to warnings that everybody can understand, For example: NON-NULL Value Error ---> Hey there, please make sure there are no empty cells in the datasheet. Ive looked into the import_export library but I couldnt find any validation at all. Thank you for any suggestions - 
        
Django selenium: i18n partially works
I currently develop a Django project and have a functional test using selenium. It was running until I internationalize my app. I do not understand why some 'send_keys' correctly use the translation but other do not. I try to find out how different are input that do not work but can't find. test.py from django.utils.translation import ugettext_lazy as _ # from django.utils.translation import ugettext as _ def test_randomisation(self): self.selenium.find_element_by_xpath('//*[@id="navbarSupportedContent"]/ul[1]/li[5]/a').click() PatientCode = self.selenium.find_element_by_xpath('//*[@id="table_id"]/tbody/tr[1]/td[1]').text self.selenium.find_element_by_xpath('//*[@id="table_id"]/tbody/tr[1]/td[4]/a').click() PatientCodeFormulaire = self.selenium.find_element_by_xpath('/html/body/div[1]/div[1]/div[1]').text self.assertEqual(PatientCodeFormulaire[14:24],PatientCode) ran_inv = self.selenium.find_element_by_xpath('//*[@id="id_ran_inv"]') ran_inv.send_keys('Slater') ran_pro = self.selenium.find_element_by_xpath('//*[@id="id_ran_pro"]') **ran_pro.send_keys(_('On-line'))** # problem here ran_pro_per = self.selenium.find_element_by_xpath('//*[@id="id_ran_pro_per"]') ran_pro_per.send_keys('Iron') ran_crf_inc = self.selenium.find_element_by_xpath('//*[@id="id_ran_crf_inc"]') **ran_crf_inc.send_keys(_('Yes'))** # problem here ran_tbc = self.selenium.find_element_by_xpath('//*[@id="id_ran_tbc"]') ran_tbc.send_keys(_('Possible')) ran_crf_eli = self.selenium.find_element_by_xpath('//*[@id="id_ran_crf_eli"]') **ran_crf_eli.send_keys(_('Yes'))** # problem here ran_cri = self.selenium.find_element_by_xpath('//*[@id="id_ran_cri"]') **ran_cri.send_keys(_('Yes'))** # problem here ran_sta = self.selenium.find_element_by_xpath('//*[@id="id_ran_sta"]') ran_sta.send_keys(_('Mild')) ran_vih = self.selenium.find_element_by_xpath('//*[@id="id_ran_vih"]') ran_vih.send_keys(_('Negative')) django.po # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-12-06 10:03+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: .\intenseTBM_eTool\settings.py:160 msgid "English" msgstr "Anglais" #: … - 
        
Django: Unable to load admin page and HTML page using TemplateView.as_view()
I used the django-twoscoops project template to setup a simple project (made some modifications to use django 2.2.5). My project urls.py looks like this: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.views.generic import TemplateView urlpatterns = [ # Landing page. path('', TemplateView.as_view(template_name='base.html')), # Admin. path('admin/', admin.site.urls), # Apps. path('polls/', include('apps.polls.urls')), ] I ran check and no issues were found. When I run the server, and connect to 127.0.0.1:8000/admin/ I get an error. However, if I go to 127.0.0.1:8000/polls/ the polls page loads OK. I also get an error if I try to go to 127.0.0.1:8000 (it complains base.html is not found and I don't understand why it is looking at a different path). I am not sure what I am doing wrong. Admin error: OSError at /admin/login/ [Errno 22] Invalid argument: 'C:\\Users\\drpal\\PycharmProjects\\tvpv_portal\\:\\admin\\login.html' Landing page error: OSError at / [Errno 22] Invalid argument: 'C:\\Users\\drpal\\PycharmProjects\\tvpv_portal\\:\\base.html' For landing page, I have set 'DIRS' in TEMPLATE dictionary to point to C:\Users\drpal\PycharmProjects\tvpv_portal\templates which contains base.html, so I'm not sure why it is looking one directory above. The settings are shown below but I am not sure what the culprit could be: ABSOLUTE_URL_OVERRIDES {} ALLOWED_HOSTS [] APPEND_SLASH True AUTHENTICATION_BACKENDS …