Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker on windows8.1 can't run Django
cmd: Successfully built c16b1b66eff5 Successfully tagged django_docker_with_postgresql_web:latest Recreating django_docker_with_postgresql_web_1 ... done Recreating django_docker_with_postgresql_db_1 ... done Attaching to django_docker_with_postgresql_db_1, django_docker_with_postgresql_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2022-06-26 14:22:42.826 UTC [1] LOG: starting PostgreSQL 14.3 (Debian 14.3-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit db_1 | 2022-06-26 14:22:42.828 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2022-06-26 14:22:42.830 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2022-06-26 14:22:42.834 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2022-06-26 14:22:42.843 UTC [24] LOG: database system was shut down at 2022-06-26 14:18:52 UTC web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | web_1 | You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. web_1 | Run 'python manage.py migrate' to apply them. web_1 | June 26, 2022 - 14:22:46 ''' Blockquote docker-compose.yml version: '3.3' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 db: … -
Django override django.contrib.auth login process
views.py from django.contrib import messages from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.contrib.auth.views import LoginView from django.shortcuts import render def index(request): return render(request, 'index.html') def templates(request): return render(request, 'templates.html') def information(request): return render(request, 'information.html') def custom_login(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username = username, password = password) print("work") if user is not None: messages.success(request, 'Success') login(request, user) return HttpResponse('login') #logout(request) else: messages.error(request, 'Invalid username or password') print("error") return HttpResponse('wrong username or password') class CustomLoginView(LoginView): print("check") def form_valid(self): custom_login(self.request) urls.py from django.contrib import admin from django.urls import path, include from ArtisticCode import views urlpatterns = [ path('admin/', admin.site.urls), path('accounts/login/', views.CustomLoginView.as_view(), name='login'), path('accounts/', include('django.contrib.auth.urls')), path('', views.index, name = 'index'), path('templates/', views.templates, name = 'templates'), path('information/', views.information, name = 'information'), ] accounts/login.html <form method="post" class="login"> {% csrf_token %} <div class="login_input"> <img src="{% static 'img/bx_img1.png' %}" alt="image"/> <input type="text" placeholder="Username" name="username" required/> </div> <div class="login_input"> <img src="{% static 'img/bx_img1.png' %}" alt="image"/> <input type="password" placeholder="Password" name="password" required/> </div> <input type="submit" value="Send message"/> {% if messages %} {% for message in messages %} <strong style="color:white;">{{ message }}</strong> {% endfor %} {% endif %} </form> The idea is to display a message in case of a wrong password, but … -
Template - Parent Detailview w/ child for loop list
I've been trying solutions that have been suggested for others in similar situations, however almost all questions are regarding bizzarely unusual scenarios and I've been unable to adapt them to my situation. I'd like a for loop of child information in a parent's DetailView Models class Projects(models.Model): fk_user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.BooleanField(default=False) class Projects_items(models.Model): itemName = models.BooleanField(default=False) fk_project = models.ForeignKey(Projects,on_delete=models.CASCADE, related_name="item") value = models.FloatField() Views class projects(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Projects fields = [ 'name', ] template_name = 'games/project_details.html' context_object_name = 'projects' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False Template - projects_details {% extends './underlay.html' %} {% load static %} {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'details.css' %}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins"> {% block content %} <H2>LIST OF ITEMS BELONGING TO THIS PROJECT</H2> ? SOMETHING LIKE: {% for projects.item in projects %} {{ projects.item.itemName }} - {{ projects.item.value }} {% endfor %} THIS GAVE AN ERROR OF 'PROJECTS' OBJECT NOT ITERABLE -
Saving related model objects in single view
I need some help from you folks! I am beginner and I am working on Django project - risk assessment application. I have a trouble to achieve saving on related objects for my application risk record. I am using MultiModelForm to achieve the following. I am successfully creating Whatif instance and connecting it with GuideWordi instance on save, however, I am not able to connect my RiskRecordi instance with GuideWordi instance, but RiskRecordi instance is saved into the db (I see it through admin). I tried lot's of research over the web, but confused now. My models.py: class WhatIf(models.Model): moc_no = models.CharField(max_length=12, blank=True) ra_scope = models.TextField(max_length=128, blank=True) facilitator = models.ForeignKey(User, related_name='facilitator', null=False, on_delete=models.SET_DEFAULT, default='0') def __str__(self): return self.moc_no def get_absolute_url(self): return reverse('whatif:whatif_form', kwargs={'pk': self.pk}) class GuideWordi(models.Model): whatif = models.ForeignKey(WhatIf, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=160, blank=True) def __str__(self): return self.name class RiskRecordi(models.Model): guidewordi = models.ForeignKey(GuideWordi, blank=True, null=True, on_delete=models.CASCADE) cause = models.TextField(max_length=128, blank=True) consequence = models.TextField(max_length=128, blank=True) safeguard = models.TextField(max_length=128, blank=True) My views.py class WhatIfCreateView(CreateView): Model = WhatIf form_class = WhatIfForm template_name = 'whatif/ra-initiate.html' def form_valid(self, form): obj = form.save(commit=False) obj.facilitator = self.request.user return super().form_valid(form) from multi_form_view import MultiModelFormView class RiskRecordView(MultiModelFormView): form_classes = { 'guideword_form' : GuideWordiForm, 'riskrecord_form' : RiskRecordiForm,} template_name = … -
Django squashmigrations: How to rollback effects of squashmigrations command?
I have squashed migrations and it created a new migration files by squashing all the migrations of the app. Due to some post squashmigrations issue I want to undo the effects of squashmigrations command. The problem is that now migrate command is not working because Django is not able to detect the presence of old migrations file that are squashed into a new migrations file. Example: Let's say all the four migrations from 0001 to 0004 are applied and then I squash them by running the following command. $ ./manage.py squashmigrations myapp 0004 Will squash the following migrations: - 0001_initial - 0002_some_change - 0003_another_change - 0004_undo_something Do you wish to proceed? [yN] y Optimizing... Optimized from 12 operations to 7 operations. Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py You should commit this migration but leave the old ones in place; the new migration will be used for new installs. Once you are sure all instances of the codebase have applied the migrations you squashed, you can delete them. Now if I try to run the following command to rollback to previous state: python manage.py migrate myapp 0004 It throws an error saying CommandError: Cannot find a migration matching'myapp/migrations/0004_undo_something.py' from app 'myapp' -
Bootstrap dropdown list won't work in django html template
I just was trying to apply bootstrap in my shared html file in a Django project and the dropdown list just won't work I tried everything I could cdn local bootstrap and when I click the dropdown list nothing happens. that's my template script: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <title> {% block title %}{% endblock %} </title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'upload'%}">Upload</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ms-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ms-2"> Sign up</a> </form> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock content %} </div> <script src="{% static 'js/bootstrap.bundle.js'%}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> … -
In datatables, how can we show headers while loading, and then when data loads, show all the datatable?
I am running a django project in which I have a html page to render where I am displaying some data in tabular format using datatables. I am getting that data for the table from api, so it takes time of about 1 or 2 seconds. During this loading time I am using a spinner. But I want the table headers and the filters and search tab that comes with datatables to be displayed while those 2 seconds of loading time, and when the data is ready, complete datatable will be displayed. How can I do that? Thanks in advance. -
Deploy Django project on ubuntu
I have a Django project with written Dockerfile and docker-compose.yml. Projects works as expected on localhost and I want to deploy it to already created ubuntu machine. I tried to manage that with Ansible but haven't succeeded. I use postgresql to store data my docker file # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ CMD python manage.py runserver 0.0.0.0:80 docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:80 volumes: - .:/code ports: - "80:80" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db -
How can from the sum of invested amount and deposit amount using Django
I am trying to withdraw some amount from my investment using the line of code below but its not working. investment.basic_investment_return -= investment.basic_withdraw_amount Model from django.db import models class Investment(models.Model): basic_deposit_amount = models.IntegerField(default=0, null=True) basic_interest = models.IntegerField(default=0, null=True) basic_investment_return = models.IntegerField(default=0, null=True) basic_withdraw_amount = models.IntegerField(default=0, null=True, blank=True) basic_balance = models.IntegerField(default=0, null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True, null=True) Forms from django import forms from .models import Investment class BasicInvestmentForm(forms.ModelForm): class Meta: model = Investment fields = ['basic_deposit_amount'] class BasicWithdrawalForm(forms.ModelForm): class Meta: model = Investment fields = ['basic_withdraw_amount'] Views from django.shortcuts import get_object_or_404, redirect, render from django.db.models import Sum, F from django.contrib import messages from .forms import BasicInvestmentForm, BasicWithdrawalForm, from .models import Investment, def create_investment_view(request): if request.method == 'POST': basic_investment_form = BasicInvestmentForm(request.POST) if basic_investment_form.is_valid(): investment = basic_investment_form.save(commit=False) investment.basic_investment_return += investment.basic_deposit_amount print(investment.basic_investment_return) investment.is_active = True investment.save() messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount)) else: messages.success(request, 'your investment is not successfull! Try again.') else: basic_investment_form = BasicInvestmentForm() context = {'basic_investment_form': basic_investment_form} return render(request, 'create-basic-investment.html', context) def create_withdrawal_view(request): if request.method == 'POST': basic_withdraw_form = BasicWithdrawalForm(request.POST) if basic_withdraw_form.is_valid(): investment = basic_withdraw_form.save(commit=False) investment.basic_investment_return -= investment.basic_withdraw_amount print(investment.basic_investment_return) investment.save() messages.success(request, 'your withdrawal of {} is successfull '.format(investment.basic_withdraw_amount)) else: messages.success(request, 'your … -
Generate same Django Token Docker
I wanted to know if there was any way to always generate the same token for a user. I currently use the following command in building a docker image but it always generates a different token which makes the services are connected through the token, stop working. python3 manage.py drf_create_token root Is there any way to always generate the same token or some other method to achieve something similar? Thank you very much and sorry for the ignorance xd -
Django channels - not connection to ws
I'm making an example from the documentation Django channels and it works great! I see in the logs HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:43164] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:43168] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:43168] however I can't connect with the client andrey@andrey-desktop:~$ wscat -c "ws://127.0.0.1:8000/ws/chat/lobby/" error: Unexpected server response: 403 or postman postman disconnect I see in the logs on unsuccessful attempts WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:43232] WebSocket REJECT /ws/chat/lobby/ [127.0.0.1:43232] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:43232] How do I make connectivity from other clients, not just from the javascript/html page? -
Django query from paypalipn table
I have connected my django-paypal and I have managed to make payments but it seems I can make queries from paypal_ipn table or I'm making mistakes somewhere. The below are the currect snippets of what I have done. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN #On here I'm trying to query serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) The below is something that I intend to get. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN.objects.filter(invoice=postedRef).first() #Something like this serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) -
Unable to change position of previous and next button and background color of carousel slide
Can't change positions of the prev and next buttons and not only that but also the background color of carousel slidebar of also unable to changed. i tried from inspecting it but can't save changes in inspect and not by entering code of those buttons. {% extends 'shop/basic.html' %} {% block css %} .carousel-indicators [data-bs-target] { background-color: #0d6efd; } .col-md-3 { display: inline-block; margin-left: -4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 170px; height: 200px; } body .carousel-indicator li{ background-color: blue; } body .carousel-indicators{ bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon{ background-color: blue; } .carousel-control-prev, .carousel-control-next{ bottom: auto; top: auto; padding-top: 222px; } body .no-padding{ padding-left: 0; padding-right: 0; } {% endblock %} From here I given id and names to the particular code above mentioned {% block body %} {%load static%} <div class="container"> {% for product,range,nSlide in allprods %} <h5 class="my-4"> {{product.0.category}} </h5> <div id="row"> <div id="demo{{forloop.counter}}" class="carousel slide my-3" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#demo{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> {% for i in range%} <button type="button" data-bs-target="#demo{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} </div> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" … -
Username and password are always incorrect in my django AuthenticationForm
I'm trying to login user by his username and password, but when i'm trying to check form.is_valid(), it returns False. Errorlist contain error: "Please enter a correct username and password. Note that both fields may be case-sensitive.". When i don't specify my own post it's doesn't work either. I was looking for typo, but didn't found any. In internet nothing helped me at all. I tried switch form and it's fields, but error was the same. views.py from django.views.generic import * from django.views.generic import * from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login, logout ... class RegisterView(CreateView): form_class = UserRegisterForm success_url = reverse_lazy('main:homepage') template_name = "accounts/register.html" def post(self, request): form = self.get_form() if form.is_valid(): user = form.save() login(request, user) return redirect("main:homepage") else: print(form.errors) return redirect("accounts:register") class LoginView(FormView): form_class = AuthenticationForm template_name = "accounts/login.html" def post(self, request): form = self.get_form() if form.is_valid(): form.clean() user = authenticate( request, username=form.cleaned_data["username"], password=form.cleaned_data["password"], ) login(request, user) return redirect("main:homepage") else: print(form.errors) print(form.cleaned_data) return redirect("accounts:login") forms.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = get_user_model() fields = ['username', 'email', 'first_name'] def save(self): self.clean() user = self.Meta.model( username = self.cleaned_data['username'], email … -
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a'
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a' Code val1 = float(request.GET['a']) -
Correct way to consume 3rd party API with query in Django + React (Backend + Frontend)
I'm using Django on my backend and React on my frontend. I want to consume the OpenWeatherMap API. For security reasons, I want to keep my API key on the backend. Currently, I have this working on my Django app. When a POST request is made, the Django view renders the information required from OpenWeatherMap. How can the user type the query in React, send the query to to the backend and get the results on the frontend? I have a very hacky way of doing this currently: I POST (using axios) the city that the user enters in React to a REST API that I built in Django. The backend queries the OpenWeatherMap API with the city that the user enters and POSTs the data that it gets from OpenWeatherMaps back to my API. After this, the frontend uses a GET request on my API to show the information to the user. I'm pretty sure this isn't the correct way to do this but I couldn't find any other questions on this, and I'm pretty new to web development. -
Rendering custom html templates in Django
I am not an expert in Django, but this software is written in Django using the rest framework, and I need to make customizations to it: https://github.com/openvinotoolkit/cvat/tree/develop/cvat I need to render a custom html template, and this is what I've done so far. I created a new folder in apps called custom with these files: cvat/apps/custom/templates/custom/<name>.html (there are various html templates in custom with different "names". i.e. a.html, b.html, c.html, etc.) Other files in cvat/apps/custom: cvat/apps/custom/__init_.py cvat/apps/custom/apps.py from django.apps import AppConfig class CustomConfig(AppConfig): name = 'cvat.apps.custom' cvat/apps/custom/urls.py from django.urls import path from . import views urlpatterns = [ path('custom/<str:name>', views.CustomView), ] cvat/apps/custom/views.py from django.shortcuts import render def CustomView(request, name): return render(request, 'custom/'+name+'.html') In addition, I have modified these existing files to add the custom folder that was created in apps: https://github.com/openvinotoolkit/cvat/blob/develop/cvat/urls.py#L27 added path('custom/', include('cvat.apps.custom.urls')),: urlpatterns = [ path('admin/', admin.site.urls), path('custom/', include('cvat.apps.custom.urls')), path('', include('cvat.apps.engine.urls')), path('django-rq/', include('django_rq.urls')), ] https://github.com/openvinotoolkit/cvat/blob/develop/cvat/settings/base.py#L129 INSTALLED_APPS = [ ... 'cvat.apps.custom' ] However, when I go to http://localhost:8080/custom/custom/a I get redirected back to another page - not a.html Any advice on what I'm doing wrong? -
Django Rosetta and i18n not working with some ids in Javascript
I have a proyect with Django and I want to translate it to Spanish, English and Italian. Everything working correctly in html files, but I have a file in .js that not working correctly. There are ids that have been translated and there are ids that haven't been translated. This file, is in the folder static and its called from .html file <script src="{% url 'javascript-catalog' %}"></script> <script type="text/javascript" src="{% static 'services_steps/file.js' %}"></script> In file.js I have all ids in variables: var whatever1 = gettext("filejs_whatever1") var whatever2 = gettext("filejs_whatever2") var whatever3 = gettext("filejs_whatever3") Url.py path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^i18n/', include('django.conf.urls.i18n')), if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += [ re_path(r'^rosetta/', include('rosetta.urls')) ] And files.po get all ids (services_steps/locale) ... #: file.js:70 msgid "filejs_whatever0" msgstr "Whatever 0" #: file.js:71 msgid "filejs_whatever1" msgstr "Whatever 1" #: file.js:72 msgid "filejs_whatever2" msgstr "Whatever 2" The commands are, in static (services_steps) folder: django-admin makemessages -d djangojs -l en_GB django-admin makemessages -d djangojs -l es_ES django-admin makemessages -d djangojs -l it_IT And in root directory django-admin compilemessages -
Django Channels: Send message from outside Consumer Class
I'm new in Python and Django, Currently, I need to setup a WebSocket server using Channels. I follow the code in this link: Send message using Django Channels from outside Consumer class setting.py ASGI_APPLICATION = 'myapp.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } Here is the code Consumer import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ZzConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) print("DISCONNECED CODE: ",code) def receive(self, text_data=None, bytes_data=None): print(" MESSAGE RECEIVED") data = json.loads(text_data) message = data['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": 'chat_message', "message": message } ) def chat_message(self, event): print("EVENT TRIGERED") # Receive message from room group message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'type': 'chat', 'message': message })) And outside the Consumer: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'test', { 'type': 'chat_message', 'message': "event_trigered_from_views" } ) The expected logics is I can received the data from the group_send in the receive on the Consumer class. So that I can send message to client. However, It's not. Can anyone here know what's I missing? Any help is very appreciated. Thanks! -
How to load a static file in django v4.0.5?
I was trying to load a static file i.e my CSS in django and i am doing evrything taught in tutorial but it isn't happening. i have my CSS inside static folder. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> <title> Django </title> </head> <body> <header> <div> <nav id="a1"> <a href="{% url 'home'%}" class="a">Home</a> <a href="{% url 'about'%}" class="a">About</a> <a href="{% url 'contact'%}" class="a">Contact</a> <a href="{% url 'courses'%}" class="a">Courses</a> </nav> </div> </header> Here, is my settings.py file as i was following tutorial, settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIR=[ BASE_DIR,"static" ] -
How use a different language with Django?
Is it possible to customise every error message in Django? I am using a language that does not seem to be supported by Django so the translation method won't work. Also, I prefer to write my own error messages. If I have to manually change everything, is there somewhere I can see all the error messages and where they're used in Django? For example, all the error messages associated with a form or a field, such as unique, min_length, etc. -
zipped data shown in view but not in templete
row1 = [] row2 = [] categories= Kategoriler.objects.all().filter(parent_id__isnull=True).order_by('id') for x in categories: row1.append(x.title) row2.append(Kategoriler.objects.all().filter(parent_id=x.id).order_by('title')) zipped = itertools.zip_longest(row1, row2) for u, y in zipped: print(">>>>>>>>>>>>>>>", u, "<<<<<<<<<<<<<<<<<<<<") for q in y: print(q.title) context = {'segment': 'categories', "zipped": zipped} Above code prints as expected in view.py In templete; {{ zipped|length }} {% for u, y in zipped %} {{ u }}---{{ y.title }} {% endfor %} len gives 0, and loop is empty. What's the reason of it? Thank you. -
Implementing the features of "The Browsable API" from the Django REST Framework in a react app
I have a few models with a structure similar to this: class YearInSchool(Enum): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' @classmethod def choices(): return (tuple(i.name, i.value) for i in YearInSchool) class Student(models.Model): year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices(), ) class MyModel(models.Model): # Some other fields here year = models.ForeignKey(Student, blank=True, null=True, on_delete=models.SET_NULL) The View I am using looks something like this: class GetStudentDetails(generics.RetrieveUpdateDestroyAPIView): class StudentSerializer(serializers.Modelserializer): class Meta: model = Student fields = '__all__' queryset = Student.objects.all() serializer_class = StudentSerializer lookup_field = 'year_in_school' If I made an API call the result would look something like this: { // Some other fields here "year_in_school": 1, } If I wanted to have the options returned from the API call as well, I would have to add an additional field like the one described in this post: https://stackoverflow.com/a/54409752/15459291 If I wanted the value of the currently selected choice instead of the primary key, I would also have to flatten the structure by adding another new field. "The Browsable API" from the Django REST Framework shows all this information and implements drop-down selectors for choice fields that have the currently selected value preselected. To me this seems like … -
How can I place header and text next to my img?
I want to add 4 images to Blog(2 columns and each one has 2 images with its header and description) of my site want to place its header and paragraph on right side of it, how can I do that? here is my css and html code: <section id="part2"> <div class="container"> <h1>Blog</h1> <div class="box"> <img src="images/img1-service.jpg" width='255' height="175"/> <h3>10 RULES TO BUILD A WILDLY</br> SUCCESSFUL BUSINESS</h3> <p>You can edit all of this text and</br> replace it with anything you have</br> to say on your blog.</p> </div> <div class="box"> <img src="images/img2-service.jpg" width='255' height="175"/> <h3>9 STEPS TO STARTING A</br> BUSINESS</h3> <p>This is a generic blog article you</br> can use for adding blog content /</br> subjects on your website.</p> </div> </div> </section> there should be 4 photos,i haven't add them yet and my css: body{ margin: 0; padding: 0; } .container{ margin:auto; overflow:hidden; } #part2 h1{ text-align:center; font-size:250%; } .box{ display: inline; text-align:center; float:left; padding:10px; width:30%; width: 33.3%; } -
Exception in thread django-main-thread Traceback
I am getting this error while trying to run my Django project. I have installed all needed libs and still do not have any clue why this error is accurring. Explored almost all the resources available on the internet and still did not get any help in solving this. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Dharv\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 …