Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        How to address N+1 problem in django with prefetch related?With the following code I am getting N numbers of queries based on the loop. How to avoid that ? I tried using prefetch_related but that didn't worked or am i doing the wrong way ? models class Product(models.Model): name = models.CharField() .... class ProdcutOffer(models.Model): product = models.ForeignKey(Product, related_name="offers") .... def my_view(request): qs = Product.objects.filter(is_active=True).prefetch_related("offers") data = [] for product in qs: data.append( { ...., "offer":product.offers.filter(is_active=True, is_archived=False).last() } ) paginator = Paginator(data, 10) try: page_obj = paginator.page(page_num) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj
- 
        Using tests.py file with apps in a root directoryI have a small project with all the apps inside a root directory named apps. Everything works fine, but now I tried to add some tests in the tests.py class CursoModelTests(TestCase): def test_two_identical_slugs(self): curso1 = Curso( nombre='Curso 1', precio=10, descripcion_breve='Hola', slug='prueba', profesor=create_profesor() ) with self.assertRaises(IntegrityError): Curso( nombre='Curso 2', precio=20, descripcion_breve='Otro curso', slug='prueba', profesor=create_profesor() ) And when I run python manage.py test apps I get this error System check identified no issues (0 silenced). E ====================================================================== ERROR: curso.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: curso.tests Traceback (most recent call last): File "C:\Users\Usuario\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\CocinaSalud\apps\curso\tests.py", line 5, in <module> from .models import Curso File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\CocinaSalud\apps\curso\models.py", line 7, in <module> class Curso(BaseModel): File "C:\Users\Usuario\Desktop\Apps creadas\cocina-salud\venv\lib\site-packages\django\db\models\base.py", line 132, in __new__ raise RuntimeError( RuntimeError: Model class curso.models.Curso doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. ---------------------------------------------------------------------- Ran 1 test in 0.000s When I define an app_label in the Meta class this way class Curso(BaseModel): # fields... class Meta: app_label = 'apps.curso' I receive this other error Found 1 test(s). System check identified no issues (0 silenced). E ====================================================================== ERROR: curso.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: …
- 
        Designing a Generic List Manager Library with User Permissions in Django/PythonI'm currently in the process of developing a versatile and reusable Generic List Manager Library for applications built with Django/Python. This library aims to provide a generic solution for creating and managing lists of various entities Here are the key requirements for this generic library: User-List Association: A list should be associated with one or multiple users. User Permissions: Users linked to a list should have different permissions such as read, write, and share rights. Abstract Lists: Lists should be abstract and capable of linking to a single model, with a field defining the primary model it references. Multiple Models: It should be possible for two different lists to point to different models. I am seeking advice on what are some suitable design patterns for doing this. I am thinking of using a combination between Repository Pattern && Mediator Pattern to implement this, but I would love to hear different opinion or takes into this.
- 
        I am unable to update value of lifecycle stage using hubspot apiI am using hubspot api to update the value of lifecycle stage of a contact. The value can be changed to any other value in the hubspot crm. But when I am using the api to do so, I can change the value of the lifecycle stage to a higher stage say, from a Subscriber to Lead, as Subscriber is lower in rank than Lead. But when I try to change the value from Lead to Subscriber using the api, it doesn't do so. There is no error too. I am not sure if it is a bug with the api or there is some restriction to do so. The code for my api: def update_contact_lifecycle_stage(request , *args): try: api_client = HubSpot(access_token=HUBSPOT_API_KEY) #get this from params contact_email = "test@test.com" filter_query = { "propertyName": 'email', "operator": 'EQ', "value": contact_email } filterGroup = { "filters" : [filter_query] } search_request = PublicObjectSearchRequest( filter_groups= [filterGroup], properties=['vid'] ) response = api_client.crm.contacts.search_api.do_search(public_object_search_request=search_request) contacts = response.results if contacts: contact_vid = str(contacts[0].id) #Get this from params new_lifecycle_stage = "subscriber" contact_update = { "lifecyclestage": new_lifecycle_stage } simple_public_object_input = SimplePublicObjectInput( properties=contact_update) try: api_response = api_client.crm.contacts.basic_api.update( contact_vid, simple_public_object_input=simple_public_object_input ) except ApiException as e: print(f"HubSpot API error: {e}") except Exception as e: …
