Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist django rest framewok
I try to return HTML responses, but i have a TemplateDoesNotExist problem. ModelViewSet class ProfileList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'test.html' def get(self, request): queryset = Profile.objects.all() return Response({'profiles': queryset}) Strucute of app -
Is there a way to use optgroup to group results in Django admin select2 autocomplete fields?
I've got a Django application that allows people to set a foreign key to city, state, and country models on a Post model. I have set up the Django admin form to use the built-in autocomplete fields for each of the location fields of the Post instance. I would like to be able to use the built-in select2 ability of generating <optgroup>s to nest the cities in the list inside a group for their state to keep things tidy and allow the user to visually distinguish between cities in different states with the same name. I have already added the state name to the string representation of the city, and expanded the search fields of the city admin to include the state's name in addition to the city's name. At the moment, admins can type Alaska in the city select2 field and return all cities whose name or whose state's name contains the string Alaska. However, I can't seem to find any documentation or anyone who's ever asked about providing a way to group the select2 results. The closest thing that's I've found is this support ticket for Django where someone wanted to add the autocomplete functionality and suggested using … -
CSS is loading to the page, but not showing up fully
padding-top is working correctly, but background-color is crossed out how to fix it? -
Could not parse the remainder:
I saw many questions about this error, but all are distincts and not apply to me, so... My models.py # Category class Category(models.Model): category_name = models.CharField(max_length=64) def __str__(self): return f"{self.category_name}" # Item class Item(models.Model): item_name = models.CharField(max_length=64) category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="items_by_category") price_small = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0) price_large = models.DecimalField(help_text="Price in U$S",max_digits=6, decimal_places=2, default= 0) nradd = models.IntegerField(default=0) def __str__(self): return f"{self.category} {self.item_name} - Qty.of Adds: {self.nradd} - Price Small: {self.price_small} - Price Large: {self.price_large}" My views.py def menu(request): products = list(Item.objects.all().values().order_by('category')) categories = list(Category.objects.all().prefetch_related('items_by_category')) extras = list(Extra.objects.filter(category="T")) subsextras = list(Extra.objects.filter(category="S")) context = { 'Products' : products, 'Categories': categories, 'Extras' : extras, 'Subextras' : subsextras } return render(request, 'orders/menu.html',context) First, I'm trying to simply list the categories with the items who belongs to: My menu.html: {% extends 'orders/base.html' %} {% load static %} {% block title %} Menu {% endblock %} {% block body %} <ul> {% for cate in Categories %} <li>{{ cate.category_name }}</li> <ul> {{% for myitem in cate.items_by_category.all %}} <li>{{ myitem.item_name }}</li> {{% endfor %}} </ul> {% endfor %} </ul> {% endblock %} the error appears in the line: {{% for myitem in cate.items_by_category.all %}} Same commands in the shell goes well: cate … -
Delete button form tag causes line break
I'm trying to have the edit and delete button in the code below side-by-side. They are until i add the form tag for the 'delete_dealer_view'. I'm also wondering why I need the form can't I just use an anchor tag and call the url? <div class="card"> <div class="card-header card-header-success"> All Dealers </div> <div class="card-body"> <table class="table"> <tbody> {% for dealer in dealers %} <tr> <td>{{dealer.name}}</td> <td class="td-actions text-right"> <button type="button" rel="tooltip" title="Edit Dealer" class="btn btn-white btn-link btn-sm"> <i class="material-icons">edit</i> </button> <form method="POST" action="{% url 'dealers:delete_dealer_view' dealer.slug %}"> {% csrf_token %} <button type="submit" rel="tooltip" title="Remove" class="btn btn-white btn-link btn-sm"> <i class="material-icons">close</i> </button> </form> </td> </tr> {% endfor %} </tbody> </table> </div> </div> -
How to convert a datetime from a specific timezone to its UTC version using the django.utils.timezone library?
I am looking for a function from the django.utils.library that would take a datetime from a specified timezone and return its UTC equivalent. Does such a function exist? -
I want to switch the pages in Navigation bar dynamically in django, But my error is page not found 404
Homepage.html <a href="{% url 'home' %}"></a> views.py def home(request): return render(request,'test_homepage.html') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), ] -
Django Admin TypeError args[0] = str(args[0]), cannot update or delete objects
Jun 04 18:21:25 dev-strandbase app/web.1 [2020-06-05 01:21:24 +0000] [10] [ERROR] Error handling request /admin/parts_table/part/35/change/ Jun 04 18:21:25 dev-strandbase app/web.1 Traceback (most recent call last): Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 134, in handle Jun 04 18:21:25 dev-strandbase app/web.1 self.handle_request(listener, req, client, addr) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 175, in handle_request Jun 04 18:21:25 dev-strandbase app/web.1 respiter = self.wsgi(environ, resp.start_response) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ Jun 04 18:21:25 dev-strandbase app/web.1 response = self.get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response Jun 04 18:21:25 dev-strandbase app/web.1 response = self._middleware_chain(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response = response_for_exception(request, exc) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception Jun 04 18:21:25 dev-strandbase app/web.1 response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response = get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/deprecation.py", line 94, in __call__ Jun 04 18:21:25 dev-strandbase app/web.1 response = response or self.get_response(request) Jun 04 18:21:25 dev-strandbase app/web.1 File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner Jun 04 18:21:25 dev-strandbase app/web.1 response … -
django static file not found issue for new create static file
<!DOCTYPE html> {% load static %} <html> <head> <style> .info-container { margin-top: 6%; background-color: honeydew; text-indent: 20px; } .video-label { text-align: center; } .back-link { margin: 9px 15px; padding: 2px; } </style> <title>Coronavirus Tracker</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light" id="header-nav"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-nav"> <h2 class="nav-item">Weather Observations and Forecast</h2> <a class="nav-item back-link" href="/covid_tracker">Back to Coronavirus Tracker Home</a> </div> </nav> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 info-container"> <p> test </p> </div> </div> <div class="row"> <video width="480" height="360" class="video-player col-6" controls> <source src="{% static 'coronavirus_tracker/videos/wind.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> <video width="480" height="360" class="video-player col-6" controls> <source src="{% static 'coronavirus_tracker/videos/noaatemp-usa.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> </div> <div class="row"> <p class="col-6 video-label"> Global Wind Animation </p> <p class="col-6 video-label"> US Tempature Animation </p> </div> <div class="row"> <video width="480" height="360" class="video-player col-12" controls> <source src="{% static 'coronavirus_tracker/videos/sat-rainfall.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> <p class="col-12 video-label"> Satellite Rainfall Observations </p> </div> </div> … -
How can I print the result I get from the algorithm in my Django project?
enter image description here I want to show my conclusion to the percentile here. enter image description here -
Install DRF 3.12 Alpha
I want to use a pre-release version of Django Rest Framework (DRF) in order to take advantage of the new JSONField feature. There doesn't appear to be a version to "pip install" for alpha 3.12. What is the appropriate way to install the alpha version into my env? -
Django template variable not accessible in javascript
The html (see below) has a <div class="choiceRadio"> that contains radio buttons and another <div class="choiceSelect"> that contains check boxes. The goal is to make the .choiceSelect div appear or disappear dependent on which radio button is selected. Note that this question may have been answered already except I have trouble applying them to my situation where the django template variable is needed to determine which radio button was selected. The buttons were created on the fly when the html is rendered from views.py. I have not been unable to get the template variable {{ selection.name }} to show up in the javascript. <script> document.addEventListener('DOMContentLoaded', () => { // hide div styled .choiceSelect when radio button #choice button is clicked document.querySelector('#choice').onclick = () => { var s = "{{ selection.name }}"; alert(s); div = document.querySelector('.choiceSelect'); if ('s' === 'special') { div.style.display = 'none'; } else { div.style.display = 'block'; } } }); </script> <body> {% for selection in category %} <div class="choiceRadio"> <ul> <li> {% if size == "small" %} <input type="radio" name="optradio" id="choice" value="{{ selecton.name }}-{{ selection.price-small }}"> <label for="{{ selecton.name }}-{{ selection.price-small }}">{{ selection.price_small }}</label> {% elif size == "large" %} <input type="radio" name="optradio" id="choice" value="{{ selecton.name }}-{{ … -
Changing API endpoint between development and production (React/Django)
I am developing a react app inside of a django project and connect them using the Django rest framework. For making API calls from within the react app I am using axios. Now in my development environment, I obviously call a localhost URL to access the API. For this, I have a file that contains an axios instance: import axios from "axios"; export const axiosInstance = axios.create({ baseURL: "http://127.0.0.1:8000/api/", timeout: 60000, }); Obviously, my API calls don't work in production as the URL differs from the one above. I am compiling my react app to a static file which I include in my django project so I don't think I could really add any code that checks for the environment. One idea that I had is that I could include a file into my project that I would not push into production and then check for whether this file exists or not and adjust the url in an if statement. However, I am not sure if that is a good solution or how I would implement this in plain Javascript. I am happy to hear any thoughts on this -
How not to display Django foreign key object source in table
I want to display date in table which is foreign key in this case and when I do this as result I see the date with information that it is object of different table. Which I don't want. I would appreciate help with this. class Factclaimcases(models.Model): idfactclaimcase = models.IntegerField(db_column='IdFactClaimCase', primary_key=True) # Field name made lowercase. idtechnican = models.ForeignKey(Dimtechnican, models.DO_NOTHING, db_column='IdTechnican') # Field name made lowercase. thedate = models.ForeignKey(Dimdate, models.DO_NOTHING, db_column='TheDate') # Field name made lowercase. description = models.CharField(db_column='Description', max_length=50) # Field name made lowercase. manufacturedef = models.TextField(db_column='ManufactureDef', blank=True, null=True) # Field name made lowercase. This field type is a guess. doc = models.BinaryField(db_column='Doc', blank=True, null=True) # Field name made lowercase. <div class="container"> <table> {% for item in query_results %} <tr> <td>{{ item.idfactclaimcase }}</td> <td>{{ item.thedate }}</td> <td>{{ item.description }}</td> </tr> {% endfor %} </table> </div> def index(request): query_results = Factclaimcases.objects.all() context = { 'query_results': query_results, } return render(request, 'index.html', context) -
How i can get all products except duplicates?
I have 2 models: class Product(models.Model): ... products = models.ManyToManyField('self', related_name='products') class OrderProduct(models.Model): """Products for Order that a user added in his cart.""" product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='order_products') I need to get all OrderProduct.product.products but without duplicates I tried to solve it like: suggestions = [product.product.products.all().distinct() for product in order_products] But I got [<QuerySet [<Product: Apple iMac Retina 5K>, <Product: iMac Pro>, <Product: Apple MacBook Air 2020>]>, <QuerySet [<Product: Apple iMac Retina 5K>, <Product: iMac Pro>]>] That's a list of querysets, not products list Please help me, I want to get result like QuerySet [Product: Apple iMac Retina 5k>, Product: iMac Pro>, Product: Apple MacBook Air 2020>] (so it looks like the result in my previous code, but in a 1 queryset and without duplicates (distinct)) -
Django Model for defining a relationship between two other models and filtering later
So am designing a REST API for a mobile blogging app, in which am trying to implement an upvote feature for the blog posts where what i want to implement is: Whenever a user U upvotes a particular blog B the client will send a POST request (with username and the blog name) which will define a relationship between them in the Database, so that later when the client wants to know that if a particular user has upvoted a particular blog or not, it can get to know by making a GET request through some filering. I have tried to create Vote model, in which i define a ManyToMany relationship with both, user and the blog post ( see the Vote Model below for better understanding) here are my models, class User(models.Model): username = models.TextField(max_length=30) def __str__(self): return self.username class Post(models.Model): headline = models.CharField(max_length=200) # the name of the blog #some other stuff like body of the blog . . def __str__(self): return self.headline The Vote model, class Vote(models.Model): user = models.ManyToManyField(User) post = models.ManyToManyField(Post) def __str__(self): return ("%s %s" %(self.user, self.post)) This does not do the job well, e.g., It requires the URL of the users and blog … -
React with Django: Internal Server Error 500
api-service.js This is my api code. Using this code, a user can login and do some operations like update, create and delete movies. All functions are working fine except for the registerUser. export class API { static loginUser(body) { return fetch(`http://127.0.0.1:8000/auth/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static registerUser(body) { return fetch(`http://127.0.0.1:8000/api/users/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static updateMovie(mov_id, body, token) { return fetch(`http://127.0.0.1:8000/api/movies/${mov_id}/`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static createMovie(body, token) { return fetch(`http://127.0.0.1:8000/api/movies/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static deleteMovie(mov_id, token) { return fetch(`http://127.0.0.1:8000/api/movies/${mov_id}/`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` } }) } } auth.js import React, { useState, useEffect } from 'react'; import { API } from '../api-service'; import { useCookies } from 'react-cookie'; function Auth(){ const [ username, setUsername ] = useState(''); const [ password, setPassword ] = useState(''); const [ isLoginView, setIsLoginView ] = useState(true); const [token, setToken] … -
Part of celery-beat periodic task not triggered
In django admin panel, I created about 1500 celery-beat periodic tasks, and 100 of them has the same crontab schedule 15 4 * 1 *. All of them were enabled. But at 04:15 on day-of-month 1, one of the periodic tasks was not sending due task to celery worker while all other tasks were sending. From the django admin panel, this periodic task's last_run_time is None, which indicates that it is not triggered. I tried to configure the crontab schedule to 15 * * * * and then it runs successfully at minute 15. So I wonder is there any limitation of the number of celery-beat periodic tasks? celery.py app = Celery('myapp', broker=os.getenv('BROKER_URL', None)) @signals.setup_logging.connect def setup_logging(**kwargs): """Setup logging.""" pass app.conf.ONCE = { 'backend': 'celery_once.backends.Redis', 'settings': { 'url': 'redis://localhost:6379/0', 'default_timeout': 60 * 60 } } app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) from django.utils import timezone app.conf.update( CELERY_ALWAYS_EAGER=bool(os.getenv('CELERY_ALWAYS_EAGER', False)), CELERY_DISABLE_RATE_LIMITS=True, # CELERYD_MAX_TASKS_PER_CHILD=5, CELERY_TASK_RESULT_EXPIRES=3600, # Uncomment below if you want to use django-celery backend # CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend', CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', # Uncomment below if you want to store the periodic task information in django-celery backend CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers.DatabaseScheduler", # periodic tasks setup CELERYBEAT_SCHEDULE={ 'check_alerts_task': { 'task': 'devices.tasks.alert_task', 'schedule': 300.0 # run every 5 minutes }, 'weather_request': { … -
CMS build with Python?
I'm trying to create a blog and e-commerce site. Is there an equivalent of Wordpress developed with Python ? Unfortunately I don't speak php. Thank you. -
Django Queryset returning different results for two exclude criteria and combined exclude criteria
Why django returning different results for below two exclude statements? Django Exclude Statement 1: self.fields.exclude(record_type__isnull=True, field=None).prefetch_related('field', 'field__table') Respective Django SQL Query: SELECT field1, field2, field__table FROM `table` WHERE (`table`.`t_ct_id` = 2 AND `table`.`t_id` = 32 AND NOT (`table`.`record_type` IS NULL AND `table`.`field_id` IS NULL)) Record Count: 395 Django Exclude Statement 2: self.fields.exclude(record_type__isnull=True).exclude(field=None).prefetch_related('field', 'field__table') Respective Django SQL Query 2: SELECT field1, field2, field__table FROM `table` WHERE (`table`.`t_ct_id` = 2 AND `table`.`t_id` = 32 AND NOT (`table`.`incoming_record_type` IS NULL) AND NOT (`table`.`field_id` IS NULL)) Record Count: 152 I am using django version 2.2.11 and MYSQL as database -
Django and Ajax: SyntaxError: Unexpected token D in JSON at position 0 at parse (<anonymous>)
The backend to my project is django (I am working on the 4th page of my project). I have a series of forms and inputs that take input data and then roll the inputs into a json object. I have checked to make sure that the json object is valid (pulled it from the console and used a json validator) after using stringify (var modelData_toserver = JSON.stringify(modelData). The resultant json is: {"data":[{"depth":[0]},{"temp":[1]},{"lakename":"m"},{"lakeId":"m"},{"area":"1"},{"fetch":"1"},{"maxDepth":"1"},{"lat":"1"},{"long":"1"},{"airTemp":"1"},{"shelterFactor":"1"},{"extinctCoeff":"1"},{"dispersion":"1"},{"longWave":"1"}]} My ajax code is (modelData_toserver is the json): function sendInputs(modelData_toserver, name){ var urlViews = "/beach/bmominputs/" + name + "/" console.log(urlViews) $.ajax({ url: urlViews, type:"POST", dataType: "json", data: modelData_toserver, error: function(jqXHR, textStatus, errorThrown) { alert('Lake Characteristics Data Not Delivered Properly'); $('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>'); console.log('jqXHR:'); console.log(jqXHR); console.log('textStatus:'); console.log(textStatus); console.log('errorThrown:'); console.log(errorThrown); console.log('datatype:'); console.log(typeof data); }, success: function(data, textStatus, jqXHR) { alert('Data Sent Sucessfully'); } }); I am pretty sure my url.py is pointing properly to my view since if I input my URL directly into the browser it prints out the HttpResponse of the view -- HttpResponse("Data Posted Successfully"). I suspect that the stingify javascript is causing problems but not sure how to convert variable values to strings another way. Thank you for any … -
How to render HTML template for all nodes on-click - using Django mptt tree
I have setup a Django mptt tree which is displaying the tree correctly. The nested tree consists of 2 types of objects (reseller and customer - added in model). The reseller menu can be nested before reaching to a final customer menu at the end of a node. Based on type, both of them should render a html template on-click. But only the end node (leaf-node) is rendering html on-click. While the root-node or intermediate nodes do not respond to href menu associated. I'm stuck for almost 2 days and cannot figure out a solution. Please help. Django Model: from django.db import models from django.contrib.auth.models import User from mptt.models import MPTTModel, TreeForeignKey class Reseller(MPTTModel): reseller_name = models.CharField(max_length=40) reseller_email = models.EmailField(max_length=70,blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['reseller_name'] def __str__(self): return self.reseller_name class Customer(models.Model): customer_name = models.CharField(max_length=40) customer_email = models.EmailField(max_length=70,blank=True) reseller = models.ForeignKey(Reseller, on_delete=models.CASCADE, null=True, blank=True, related_name='cust_children') def __str__(self): return self.customer_name Django Url: from django.urls import path from . import views urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard'), path('', views.loginpage, name='login'), path('ViewReseller/<str:pk>', views.ViewReseller, name='ViewReseller'), path('ViewCustomer/<str:pk>', views.ViewCustomer, name='ViewCustomer'), ] Django View: @login_required(login_url='login') def ViewReseller(request, pk): resellers = Reseller.objects.all() customers = Customer.objects.all() reseller_details = Reseller.objects.get(id=pk) context = { 'resellers' … -
How can i make a random default value for a django app that will change every time
I am trying to make a randomized math problem site but i cant save my random value in the database models.py class Problem(models.Model): answer = models.IntegerField() solution = models.IntegerField(default = random.randint(1,100)) correct = models.BooleanField(default = False) view.py def TedixRS_view(request, *args, **kwargs): current = Problem.objects.last() current.solution = random.randint(1,100) current.save() random_one = current.solution - random.randint(1,current.solution-1) random_two = current.solution - random_one print(current.solution) form = ProblemForm(request.POST or None) if form.is_valid(): form.save() form = ProblemForm() my_context = { 'random_one' : random_one, 'random_two' : random_two, 'form': form } -
How to change html file (front end) following the back end
I already have an html file of login user page(front end), then i follow the tutorial https://developer.mozilla.org/id/docs/Learn/Server-side/Django/Authentication I have reached stage Login Template, can you help me convert my html page (front end) following the tutorial my login page html: {% load static %} <html> <head> <title>Login Page</title> <link rel="stylesheet" type="text/css" href="{% static 'style login.css' %}"> <body> <div class="loginbox"> <img src="{% static 'avatar.png' %}" class="avatar"> <h1>Login Here</h1> <form method="post" action="{% url 'login'%}"> <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="Login"> <a href="">Don't have an account</a> </form> </div> </body> </head> </html> the tutorial: {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> … -
how to pass value from views to non-editable field django pyhton
i want to auto insert user to the follwing model: class Moduls(models.Model): module_name = models.CharField(max_length=255) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='created_by', blank=False, null=False , on_delete=models.CASCADE, editable = False) i have 2 cases : 1- in django admin and i solve this case by the following * add editable = False to created by field * in admin.py i used the follwoing: def save_model(self, request, obj, form, change): obj.created_by = request.user super().save_model(request, obj, form, change) but i face the problem when i try to use forms.py i can't pass user from user views.py and if i want to add created_by field to my form i have this error: 'created_by' cannot be specified for Moduls model form as it is a non-editable field