Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why block tag in django framework is working properly?
i'am new to django , i have been trying to replace small contant of the "base.html" with the contant of "contact.html" but nothing happends base.html <!DOCTYPE html> <html> <head> <title>this is base</title> </head> <body> {% block content %} replace me {% endblock %} </body> </html> contact.html {% extends "base.html" %} {% block content %} <h1>this is contact,contact is working congrats</h1> {% endblock %} result setting.py -
Author page in django migrations and questions
I want to make a website for eBooks with a page that has all the books published by one of the authors. The problem is that I have no idea how to do that. I will mention that I am a beginner. I tried this int the model file class Author(models.Model): author = models.TextField() class Product(models.Model): β¦ author=models.ForeignKey(Author,on_delete=models.CASCADE) The result in the terminal was: File "/home/user/petnet/petnet-env/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 264, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'store_product' with primary key '2' has an invalid foreign key: store_product.author_id contains a value 'anonim' that does not have a corresponding value in store_author.id. I think this is caused by the act that I made the author field later and there were already authors fields from before, but then, when I tried to revert back to what I had before doing this, I got some errors regarding migrations. Also the views were: def author_detail(request, slug): author = get_object_or_404(Author, slug=slug) products = author.products.filter(status=Product.ACTIVE) return render(request, 'store/author_detail.html', { 'author':author, 'products':products }) But I am also curious if there is a chance I could use only this for models so I could use the form for adding a product in a much easier way. class Product(models.Model): β¦ -
Django: Problems passing a list and the results of the list treated by a function as two separate variables to the template
I'm trying to make CV website which has a sudoku generator and solver. The generator and solver are two separate functions in the functions.py file imported into the views.py file. My sudokus are stored in a list of 9 lists of 9 ints. from views.py: from functions import * def sudoku(request): grid = make_sudoku() # generates unsolved sudoku list solved = solve(grid) # generates solved list of unsolved list fed in. count = [i for i in range(9)] context = { 'grid': grid, 'solved': solved, 'count': count } return render(request, 'main/sudoku.html', context) if I print grid, I get an unsolved sudoku list. If I print solved, I get a the same list which has been solved. Everything works dandy up until that point, but if I go to sudoku.html and type {{ grid }}, I get a solved sudoku list. As the tree said to the lumberjack, I'm STUMPED! I'm completely baffled as to why this might happen because at no point in sudoku.html do I refer to grid or solved outside of passing them on to sudoku.js which actually makes the puzzle. -
I can't connect to postgresql database in deployment
Hello I just want to deploy my django project in python anywhere .... and when I run the command py manage.py migrate it shows this error message django.db.utils.OperationalError: connection to server at "<Host name>" (<IP address>), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I think that the problem in python anywhere because when I connect to the server in pgadmin using the same info in the settings.py file I don't get any error messages and you have to know that I am using neon.tech for my postgresql database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<the database>', 'USER':'<User>', 'PASSWORD':'<Password>', 'HOST':'<Host>', 'PORT':5432, } } and I am sure that all information is right because I used it to connect to the server in pgadmin in my local machiene -
can we integrate websockets (ws) in our current project which only uses http.Can websockets and http can work together in one project .DJANGO CHANNELS
I created a social network site using django and my project or site was only using django with http protocols. I only have crud like features in my site but now i discovered about django channels. Django Channels allow django project to not only handle http but can also work with websockets protocol. So can we integrate websockets protocol in the website which only uses http ?. Can http and websockets protocol can work together in one project or one website ?. Can we integrate django channels in the existing django project which only uses http protocol ?. Is any website only have to use one protocol ? Hope you will help me in my journey. π I tried using django channels and django in one project and it was working fine . Both http and websockets protocols was working fine but i want answer from a experience developer bcoz i don't have much knowledge about networking and protocols and i never used websockets before. -
how to do makemigrations/migrate in gnadi(python/postgresql web hebergement)
I am a python developer and new to GANDI (python/PostgreSQL web hosting). There is no document to migrate databases to their server. they have their document to deploy a Project Django but not very clear there are a lot of things missing. After taking a lot of time on the internet, I managed to deploy a Django project in their server. The site works smoothly with an SQLite database. Now I would like to make a Django Project with PostgreSQL. I have an emergency console, but I would like to work locally and then I would like to migrate the DBs to their phpPGadmin server. I just need your help to do makemigrations/migrate to thier PostgreSQL(PhpPGadmin) server. Thanks in advance. -
Different behavior between multiple nested lookups inside .filter and .exclude
What's the difference between having multiple nested lookups inside queryset.filter and queryset.exclude? For example car ratings. User can create ratings of multiple types for any car. class Car(Model): ... class Rating(Model): type = ForeignKey('RatingType') # names like engine, design, handling user = ... # user Let's try to get a list of cars without rating by user "a" and type "design". Approach 1 car_ids = Car.objects.filter( rating__user="A", rating__type__name="design" ).values_list('id',flat=True) Car.objects.exclude(id__in=car_ids) Approach 2 Car.objects.exclude( rating__user="A", rating__type__name="design" ) The Approach 1 works well to me whereas the Approach 2 looks to be excluding more cars. My suspicion is that nested lookup inside exclude does not behave like AND (for the rating), rather it behaves like OR. Is that true? If not, why these two approaches results in different querysets? -
problème sur makemigration en Django [closed]
Comment résoudre le problème de Aucun changement détecté en Django en faisant le makemigration. Comment résoudre le problème de Aucun changement détecté en Django en faisant le makemigration. -
Is good convention to define list_select_related always for all model ForeignKey fields?
I'm just doing some optimizations in my Django app and I wondered if it's a good convention when I always define list_select_related with all model ForeignKey fields in the model Admin. Now I'm not talking about ManyToMany etc where I should use prefetch_related on my own in queryset. -
Django ORM vs raw SQL - security
My django project makes use of lots and lots of database queries, some are complex and some are basic SELECT queries with no conditions or logic involved. So far I have been using the sqlite3 module to manage my database, instead of the django ORM which has worked very well. One problem or drawback I am aware of using raw SQL queries is their security flaws when compared to django's ORM, such as being viable to SQL injection attacks when passing in user input into my raw SQL queries. My question is - Is it absolutely necessary to use django's ORM for queries involving user input or can I use a general function to remove any potentially malicious characters eg (,' -, *, ;) def remove_characters(string:str): characters = ["'", ";", "-", "*"] for char in characters: if char in string: string = string.replace(char, "") return string example of vunrable query in my project username = "logan9997" password = "x' or 'x' = 'x" def check_login(self, username, password): sql = f""" SELECT * FROM App_user WHERE username = '{remove_character(username)}' AND password = '{{remove_character(password)}' """ Without the remove_characters function a hacker could gain access to someone else's account if the inputs were β¦ -
How to log in in existing password account with google auth django?
I have problem with google auth. Steps to reproduce problem: Register password account Try to log in with google auth Get 500 answer Traceback: Internal Server Error: /api/v1/auth/google/ Traceback (most recent call last): File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/andrew/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 54, in dispatch return super().dispatch(*args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/andrew/Documents/pets_backend/project/api_v1/views/social.py", line 77, in post response = super().post(request, *args, **kwargs) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 220, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/home/andrew/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 422, in run_validation value = self.validate(value) File "/home/andrew/.local/lib/python3.10/site-packages/dj_rest_auth/registration/serializers.py", line 151, in validate complete_social_login(request, login) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login return _complete_social_login(request, sociallogin) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", line 172, in _complete_social_login ret = _process_signup(request, sociallogin) File "/home/andrew/.local/lib/python3.10/site-packages/allauth/socialaccount/helpers.py", β¦ -
Importing a file to a Django project - errors when running manage.py due to location of script
So, I know the source of my error, and I can fix it in a kind of hacky way, but I want to know the sort of best practices way of solving it - especially as my hacky way runs into issues when running stuff via commandline - and throws errors in my IDE. So, I have a django project, the folder tree looks like this (edited out irrelevant parts) βββ manage.py βββ simulator β βββ angus_testing.py β βββ events.py β βββ parser.py β βββ parser_test.py β βββ patch.py β βββ simulator.py βββ VSPOMs β βββ settings.py β βββ urls.py β βββ wsgi.py βββ VSPOMsApp βββ admin.py βββ apps.py βββ models.py βββ tests.py βββ urls.py βββ views.py When I run manage.py that is obviously running in the . directory. views.py is in the VSPOMSapp directory. If I have the following imports in views.py from ..simulator.patch import Patch from ..simulator.simulator import Simulator The IDE doesn't throw an error - and this is correct as it is searching in the parent directory for a file called patch in a folder called simulator that is in the dir above. However, when I run manage.py this causes me to get an error ImportError: attempted β¦ -
Can't add ManyToMany relation in admin
I have following model created in Django: class Content(models.Model): publish_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length = 100, blank = False, default='name') summary = models.CharField(max_length=400, blank=True, default='summary') description = models.TextField(blank = True, max_length=5000, default = LOREM_IPSUM) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) rules = models.TextField(blank = True, default='rule set') parent = models.ManyToManyField(to = 'self', related_name="child", symmetrical = False, blank=True) I added four Content objects through Django admin: Project1 Task1 Task2 Task3 And set parent to Project1 for all TaskX. When I want to display all the content with detailed parent atrribute it turns out to be None. views.py def display_ideas(request): ideas = Content.objects.filter(name="Task3") return render(request, 'display_ideas.html', context = { 'ideas' : ideas }) ** display_ideas.html ** <div class="container bg-success"> {% for idea in ideas %} <div class="container bg-danger"> <h2>Name:</h2> {{ idea.name }} has parent: {{ idea.parent.name }} </div> {% endfor %} </div> The output is: Name: Task3 has parent: None What am I doing wrong? All migrations are done and the site is up and running. -
Python Django Interaction with Third Party Backend via Client Library
I am programming a web frontend and backend with Python Django for a FinTS client (https://python-fints.readthedocs.io/en/latest/). The FinTS client library provides an API to communicate with a third party backend. The communication with the FinTS client has to be done in multiple steps: first connect then the backend asks for a TAN number the TAN number has to be provided then transactions can be fetched Basically the sequence looks like this: Sequence I am struggling with the question how I could realize this in detail with Django. I did some experiences with Django, Django Channels and Websockets, but without real success. I tried so far: A Django view provides a Django form The web client creates a websocket connection to a WebSocketConsumer The WebSocketConsumer provides its Django channel name to the web client The web client posts the form with credentials including the channel name When the form is posted, the view sends a message via a Django Channel to a BackgroundWorker inlcluding the web socket channel name The BackgroundWorker instantiates the FinTS client object and initiates the connection. The BackgroundWorker sends a message to the WebSocketConsumer asking for the TAN The WebSocketConsumer sends a web socket message to the β¦ -
Can't add file apache2/wsgi.24.0.1.sock to tar: archive/tar: sockets not supported
I try to build my Docker image : sudo docker build --ulimit nofile=8192:8192 . And I got the following error : Can't add file /var/lib/docker/overlay2/8a4e2447c4fc77a20c1f075fc5d887520fe22dd6ee559cfd480287e4914a1c5c/diff/run/apache2/wsgi.24.0.1.sock to tar: archive/tar: sockets not supported Some informations on my env : . βββ .dockerignore βββ .env βββ .git βββ .gitignore βββ .gitlab-ci.yml βββ Dockerfile βββ Project βββ README.md βββ docker-entrypoint.sh βββ requirements.txt βββ site-config.conf βββ user βββ utils Dockerfile : FROM debian:bullseye-slim RUN apt-get update RUN apt-get install -y apt-utils dialog RUN apt-get install -y nano curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 python3-venv RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN pip install --upgrade pip ENV PYTHONUNBUFFERED 1 RUN mkdir /code/ WORKDIR /code/ COPY requirements.txt /code RUN python -m venv .env RUN pip install -r requirements.txt COPY . /code/ ENV F_FROM_DOCKER=True RUN chmod 775 docker-entrypoint.sh ADD ./site-config.conf /etc/apache2/sites-available/mpn.conf RUN a2dissite 000-default RUN a2ensite mpn RUN service apache2 start EXPOSE 80 3500 CMD ["./docker-entrypoint.sh"] It's a Django project using apache. I already tried solutions here but nothing worked for me. When I run my docker image in interactive mode I haven't any interactivity (I am not sure this is linked with the build error) : ~/workspace/docker_mpn$ sudo docker run --interactive β¦ -
How can I send swift json to django server?
Swift code: static func send(url: URL, data: Data) async { var request = URLRequest(url: url) request.httpMethod = "POST" let json: [String: Any] = [ "order_details": ["meal_id":"6", "quantity":"1"], "restaurant_id": "1", "access_token": "FUJMNpU77OyuLiohOl5wzRQkGpHleV", "address": "13" ] let jsonData = try? JSONSerialization.data(withJSONObject: json) request.httpBody = jsonData print(String(data: jsonData ?? Data(), encoding: .utf8)) do { let (_, response) = try await URLSession.shared.data(for: request) guard let statusCode = (response as? HTTPURLResponse)?.statusCode, 200..<300 ~= statusCode else { throw URLError(.badURL) } } catch { print(error) } } Print: Optional("{\"address\":\"13\",\"order_details\":{\"quantity\":\"1\",\"meal_id\":\"6\"},\"restaurant_id\":\"1\",\"access_token\":\"FUJMNpU77OyuLiohOl5wzRQkGpHleV\"}") JSON looks normal. BUT in my django server I get this: if request.method == "POST": print(request.POST) Print: <QueryDict: {'{"address":"13","order_details":{"quantity":"1","meal_id":"6"},"restaurant_id":"1","access_token":"FUJMNpU77OyuLiohOl5wzRQkGpHleV"}': ['']}> i.e. my request becomes a key I tried to compose the request in different ways, I used JSONEncoder and JSONSerializer but nothing happened -
In Django, why does queryset's iterator() method reduce memory usage?
In Django, I can't understand why queryset's iterator() method reduces memory usage. Django document says like below. A QuerySet typically caches its results internally so that repeated evaluations do not result in additional queries. In contrast, iterator() will read results directly, without doing any caching at the QuerySet level (internally, the default iterator calls iterator() and caches the return value). For a QuerySet which returns a large number of objects that you only need to access once, this can result in better performance and a significant reduction in memory. In my knowledge, however, wheather iterator() method is used or not, after evaluation, the queried rows are fetched from the database at once and loaded into memory. Isn't it the same that memory proportional to the number of rows is used, wheather the queryset do caching or not? Then what is the benifit of using iterator() method, assuming evaluating the queryset only once? Is it because raw data fetched from the database and data that is cached (after instantiating) are stored in separate memory spaces? If so, I think I can understand that not performing caching using the iterator() method saves memory. -
The 'patch' method generating a 500 error when recieving a pk in the URL
I'm sending a PATCH request (naturally) passing a pk and I'm getting a TypeError: patch() got an unexpected keyword argument 'pk' These are the request parameters I'm sending: Request URL: http://localhost:8000/api/task/toggle-done/1/ Request headers: {'Authorization': 'Token 13f2f18ea582e9c585c817ba52358b5b19e696a8', 'Content-Type': 'application/json', 'Content-Length': '0'} Request method: PATCH Request body: None This is the URL Patterns: path('task/toggle-done/<int:pk>/', TaskToggleDoneAPIView.as_view(), name='task_toggle_done'), This is the TaskToggleDoneAPIView implementation class TaskToggleDoneAPIView(generics.UpdateAPIView): http_method_names = ['patch'] authentication_classes = [TokenAuthentication] permission_classes = [permissions.IsAuthenticated,IsObjectOwner] queryset = Task.objects.all() lookup_field = 'pk' serializer_class = TaskSerializer def patch(self, request,): instance = self.get_object() instance.done = not instance.done instance.save() serializer = self.get_serializer(instance) return Response(serializer.data) And this is the error I'm getting gtd-api-1 | Internal Server Error: /api/task/toggle-done/1/ gtd-api-1 | Traceback (most recent call last): gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner gtd-api-1 | response = get_response(request) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response gtd-api-1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view gtd-api-1 | return view_func(*args, **kwargs) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/django/views/generic/base.py", line 70, in view gtd-api-1 | return self.dispatch(request, *args, **kwargs) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch gtd-api-1 | response = self.handle_exception(exc) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception gtd-api-1 | self.raise_uncaught_exception(exc) gtd-api-1 | File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, β¦ -
"NOT NULL constraint failed: stewardship_patientform.cultureReport" even if default is given
I am using Graphene for GraphQL This is my model class PatientForm(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) review_date = models.CharField(max_length=100) review_department = models.CharField(max_length=100) provisional_diagnosis = models.CharField(max_length=200) final_diagnosis = models.CharField(max_length=200) syndromic_diagnosis = models.CharField(max_length=200) diagnosis_choice = models.CharField( max_length=100, choices=DIAGNOSIS_CHOICES, default="null" ) sepsis = models.ForeignKey("Sepsis", blank=True, on_delete=models.CASCADE) focus_of_infection = models.ForeignKey( "FocusOfInfection", blank=True, on_delete=models.CASCADE ) cultureReport = models.BooleanField() culture_report = models.ManyToManyField("CultureReport", blank=True, default=[]) antibiotic_used = models.ManyToManyField("Antibiotic", blank=True ,default=[]) clinical_signs = models.ForeignKey( "ClinicalSign", blank=True, on_delete=models.CASCADE ) def __str__(self): return self.patient.fullName this is what I have written in my mutations try: patientForm = PatientForm.objects.create( patient=patientObject, focus_of_infection=focusOfInfection, sepsis=sepsis, clinical_signs=clinical_signs, # culture_report=[], # antibiotic_used=[], ) patientForm.culture_report.set(culture_reports) patientForm.antibiotic_used.set(antibiotics_used) except Exception as e: print("Error: ", e) raise APIException(message=e, code=400) patientForm.save() here culture_reports and antibiotics_used are list of objects. Now I am facing - "NOT NULL constraint failed: stewardship_patientform.cultureReport" Initally I was facing "Direct assignment to the forward side of a many-to-many set is prohibited. Use culture_report.set() instead." therefore I am using .set(). I have also tried giving "[]" as its previous value, but thats also does not work. -
Django-Login page
views.py def userhomepage(request): usersgmail_id = request.POST.get("user_gmail_id") userspassword = request.POST.get("user_gmail_pas") myslt = User.objects.filter( useremlid__contains=usersgmail_id, userpassword__contains=userspassword ) if myslt != "": return render(request, "UserHome.html") else: return render(request, "mylogin.html") I am making a login page using Django table. When no record match with the table of Django database I get "<QuerySet []>" in the "myslt" variable and when match any record than it displays the record no like "<QuerySet [<User: User object (2)>]>". I want to render "UserHome.html" page when record match with the table of Django. Otherwise render "mylogin.html" page. The problem here is that the above code always opens the "UserHome.html" page. When no record match than it also opens the "UserHome.html" page. I also used if myslt != "<QuerySet []>": in place of if myslt != "": but it has no effect. Is there a way to open "UserHome.html" page when record match and open "mylogin.html" page when no record match. -
How to send emails from django shell with AWS ses?
I have verified my domain with AWS SES and as a result my site successfully does send password verification emails (via allauth). I would, however, also like to be able to send emails based on local scripts. To do this I have been using django shell_plus: from django.core.mail import send_mail send_mail("It works!", "This will get sent through anymail", "me@mysite.com", ["me@mysite.com"]) I get output of '1' suggesting this the email has been sent successfully but I do not receive an email I think my config is correct given that the site does successfully send emails: EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend" ANYMAIL = { "AMAZON_SES_CLIENT_PARAMS": { "aws_access_key_id": AWS_ACCESS_KEY_ID, "aws_secret_access_key": AWS_SECRET_ACCESS_KEY, "region_name": "us-east-1", }, } Can anyone explain what I need to do to send emails from the terminal i.e. without being directly logged into an AWS server? -
Combine models to get cohesive data
Im writing app in witch I store data in separate models. Now I need to combine this data to use it. The problem. I have three models class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=True) ... class Contacts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") contact_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contact_user") class UserPhoto(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.CharField(max_length=220) How can I get the current user contacts with their names and pictures like this (serialized) { { "contact_user":"1", "first_name":"Mark ", "url":first picture that corresponds to contact_user id }, { "contact_user":"2", "first_name":"The Rock", "url":first picture that corresponds to contact_user id } } Now im queering the Contacts model to get all contatcs_user id's that he has connection to class MatchesSerializer(serializers.ModelSerializer): class Meta: model = Contacts fields = '__all__' depth = 1 class ContactViewSet(viewsets.ModelViewSet): serializer_class = ContactsSerializer def get_queryset(self): return Contacts.objects.filter(user__id=self.request.user.id) -
How should I use localization and internationalisation on Django
I'm building a new bible website, using Django. I started with English and now I want to translate it to other languages like Spanish, Hebrew, etc. Here's the issue: The bible has many versions - King James bible, new international bible, etc. Each version can be in a few languages - like English, Spanish, etc. Here's the model I used for the default King James english bible: class verses (models.Model): id = models.IntegerField("ID",primary_key=True) book = models.CharField("Book",max_length=20,default=1) chapter = models.IntegerField("Chapter",default=1) verse = models.IntegerField("Verse",default=1) versetext = models.CharField("Versetext",max_length=550,default=1) title = models.CharField("Title",max_length=100,default=1) summary = models.CharField("Summary",max_length=550,default=1) id: a primary key for each verse book - the name of the book (in English). For example: Genesis chapter: the number of the chapter. For example: 1 verse: the number of the verse. For example: 2 versetext: the verse text. For example: In the beginning God created the heaven and the earth title: the title of the chapter (in English). For example: Creation summary: the summary of the chapter (in English). For example: In chapter 1 God creates the heaven and the earth... I want to achieve two things: A user should see a default language of the website, based on his location. Spain users should see the β¦ -
Does DOMContentLoaded works in Django?
Trying to get my button working. Project is setup on Django, using pure JS. My JS script button.js: document.addEventListener('DOMContentLoaded', () => { const btn = document.getElementById('exchange-button'); console.log("Button: " + btn); // Button: nu;; if (btn) { btn.addEventListener('click', () => { console.log('btn clicked'); }); } else { console.log("Not Working") } }); And usage in html declared in head tag: <div> <button class="exchange-button">Get Exchange rate</button> </div> {% load static %} <script src="{% static 'js/button.js' %}"> </script> When Im checking if button exists, its not, the button is null and gettig same error all the time: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at HTMLDocument. (button.js:5:7) Script is working perfectly when Im using pure html and js in other project. What am I doing wrong? Thanks for help -
Django DRF Djoser - change default User model to custom model which is not equal but inherited from AUTH_USER_MODEL
In django have the following custom user structure: class CinemaUser(AbstractUser): ... class CinemaAdmin(CinemaUser): .... class Cinemagoer(CinemaUser): ... Logic is that I have Cinemagoer - an ordinary user, CinemaAdmin - kind of administrator and superuser. Cinemagoer - can register themselves, CinemaAdmin is created only by superuser in settings: AUTH_USER_MODEL = CinemaUser the problem is with Djoser, a request http://localhost:8000/auth/users/ (with data in body) creates CinemaUser, because Djoser has User = get_user_model(), which means Djoser uses AUTH_USER_MODE, while I need Djoser to use Cinemagoer model to create Cinemagoer). How can I use Cinemagoer with Djoser in this case? I tried to change in Djoser/serializers directly User = CinemaUser ... just for test, it works fine, but it is definitely the wrong way.