- 
        I cannot get my site to show on a reverse proxy NginX serverI am trying to deploy a Django website on a VPS and I have everything set up in terms of the following: The app runs if I use the development server and I go to xxx.xxx.xxx.xxx:8000 Nginx is running because if I go to the site at founderslooking.com I can see the nginx server page. I am following the instructions from a video as this is my first time doing it and I have set up supervisor. I have the following conf file set up so I can use nginx as a reverse proxy but clearly this is not working because I do not see my site. I checked and supervisor is running. /etc/nginx/sites-available/founders.conf: upstream founders_app_server { server unix:/websapps/founders/founders_3_10_12/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name api.founderslooking.com; client_max_body_size 4G; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename){ proxy_pass http://founders_app_server; } } } If I change the server name to founderslooking.com then I get a bad gateway if I go to founderslooking.com /etc/supervisor/conf.d/founders.conf: [program:founders] command = /webapps/founders/founders_3_10_12/bin/gunicorn_start user = userfounders stdout_logfile = /webapps/founders/founders_3_10_12/logs/supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 Not sure what else to include here but I checked and nginx is running, supervisor is running and …
- 
        Django Permission per Database ObjectI have an architectural question regarding Djangos permission model. I do have a Database Model which hold companies, and each company can have multiple projects. Users should be able to only see companies that they are assigned to and only see projects which they are assigned to. I am now confused whether I should have a Many2Many Relation in the companies and projects which holds the allowed users and then check them on access through the permission system? Or create a new permission for each company, add this permission to the company and/or project and then give the users these permissions? Somehow I think solution 1. gets me into problems in the long run when querying all projects one user should see. But solutions 2 got me stuck since there is no permission field in the models, so I always have to cast string field to permission and I will generate a huge amount of permissions overall. Maybe I am completely overthinking this? What would be the best approach to per Database-Entry permissions? Thanks and Best Regards
- 
        Django-admin: how to make save_formset() work once with a few inlines?My admin.py: class PollMediaInline(admin.StackedInline): model = PollMedia extra = 1 # Количество дополнительных полей для добавления readonly_fields = ('absolute_media_path',) class PollOptionsInline(admin.StackedInline): model = PollOptions extra = 1 # Количество дополнительных полей для добавления @admin.register(Poll) class BotUserAdmin(admin.ModelAdmin): list_display = ('id', 'user', 'title', 'group', 'approved', 'created_at') list_filter = ('created_at', 'approved', 'group') search_fields = ('title', 'approved') ordering = ('approved',) readonly_fields=('user',) inlines = [PollOptionsInline, PollMediaInline] def save_model(self, request, obj, form, change): pass # don't actually save the parent instance def save_formset(self, request, form, formset, change): formset.save() # this will save the children form.instance.save() # form.instance is the parent signals.py: @receiver(post_save, sender=Poll) def post_without_media_created(sender, created, instance, **kwargs): send_poll_sync = async_to_sync(send_poll) print(", ".join([option.option for option in instance.options.all()]), instance.title, ", ".join([media.absolute_media_path for media in instance.mediafiles.all()]), sep='\n') send_poll_sync([option.option for option in instance.options.all()], instance.title, [media.absolute_media_path for media in instance.mediafiles.all()]) models.py: class Poll(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Менеджер') scheduled_time = models.DateTimeField(blank=True, null=True, verbose_name="Дата и время рассылки") title = models.CharField(max_length=200, verbose_name='Заголовок') # options = models.TextField(verbose_name='Варианты ответа') # correct_answer = models.PositiveIntegerField(blank=True, null=True, verbose_name='Правильный ответ(если пусто, то без правильных ответов)') approved = models.BooleanField(default=False, verbose_name='Подтверждён') # total_media_count = models.PositiveIntegerField(default=0, verbose_name='Сколько фотографий загрузите?') group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Группа пользователей бота') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True, verbose_name='Создано') def save(self, *args, **kwargs): if …
- 
        Django cannot send email with gmail smtp using Docker, working without dockerI developed a Django app that sends verification code via email. When I run the code locally using like PyCharm my code works and emails are being sent. Then I wanted to contenerize my application using Docker. I did, but everything works beside the sending email. I get the following error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1002) when executing email.send(). I use private network at home. Port 587 is not blocked. This is my DockerFile FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update \ && apt-get -y install libpq-dev gcc \ && pip install psycopg2 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy main.sh COPY ./main.sh . RUN sed -i 's/\r$//g' /usr/src/app/main.sh RUN chmod +x /usr/src/app/main.sh # copy project COPY . . # run main.sh ENTRYPOINT ["/usr/src/app/main.sh"] This is the docker-compose.yml version: '3.9' services: backend: build: context: ./backend command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 - 587:587 volumes: - ./backend/:/usr/src/app/ environment: - DB_NAME=db_name - DB_USER=db_user - DB_PASSWORD=db_pass - DB_HOST=db - DB_PORT=5432 - EMAIL_USE_TLS=True - EMAIL_FROM=email@gmail.com - …
