Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does any interaction with the django site direct you to the data addition form?
The task was given to develop a service for working with the restaurant database on django. Clicking on the corresponding buttons /fields of the data table should redirect to pages with edit/add/delete forms, but any interaction with the site redirects only to the page for adding new data. I've been trying to find the reason for this behavior for several hours, but nothing comes out. Below is the html markup of one of the pages, views, forms and URLs for working with one of the database tables. <body> {% include 'main/navbar.html' %} <h1>restaurants</h1> <div class="add"> <form method="post" action="{% url 'create_restaurant' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Добавить</button> </form> </div> <table class="table"> <ul></ul> <thead> <tr> <th>Address </th> <th>Phone number</th> <th>Delivery area</th> <th>Menu</th> <th></th> </tr> </thead> <tbody> {% for restaurant in restaurants %} <tr data-id="{{ restaurant.id }}"> <td class="editable-field" data-field="address">{{ restaurant.address }}</td> <td class="editable-field" data-field="phone">{{ restaurant.phone }}</td> <td class="editable-field" data-field="district">{{ restaurant.delivery_code.district }}</td> <td class="editable-field" data-field="menu">{{ restaurant.menu_code.name }}</td> <td> <button class="btn btn-danger" data-toggle="modal" data-target="#confirmDeleteModal{{ restaurant.id }}"> delete </button> <div class="modal" id="confirmDeleteModal{{ restaurant.id }}" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="confirmDeleteModalLabel">Confirmation of deletion</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div … -
Django Admin not working on Azure App service
I have a Django Restful API hosted on Azure App Server. For Admin page, all static files are generated and place on a folder which configure on settings.py. BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") But when try to access admin page from browser static files return with 500 http status code. Backend logs shows AttributeError: This FileResponse instance has no `content` attribute. Use `streaming_content` instead. Can some one help on this please? -
Django Admin filter DateRangeFilter preserve date after search
I have used django filter in admin with list filter in django below is my search filter form image what issue I am facing is that whenever I filter using date ranges like (from and to) date filters works fine but 1 issue is that the date filters gets wiped after 1 search meaning If i click search button the date forms becomes empty like above I need to prevent this i have my code here any way to preserve search if date is provided in form so that upon clicking the search button does not gets cleared again from rangefilter.filters import DateRangeFilter @admin.register(UserPolicy) class UserPolicyAdmin(BaseModelAdmin): change_form_template = "payment/unsubscribe_button.html" change_list_template = 'common/download_csv.html' form = UserPolicyModelForm list_filter = ( ('created', DateRangeFilter), 'is_archived', 'is_active', ) list_display = ( 'policy', 'users', 'payments', 'payment_logs', 'start_date', 'is_active', 'end_date', 'payment_mode' ) search_fields = ( 'user__phone_number', 'registration_id' ) -
Write unittest case if a method or function returns array or list?
Here the question is that how to write test case for a Model mothod or function who returns an array or list? from django.db import models class Task(models.Model): title = models.CharField(max_length=100, blank=True) desc = models.TextField(blank=True) tags = models.TextField(null=True, blank=True) # function to split tags def tag_list(self): taglist = self.tags.split(',') return taglist Here tag_list is that function who returns list of tags Here i am expecting to write a unittest case for tag_list method -
login with superuser nog working in django admin panel
So I built this custom auth model because I want to use the email instead of the username field which is default for django. AUTH_USER_MODEL = 'customers.Customers' This I have in my settings.py from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.contrib.auth.models import UserManager # Create your models here. class CustomerManager(UserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Customers must have an email address') user = self.model( email=email, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, name, last_name, email, phone, password, **kwargs): kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_staff', True) return self._create_user(email, password, **kwargs) class Customers (AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(blank=False, unique=True) phone = models.CharField(max_length=15) password = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(blank=True, null=True) objects = CustomerManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name', 'last_name', 'phone'] class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' def get_full_name(self): return self.name + ' ' + self.last_name def get_short_name(self): return self.name def check_password(self, password): return self.password == password This is my custom auth model. I have succesfully created … -
How to write unit test case for due date validation ? How to unit test DateField or DateTimeField validation?
Here main question is that how to write unittest cases for due date validation with DateField or DateTimeField we can do it through multiple methods & i will answer you those methods So basically in models.py from django.db import models from django.forms import ValidationError class Task(models.Model): title = models.CharField(max_length=100, blank=True) desc = models.TextField(blank=True) time_stamp = models.DateField(auto_now_add=True, null=True, blank=True) due_date = models.DateField(null=True, blank=True) # logic for due_date def clean(self): super().clean() if self.due_date < self.time_stamp: raise ValidationError("Due date must be greater than current date") I am expecting to test this clean() validation method, in case when due date is less then start_date or time_stamp it should through ValidationError -
ordering = ['-date_posted'] does not work
I have this class and I wanted to sort the posts of my blog by date posted but it does not work and gives me this error what should I do? Thanks in advance FieldError at / Cannot resolve keyword 'date_posted' into field. Choices are: author, author_id, body, id, title views.py from django.shortcuts import render, redirect from django.http import HttpResponse from datetime import datetime from posts.models import post from django.contrib.auth import authenticate, login from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic import ListView # Create your views here. class PostListView(ListView): model = post template_name = 'website/welcome.html' context_object_name = 'posts' ordering = ['-date_posted'] urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users.views import signup, profile from django.contrib.auth import views as auth_views from posts import views from website.views import index from website.views import PostListView urlpatterns = [ path('admin/', admin.site.urls), path('', PostListView.as_view(), name='home'), path('posts/', include('posts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path('profile/',profile, name='profile'), path('', index, name='index'), ] -
Psycopg[binary] and psycopg2 not working in my virtual enviornment for my django project
When I try to run the command docker-compose exec web python3 manage.py startapp accounts This command outputs the following complete error message. Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/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 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 58, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.10/site-packages/django/db/models/options.py", line 243, in contribute_to_class self.db_table, connection.ops.max_name_length() File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 193, in create_connection backend = … -
Issue with requests from Nuxt.js not adding cookies to Django server
I'm working with a Nuxt.js frontend and a Django backend and encountering an issue where cookies are not being set correctly after JWT authentication. My Nuxt.js app is running on https://localhost:3000 and the Django server is on https://localhost:8000. Despite successful authentication using JWT tokens, when I make a request to the server, the cookies are not being attached. Checking the Network tab, I noticed that the client-side isn't sending cookies. Here's my Django settings related to CORS and cookies: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "https://localhost:3000", ] # Other settings... SESSION_COOKIE_SAMESITE = 'None' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CORS_ALLOW_CREDENTIALS = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] And this is how I'm making the request in Nuxt.js: <template> <div> <h1>User Profile</h1> <form @submit.prevent="getUserInfo"> <button type="submit">UserInfo</button> </form> </div> </template> <script> import axios from 'axios'; export default { methods: { async getUserInfo() { try { const response = await axios.get('https://localhost:8000/api/userinfo/', { }, { withCredentials: true }); console.log(response.data); } catch (error) { console.error(error); } }, }, … -
AJAX is only getting data from last form in loop (Django)
I have a for loop that creates a number of forms on the page. I want to be able to submit these forms to another page without refresh using AJAX, however no matter which form I submit it only ever shows the value for the very last form. HTML code {% for post in post_list %} <form class = "f_form" id="f_form" name = "myForm" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="add">Submit</button> </form> {% endfor %} Jquery <script type="text/javascript"> $(document).ready(function(){ $(document).on('click','.add',function (event) { event.preventDefault(); var element = $(this); $.ajax({ url: '{% url "webscraper-favorited" %}', method: 'post', data:element.parent('.f_form').serialize(), success: function(data){ $('#message').html(data); } }); return false; }); }); </script> views.py def favorited(request): if request.method == 'POST': favorited = request.POST.get('favorited') favorites.append(favorited) print(favorited) context = { 'favorites' : favorites, } return render(request, 'webscraper/favorited.html', context) Right now the script is outside of the for loop but I previously tried putting it in the for loop as well. Instead of binding the script to the submit button I also tried binding it to the form id. That yielded the same result from my attempts. -
InconsistentMigrationHistory
I unfortunately deleted contenttypes app from django_migrations in psql(pgadmin4) database. From then when i'm trying to run py manage.py makemigrations it returns " raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration auth.0001_initial is applied before its dependency contenttypes.0001_initial on database 'default'. " My entire project was collapsed. Any solution please.......... As these migrations are automatically created by django i cant eeven understand where to modify the code. -
RTCPeerConnection Issue: Uncaught DOMException - Failed to execute 'setRemoteDescription' on 'RTCPeerConnection Django
I am encountering an issue with my WebRTC implementation in Django using Django Channels. The error I am facing is: "Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable" After some research, I found a possible explanation for this error on Stack Overflow. It seems to be related to the fact that when a third user joins, it sends an offer to the two previously connected users, resulting in two answers. As a single RTCPeerConnection can only establish one peer-to-peer connection, attempting to setRemoteDescription on the second answer fails. The suggested solution is to instantiate a new RTCPeerConnection for every remote peer. However, I'm unsure how to implement this in my existing code. Below is the relevant portion of my consumers.py and JavaScript code. consumers.py and JavaScript code import json from typing import Text from django.contrib.auth import authenticate from Program.models import ChatRoom, Message from channels.generic.websocket import AsyncWebsocketConsumer from .service import add_remove_online_user, updateLocationList, add_remove_room_user from asgiref.sync import sync_to_async from channels.db import database_sync_to_async class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = self.room_name print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.authenticate_user() await self.channel_layer.group_send( self.room_group_name, { 'type' : … -
How to rreturn a nested serialized data in Django
I created a Registration view in my Django app, but when I tried testing it, I wasn't getting the expected result. I'm trying to test my view with the data below, but I wasn't getting the expected result: { "email": "faruqmohammad@gmail.com", "first_name": "Faruq", "last_name": "Mohahmmad", "phone_number": "08137021976", "password": "#FaruqMohammad1234", "confirm_password": "#FaruqMohammad1234", "vehicle_registration_number": "ABJ145", "min_capacity": 20, "max_capacity": 50, "fragile_item_allowed": true, "charge_per_mile": 1000 } And the response I get is { "data": { "user": { "email": "mohammedfaruq@gmail.com", "first_name": "Mohammed", "last_name": "Faruq", "phone_number": "08137021976" }, "is_available": true, "vehicle_type": "TWO_WHEELER", "vehicle_registration_number": "", "min_capacity": null, "max_capacity": null, "fragile_item_allowed": true, "ratings": null, "charge_per_mile": null }, "message": "Rider registration successful" } {"vehicle_registration_number": "", "min_capacity": null, "max_capacity": null, "fragile_item_allowed": true, "ratings": null, "charge_per_mile": null} These values are set to the default value from the model even when I provided them And below is my model, serializer and views Model: class Rider(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, related_name="rider_profile" ) vehicle_type = models.CharField(max_length=50, default="TWO_WHEELER") vehicle_registration_number = models.CharField(max_length=20, unique=True) is_available = models.BooleanField(default=True) min_capacity = models.PositiveIntegerField(null=True, blank=True) max_capacity = models.PositiveIntegerField(null=True, blank=True) fragile_item_allowed = models.BooleanField(default=True) charge_per_mile = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) current_latitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) current_longitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) ratings = models.DecimalField(max_digits=3, decimal_places=2, … -
How to filter Django model for AND and OR simultaneously
Let's say I have a User model and a Dataset model. I want to get all datasets that (have a certain type AND (belong to a certain user OR don't belong to anyone)). What is the best approach to achieve this? Code sample: class User(AbstractUser): username = models.CharField(max_length=150,unique=True,) first_name = models.CharField(blank=True, max_length=150) last_name = models.CharField(blank=True, max_length=150) class Dataset(models.Model): name = models.CharField(null=False, unique=True, max_length=50) type = (models.PositiveIntegerField()) UserID = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE, related_name="ds_owner", ) I am trying to figure out how to select something like this: def view_name(request): usr = User.objects.get(id=request.user.id) allowed_datasets = Dataset.objects.filter(type=1 AND (UserID=usr OR UserID__isnull=True)) -
Validate Django form field before sumbitting
Django form has file field and clean_file method. class UploadFileForm(forms.Form): file = forms.FileField() def clean_file(self): ... And there is a button called 'Apply' I want to validate the file when I select it, and if the validating is successful, I will click the Apply button which will send a post request with this file. But I don't understand how I can validate file before submitting it or I should use form into form. Or it will be in two forms, but then how to throw a file between them -
How do I change the name of the Django "Dosya Seç" button?
enter image description here strong text Hello I am using ImageField as my Django model. I use the structure in my model as forms. But my problem is, how do I change the text of the "Dosya Seç" button here? Currently, English and Turkish are mixed. How can I fix this? Thank you -
how to do autocomplete field with choice field in django admin panel?
i have choice field like region_choices , i want to make autocomplete in it how can i do it ? there is my models.py from django.db import models from django.utils import timezone class Theriology(models.Model): REGION_CHOICE = ( ('Восточно-Казахстанская область.', 'Восточно-Казахстанская область.'), ('Абайская область', 'Абайская область'), ('Актюбинская область', 'Актюбинская область'), ('Атырауская область', 'Атырауская область'), ('Западно-Казахстанская область', 'Западно-Казахстанская область'), ('Мангистауская область', 'Мангистауская область'), ('Акмолинская область', 'Акмолинская область'), ('Костанайская область', 'Костанайская область'), ('Павлодарская область', 'Павлодарская область'), ('Северо-Казахстанская область', 'Северо-Казахстанская область'), ('Карагандинская область', 'Карагандинская область'), ('Улытауская область', 'Улытауская область'), ('Алматинская область', 'Алматинская область'), ('Жетысуская область', 'Жетысуская область'), ('Жамбылская область', 'Жамбылская область'), ('Кызылординская область', 'Кызылординская область'), ('Туркестанская область', 'Туркестанская область')) genus = models.CharField(max_length=250) species = models.CharField(max_length=250) subspecies = models.CharField(max_length=250,blank=True, null=True) metode = models.CharField(max_length=250,blank=True, null=True) region = models.CharField(max_length=250, choices=REGION_CHOICE) now i have this kind of list so i want to add autocomlete like in picture i want like that -
How to convert dynamic html page to pdf in Django?
I have a task to convert a dynamic html page into a pdf document. What we have: dogovor application. Formadogovora.html page which contains a form with the required fields. The page dogovortemplate.html which contains text into which the values from the form should be substituted on the page formadogovora.html and a pdf document should be immediately generated. The dogovor/forms.py file contains: `from django import forms class DogovorUserForm(forms.Form): sellername = forms.CharField(label='Seller's name', widget=forms.TextInput(attrs={'class':'form-input'})) yachtclass = forms.CharField(label='Yacht Class', widget=forms.TextInput(attrs={'class':'form-input'}))` The dogovor/urls.py file contains: `from django.urls import path from . import views app_name = 'dogovor' urlpatterns = [ path('formadogovora/', views.formadogovora_user, name='formadogovora'), ]` The file dogovor/views.py contains: def formadogovora_user(request): form = DogovorUserForm() # Import the form class from forms.py return render(request, 'dogovor/formadogovora.html', {'form': form}) Contents of the formadogovora.html file: `{% extends 'base.html' %} {% load static %} {% block title %}Form of agreement{% endblock %} {% block content %} Form of agreement {% csrf_token %} {{ form.as_p }} Generate document {% endblock %}` Contents of the dogovortemplate.html file: `Agreement This agreement is concluded between: Seller: {{ dogovor.sellername }} Yacht class: {{ dogovor.yachtclass }} About the subject of the agreement: The Contractor undertakes to perform work on the development and implementation of software for the … -
Pass a view as a parameter to the url filter
What happens is that I want in my header template that I will embed in my main page to have the links to the other templates and according to what I researched I find that using the url filter and passing it a view should work but in my case it does not work <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <header> <nav> <li> <ul><a href="{% url 'Home'%}">Principal</a></ul> <ul><a href="{% url 'Informacion'%}">Informacion</a></ul> <ul><a href="{% url 'Imagenes'%}">Imagenes</a></ul> </li> </nav> </header> </body> </html> from django.shortcuts import render # Create your views here. def Home(request): return render(request,"principal.html") def Informacion(request): return render(request,"Informacion.html") def Imagenes(request): return render(request,"images.html") This produces Reverse for 'Home' not found. 'Home' is not a valid view function or pattern name. -
Serializing multiple inheritance models in Django REST Framework
I have this model structure: class Main (models.Model): name=models.Charfield(max_length=50) ... class Category (Main): type=models.Charfield(max_length=50) ... class SubCategory1(Category): charasteristic=models.Charfield(max_length=60) ... class SubCategory2(Category): charasteristic=models.Charfield(max_length=60) That is, there is one parent from which one children inherits, from which, in turn, multiple childrens inherit. For the API, I would like to show a complete structure in the json, from grandparent to every grandson. I mean, if I use the following serializer: class Subcategory1_serializer(serializers.ModelSerializer): class Meta: model=Subcategory1 fields=("__all__") it returns something like this: [ { "name": "type": "charasteristic": }, ] But this forces me to create a serializer for every single Subcategory. I want to get it in an automatic way. I've tried accessing via subclasses, I took a look at some proposals about Polymorphism (but I get lost) and I have tried to redefine inheritance in terms of OneToOne relationships, but I still cannot solve it (and it complicates data introduction from the admin panel). Any help would be great, Thanks in advance -
Assign an action to the button
By clicking the button, the item must be sold and no one else can bid. However, the button does nothing. views.py: if request.user == off.seller: close_button = True off.bid_price = (off.bid_price) Bid_info.checkclose = True html: {% if close_button %} <button type="submit" class="btn btn-primary">Close</button> {% endif %} models: class Bid_info(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") bid_price = models.DecimalField(max_digits=10, decimal_places=2) checkclose = models.BooleanField(default=False) -
Django cache not working on apache server
I'm using Django 4.2 In my development env the cache is working fine(file-based cache) but when I deployed on Apache (windows), the cache stopped working. Some research mentioned something to do with middleware but I don't have any cache meddleware in development. I'm using view-based cache. -
Attribute Error at / 'tuple' object has no attribute 'get' in Django
I add my index.html file to templates directory and then change all the src and etc but I receive this error what should I do for it: D:\Django\2\blog_project\venv\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ … Local vars D:\Django\2\blog_project\venv\Lib\site-packages\django\utils\deprecation.py, line 136, in call response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars D:\Django\2\blog_project\venv\Lib\site-packages\django\middleware\clickjacking.py, line 27, in process_response if response.get("X-Frame-Options") is not None: ^^^^^^^^^^^^ … Local vars I try to run a html page in my django project but i receive an error -
The page on the site is not displayed, please help me figure out what the problem is?
Add the dogovor application to the settings.py file. INSTALLED_APPS = [ #... 'agreement', #... ] Create a Dogovor model. `from django.db import models class Dogovor(models.Model): name = models.CharField(max_length=255) enginer = models.CharField(max_length=255) capitan = models.CharField(max_length=255) def get_absolute_url(self): return reverse('dogovor:forma-dogovora')` Create a FormaDogovoraView. `from django.views.generic import FormView from .forms import DogovorForm class FormaDogovoraView(FormView): template_name = 'dogovor/forma-dogovora.html' form_class = DogovorForm success_url = '/' def form_valid(self, form): return super().form_valid(form)` Create a DogovorForm. `from django.forms import ModelForm from .models import Dogovor class DogovorForm(ModelForm): class Meta: model = Agreement fields = ['name', 'enginer', 'capitan']` Create a template forma-dogovora.html. `{% extends 'base.html' %} {% block content %} <h1>Form of agreement</h1> <form action="{% url 'dogovor:forma-dogovora' %}" method="post"> {% csrf_token %} <label for="name">Organization name:</label> <input type="text" name="name" id="name"> <label for="enginer">Engineer:</label> <input type="text" name="enginer" id="enginer"> <label for="capitan">Captain:</label> <input type="text" name="capitan" id="capitan"> <input type="submit" value="Generate document"> </form> {% endblock %}` Create a template dogovor-template.html. ` Agreement Agreement <p>This agreement is concluded between:</p> <ul> <li>Name of organization: {{ name }}</li> <li>Engineer: {{ engineer }}</li> <li>Captain: {{ capitan }}</li> </ul> <p>The parties agreed on the following:</p> <!-- ... --> </body> </html>` But when I go to the address dogovor/forma-dogovora, it says that the page was not found. I don't know what to do. -
django forms placeholder not working as expected?
i created a django form and tried to add placeholder and remove the form label. i came across a solution to add the palceholder but it seems to have no effect. this is forms.py class AppForm(forms.ModelForm): class Meta: model = App fields = ('__all__') def __init__(self, *args, **kwargs): super(AppForm, self).__init__(*args, **kwargs) self.fields['appname'].widget.attrs['placeholder'] = 'App Name' self.fields['applink'].widget.attrs['placeholder'] = 'App Name' this is my html file {% extends 'main/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="content-above"> </div> <div class="content"> <div> <form action="" method="post" autocomplete="off" enctype="multipart/form-data"> <div> {% csrf_token %} {{ form.appname|as_crispy_field }} {{ form.applink|as_crispy_field }} </div> <div class="row"> <div class="col-md-8"> <button type="submit">Submit</button> </div> <div class="col-md-4"> <a href="{% url 'app_list' %}">Back to list</a> </div> </form> </div> </div> {% endblock content %} please help and if possible also tell me how to remove the default label!