- 
        Django model datetime filter ( model.objects.filter(datetime_field__lt=datetime.now()) ) is not workI try to filter my data model in model view.py with a datetime field. But it filter total data records and none of data is in result! And how to filter datetime fields with 'None' value? Please help me to resolve this issue problem. which part of model data filed definition is: class Post(models.Model): title = models.CharField(max_length=200,verbose_name="Título") content = models.TextField() counted_views = models.IntegerField(default=0) published_date = models.DateTimeField(blank=True, null=True) ... my command statement: posts = Post.objects.filter(published_date__lt=datetime.now())
- 
        Nginx, ReactJS with Django ArchitectureI'm new to this technology. Can anyone explain how the Architecture works ?. Where the user request will hit first, to Nginx or React or Django. How to implement a great Architecture ?. What are the good APIs use in between for better performance.
- 
        python manage.py startapp item doesn't work for meI saw this command work in my django video courses but unfortunately it doesn't work for me when I enter python manage.py startapp item it returns an error which says : File "D:\Django\puddle\manage.py", line 22, in <module> main() File "D:\Django\puddle\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\Django\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Django\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Django\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\Msk\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'item' I just tried to install this app to learn the rest of the Django course but it says the item module not found!
- 
        How to avoid client caches (Chrome) on django react app?I have a django-react app that is serving out of Heroku. I use webpack to build static files, which I serve out of a Django app called frontend. Django static files serving adds a hash to the webpack generated files for cache breaking on new releases. To illustrate, here is the index.html that is served for my site: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/static/favicon.e62ca627caf.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <link rel="stylesheet" type="text/css" href="/static/frontend/css/index.e861872e9ba7b.css"/> <link rel="manifest" href="/static/manifest.a22d2aecab21fe.json" /> </head> <body> <div id="root"></div> <script src="/static/frontend/js/index.a39c981a0accf.js"></script> </body> </html> Cache-Control for index.html is set to max-age=0. I thought this setup would be good enough for breaking client caches when I release a new frontend version of my site (since index.*.js would have a new hash). However, I observed that some of my clients had stale versions up to two weeks ago even with this setup (using Chrome on Windows). How is this possible? Am I missing something to break client caches for new frontend releases?
- 
        Django and tensorflow app deployed with herokuI am sorta new to django and heroku and but I made a django app which intakes user values, processes them through a tensorflow model which was trained and loaded by doing: enter image description here Locally, my app works just fine but now I am trying to deploy it using heroku and I am finding lots of trouble. My main issue is when I run 'git push heroku main' this is what I get: enter image description here I have tried changing my python versions even using different tensorflow versions as well. I am currently in python-3.11.6 but I have tried running this with python-3.10.13 and python-3.9.18. If anyone can help that would be appreciated. Thank you for your time.
- 
        Django with html chartjs"I use Django to create a web app with HTML, and I want to change the format of numbers in the graph from 123456.123456 to 123,456.12. I've tried using floatformat:'2g' or .toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), but the values in each point are separated by commas, like [1123,2212]. The expected result should be like 1,123 and 2,212 as usual, but in the graph, I get: Point 1: 1 Point 2: 123 Point 3: 2 Point 4: 212 Please help." my code : new Chart(chartLineCanvas, { type: 'line', data: { labels: labels, datasets: [ { label: 'Total Sales (Baht)', borderColor: 'rgba(0, 0, 255, 1)', backgroundColor: 'rgba(0, 0, 255, 0.2)', data: data }, { label: 'Average Sales Present (Baht)', borderColor: 'rgba(255, 165, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(data.length).fill(data.reduce((a, b) => a + b, 0) / data.length), }, { label: 'Average Sales Before(Baht)', borderColor: 'rgba(255, 0, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(averagedata.length).fill(averagedata.reduce((a, b) => a + b, 0) / averagedata.length), }, ], }, options: { mode: 'index', bodyFontSize: 20, locale: 'en-US', tooltips: { callbacks: { label: function (tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || ''; var value = tooltipItem.yLabel; return datasetLabel + ': ' + value.toLocaleString('en-US', { style: 'decimal', …
- 
        Problems with django testing?I am developing a django app and currently testing it as well, this is my view: from django.http import JsonResponse, HttpResponseBadRequest from store.models import Product from .basket import Basket # Create your views here. def basket_summary(request): basket = Basket(request) return render(request, "store/basket/summary.html", {"basket": basket}) def basket_add(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) product = get_object_or_404(Product, id=product_id) basket.add(product=product, product_qty=product_qty) basket_qty = basket.__len__() response = JsonResponse({"qty": basket_qty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) basket.delete(product_id=product_id) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response def basket_update(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) basket.update(product_id=product_id, product_qty=product_qty) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response My urls.py file is also below: from .views import basket_summary, basket_add, basket_delete, basket_update app_name = "store_basket" urlpatterns = [ path("", basket_summary, name="basket_summary"), path("add/", basket_add, name="basket_add"), path("delete/", basket_delete, name="basket_delete"), path("update/", basket_update, name="basket_update"), ] Finally my testing file: from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from store.models import Category, Product from json import loads class TestBasketView(TestCase): def setUp(self): category = Category.objects.create(name="django", slug="django") user = User.objects.create(username="admin") …
- 
        format datetimeinput in djangoI have a booking site and I want the booking to be permanent only by hours (I don't want minutes) an example of John booked from 8 to 10 o'clock And I don't want 8:10 to 10: 30 pm Can I remove the minutes from DateTimeInput format that the user cannot choose them and selects only the hour look at the picture here enter image description here Or any other way to do this
- 
        Docker Compose - could not translate host name "database" to address: Name or service not knownWhen i run docker-compose up it gives me this error. Im using Django and React to build the application, as listening with gunicorn for server. I know i dont need to create a network because compose do this byself, but i tryed everything i found and nothing solved my problem, any sugestions? django.db.utils.OperationalError: could not translate host name "database" to address: Name or service not known failed to solve: process "/bin/sh -c python manage.py migrate" did not complete successfully: exit code: 1 Dockerfile FROM python:3.9.13 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi docker-compose.yaml version: "3" services: database: container_name: database networks: - djangonetwork image: postgres:12.7-alpine expose: - "5432" volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=dockerteste - POSTGRES_USER=postgres - POSTGRES_PASSWORD=pw1234 backend: build: ./finapp volumes: - ./finapp:/app depends_on: - database networks: - djangonetwork frontend: build: ./frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx ports: - 8000:8000 depends_on: - backend networks: djangonetwork: driver: bridge
- 
        How to pass a list of dates from Django ORM to a javascript date list to use as labels in chart.jsI'm trying to plot some charts comparing the close price of pairs of stocks in a timeline. My Django view.py function looks like this: # Access stock pairs for the user settings stock_pairs = StockPair.objects.filter(setting=setting) # Create a context dictionary including, for each stock_pair in stock_pairs, the close prices of the stocks in the pair and pass the dictionary to the template context = {} stocks_and_pair_data_list = [] for stock_pair in stock_pairs: stocks_and_pair_data = {} stocks_and_pair_data['stock1_name'] = stock_pair.stock1.name stocks_and_pair_data['stock2_name'] = stock_pair.stock2.name stocks_and_pair_data['dates'] = [dt for dt in stock_pair.stock_pair_data_set.values_list('date', flat=True)] stocks_and_pair_data['stock1_close_prices'] = [float(close) for close in stock_pair.stock1.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data['stock2_close_prices'] = [float(close) for close in stock_pair.stock2.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data_list.append(stocks_and_pair_data) context['stocks_and_pair_data_list'] = stocks_and_pair_data_list return render(request, 'my_page.html', context) and my_page.html has this script section: <!-- For each stocks_and_pair_data in stocks_and_pair_data_list create, using chart.js, a chart of the close prices of stock1 and stock2 --> {% for stocks_and_pair_data in stocks_and_pair_data_list %} <script> const ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', data: { labels: '{{stocks_and_pair_data.dates}}', datasets: [{ label: '{{ stocks_and_pair_data.stock1_name }}', data: '{{stocks_and_pair_data.stock1_close_prices}}' },{ label: '{{ stocks_and_pair_data.stock2_name }}', data: '{{stocks_and_pair_data.stock2_close_prices}}' }] } }); </script> {% endfor %} I'm having 2 problems. The first problem is that I get the following error on the browser …
- 
        Why is my Django view not automatically downloading a fileMy view transcribes a file and outputs the SRT transcript. Then it locates and is supposed to auto download theT transcript but nothing happens after transcription completes(the file was submitted on a previous page that uses the transcribeSubmit view. The view that handles and returns the file is the initiate_transcription view). Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def transcribe_file(path): #transcription logic JS: const form = document.querySelector('form'); form.addEventListener('submit', function (event) { event.preventDefault(); const formData = …
- 
        Cannot for the life of me figure out how to get form post to work?I have an app called search. Here is urls.py from django.urls import path from . import views app_name = "search" urlpatterns = [ path("", views.UsersView.as_view(), name="all_users"), ] Here is models.py from django.db import models class User(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() email = models.EmailField() Here is forms.py from django import forms class UserForm(forms.Form): name = forms.CharField(label="Name", max_length=100) age = forms.IntegerField(label="Age") email = forms.EmailField(label="Email") Here is views.py from django.views import View from search.forms import UserForm from .models import User class UsersView(View): def get(self, request): try: user_list = User.objects.order_by("-name") form = UserForm() except User.DoesNotExist: raise Http404("Users do not exist") return render(request, "search/index.html", {"user_list": user_list, "form": form}) def post(self, request): try: form = UserForm(request.POST) if form.is_valid(): newUser = User(name=request.POST["name"], age=request.POST["age"], email=request.POST["email"]) newUser.save() except: raise Http404("Error when trying to add new user") return redirect('/') And lastly, here is index.html {% if user_list %} <h1>Here are all the users</h1> <ul> {% for user in user_list %} <li><a href="/search/{{ user.id }}/">{{ user.name }}</a></li> {% endfor %} </ul> <h1>Add a user</h1> <form action="/search/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% else %} <p>No users are available.</p> {% endif %} The form displays just fine for me, but when I enter in …
- 
        I can't get my homepage returning httpresponse what could be the issue?from django.shortcuts import render, HttpResponse Create your views here. def home(request): return HttpResponse('Welcome to Location Intelligence Kenya!') Whenever i run the my server i get the output below i can't seem to locate where the problem is
- 
        Django - inconsistent password hashingTrying to build the user manager boilerplate of a Django (DRF) project. Facing some really weird issues when registering a user. First problem I encountered was passwords not being hashed. After some investigation I found out that the auth package has make_password function, which generates a hash from a given string. But then I noticed that I cannot authenticate these users. Tried to setup my own authentication logic using the check_password of the same package, when I realized, that the password hash stored in the database is completely different from the hash generated by make_password and passed to the set_password method of the user instance. I know I should provide some code, but the computer running the code doesn't have internet access (my wi-fi adapter has died) , but the structure of the user manager, view and serializer is almost same as here: https://github.com/dotja/authentication_app_react_django_rest/tree/main/backend I do use user.save() after setting up the password. I need to figure out either why the user's password not getting hashed without using the make_password function, or why the stored hash is different when using the make_password function. Thanks.
- 
        Django - data from form (ModelForm) do not save in existing databaseIm trying to send via form data to my database as new object of my Task model. When I click submit button it only redirects me to my other page, nothing happens with submitted data and data is not saved to my db. I looked for solution in multiple sources but didn't find one. I am begginer with this topic so every feedback would be great. My questions: Where I made mistake If i have prepopulated slug field in my admin.py (from title field) will it be prepopulated in forms when i exclude my slug field? 3.I would appreciate for useful knowledge sources. model.py class Task(models.Model): is_done = models.BooleanField(default=False) title = models.CharField(max_length=100) add_time = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") slug = models.SlugField() description = models.TextField() forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): class Meta: model = Task exclude = ["add_time", "is_done"] template <form method="post" class="form" action="{% url 'add-task' %}"> {% csrf_token %} <p>Title: {{ form.title }}</p> <p>Deadline: {{ form.deadline }}</p> <p>User: {{ form.user }}</p> <p>Description: {{ form.description }}</p> <button type="submit">Submit</button> </form> views.py def add_task(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/todolist") form = TaskForm() return render(request, "todolist/add_task.html", …
- 
        Django generating python fileI am building site in django and I have table with data: <th>name</th> <th>data</th> data is necessary in my client-side python program sender.py. User double click on specific row and using pyinstaller compile it with data which user selected stored as const in python program and then download it. I manage to make JS script witch shows what row you selected, but I cant figure out how to insert data into python program, use run pyinstaller on that file and then download it. Python program have function which takes that data but is not necessary Python: from somelib import func constData = data def clientFunc(constData): if constData != None or len(constData) <= 0: print("Argument constData is valid") else: constData = str(constData) client = func(constData, 9999) client.func2() or from somelib import func constData = data if constData != None or len(constData) <= 0: print("Argument constData is valid") else: constData = str(constData) client = func(constData, 9999) client.func2() JS: const table = document.getElementById('table'); const rows = table.getElementsByTagName('tr'); Array.from(rows).forEach((row, index) => { row.addEventListener('dblclick', () => { const cells = row.getElementsByTagName('td'); console.log(cells[0]); console.log(cells[1]); const content1 = cells[0].innerHTML; alert(content1) }); }); I will be grateful for at least one of these things. Cheers!
- 
        NextJS and Django Project DeployDoes anyone know how to deploy the django+nextJs app currently, my frontend is running on localhost:3000 and Django at 127.0.1:8000 and its is working perfectly on my local machine I want to deploy it on a live server anyone who knows how to do this I have deployed the next app on Vercel (https://cropsight-dusky.vercel.app/) but it will not move further from login unless Django is also running simultaneously. I have checked it If the nextJs project is running on Vercel and my Django is running locally then the request from front end will come to me