Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render multiple update forms in Django
here is my problem. I have a list of objects that I display in a table and all works just fine except that I would like to edit them inside a modal and submit them using AJAX. I though that it was a simple idea to render, for each row, a form with the inputs pre-filled and then submit the selected form with AJAX. I wonder if there is a relatively simplified way to render the UpdateForm without writing manually all the input fields. Something like this: <table> {% for transaction in transactions %} <tr> <td>{{ transaction.date|date:"d.m.Y" }}</td> <td>{{ transaction.amount }}</td> <td> <a href="#" data-bs-toggle="modal" data-bs-target="#edit{{ transaction.id }}">Edit</a> <div class="modal" id="edit{{ transaction.id }}"> {{ transaction_form }} </div> </td> <tr> {% endfor %} </table> But how can I pass the form from the view? The way I'm currently doing it is that when the user click on edit the page refresh and the modal is displayed with the form prefilled but it is (a) slow to open and (b) I don't think it is a nice way to do it. This is my current code views.py class ProjectDetailView(DetailView): model = Project template_name = "template.html" context_object_name = "project" def get_transactions(self): transactions = … -
Invalid encoding ISO-8859-1 : in django webhook for stripe
I found an error Invalid encoding: ISO-8859-1 , 404 Error during the test a webhook event named payment_intent.succeeded. Below is the views.py code for the webhook:(maybe I have errors in the code) img -
Django-debug-toolbar not showing error 403 forbidden
I was trying to use django-debug-toolbar but it doesnt show up at all, so i tried inspecting my page and i found out theres actually a erro 403 forbidden that is hiding the toolbar. I've tried everything i knew and searched on the internet like a maniac but what solved someone elses problem wasnt working for me. Sorry if the code is hard to understand, i'm still a novice programmer. If any other information is required pelase let me know settings.py: import mimetypes from functools import partial import dj_database_url from primeiraAplicacaoDjango import base # noqa from pathlib import Path from decouple import config, Csv import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) AUTH_USER_MODEL = 'base.User' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'collectfast', 'django.contrib.staticfiles', 'primeiraAplicacaoDjango.base', ] 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', ] ROOT_URLCONF = 'primeiraAplicacaoDjango.urls' TEMPLATES = [ { … -
Get the next seven days of the week in views - Django
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error. from datetime import datetime day = datetime.now() day_1 = datetime.now() + datetime.timedelta(days=1) day_2 = datetime.now() + datetime.timedelta(days=2) day_3 = datetime.now() + datetime.timedelta(days=3) day_4 = datetime.now() + datetime.timedelta(days=4) day_5 = datetime.now() + datetime.timedelta(days=5) day_6 = datetime.now() + datetime.timedelta(days=6) day_7 = datetime.now() + datetime.timedelta(days=7) It returns: type object 'datetime.datetime' has no attribute 'timedelta' -
Django server not refreshing pages after reloading
When I start the Django server it gives me proper output at first but the next time I make changes to code it does not reflect the changes even after reloading. I am usin react at the frontend. -
Django Beautiful Soup Parsing Data
Here is the XML data that I am trying to retrieve values from with Beautiful Soup. <students> <alerts> <medical> <description>All Nuts, Environmental allergies (rash): Sublingual Immunotherapy- Epi-Pen Asthma</description> <expires_date>NEVER_EXPIRES</expires_date> </medical> </alerts> </students> That value you I am trying to get is description . However, anytime I go over 3 instances of the .find() command it doesnt work. Here is my code. for student in soup.find_all('student'): #SETS VALUES WITHIN ALERTS ARRAY try: alert_medical = student.find("alerts").find("medical").find("description").get_text() except Exception as err8: print(err8,'Error in student.alert array.') Error I get in console is : object has no attribute 'find' -
Connection reset by peer after fetching file in django
i'm using django as a backend server and flutter as a mobile app. when i request a 3d model from my django app the message Exception occurred during processing of request from ('127.0.0.1', 49163) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 747, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer but when i open the same file from another online server it works! what should i do? -
How can i save data to text file from django form inputs?
I wanna save form input datas to text file and storage in local. But i am also new at django. Here is my sample codes... How can i save to form datas to text file? Thanks for help. My models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse #from datetime import datetime, date class Post(models.Model): #post_date = models.DateField(auto_now_add = True) soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="") soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="") soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="") soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="") soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="") soru6 = models.CharField(verbose_name='Birinci Evlilik', max_length=10000, default="") My forms.py file from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' #field = ('title', 'author') yapılabilir widgets = { # 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), # 'author': forms.Select(attrs={'class': 'form-control'}), # 'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), 'soru1': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), 'soru2': forms.TextInput(attrs={'class': 'form-control'}), 'soru3': forms.TextInput(attrs={'class': 'form-control'}), 'soru4': forms.TextInput(attrs={'class': 'form-control'}), 'soru5': forms.TextInput(attrs={'class': 'form-control'}), 'soru6': forms.TextInput(attrs={'class': 'form-control'}), my views.py file from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from .forms import PostForm from django.urls import reverse_lazy from django.db.models import Q from django.http … -
Django - how to correctly install library without pip in venv to work after deployment
According to this guide I successfully connected to Sybase database in my django project in virtual environment. After deployment in Apache the web writes this error message Environment: Request Method: GET Request URL: http://localhost:8080/ Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'sybase_app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/contextlib.py" in inner 51. with self._recreate_cm(): File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__ 150. if not connection.get_autocommit(): File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit 286. self.ensure_connection() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 130. self.connect() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__ 97. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise 658. raise value.with_traceback(tb) File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 130. self.connect() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect 118. conn_params = self.get_connection_params() File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params 517. root = Database.Root('PYTHON') File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__ 466. 'libdbcapi_r.dylib') File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in load_library 458. raise InterfaceError("Could not load dbcapi. Tried: " + ','.join(map(str, names))) Exception Type: InterfaceError at / Exception Value: Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib I edited /etc/apache2/envvars and appended a line export LD_LIBRARY_PATH=/opt/sqlanywhere17/lib64:/opt/sqlanywhere17/lib32:$LD_LIBRARY_PATH The error message changed to: Environment: Request Method: GET Request URL: http://localhost:8080/ Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', … -
Heroku Failing to launch, at=error code=H10 desc="App crashed" | django
This is the message I see in my logs. The code in my log file is also accurate as it is supposed to be. Also I have gunicorn installed in my VENV. Can someone help me deply this django app on heroku. -
Django error when accessing many to many through field of not managed model
I am getting this weird error which I am unable to sort out myself: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' Relevant parts of code are these: models.py: class Section(models.Model): type = models.IntegerField(blank=True, null=True) child=models.ManyToManyField( 'self', through='SectionParent', through_fields = ('parent_section_id', 'section_id'), ) class Meta: managed = False db_table = 'section' class SectionParent(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="m2m_child") parent_section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name="m2m_parent") class Meta: managed = False db_table = 'section_parent' views.py: def navigation(request, section_id=None): # Load species if no id is provided if not section_id: sections = Section.objects.using('app-db').filter(type=SectionType.speciesCategory.value[0]).first() # Load children of current section else: sections = Section.objects.using('app-db').filter(id = section_id).first() print(sections.child()) <-------------- ERROR HERE return HttpResponse("test") I tried to modify models.py many times including adding related_name, replacing 'self' with 'Section' and other things, changing name of the relationship (child), but nothing seems to sort this out. I think it might be related to the fact that the model runs over existing database (hence managed = false), as I never got such an error with migrations enabled. -
Django: While loop doesn't work correctly
i'm buildint a warehouse management application, i have a product model and an placement for each product, every placement has a volume, once i put a product in a placement, the volume of this placement must be reduced. The problem is when the app finds a placement for the product, the placement volume stay the same models.py class Emplacement(models.Model): address = models.CharField(max_length=25, blank=True) volume = models.DecimalField(max_digits=10, decimal_places=2, null=True) class Product(models.Model): name = models.CharField(max_length=100) quantity = models.PositiveIntegerField() is_disponible = models.BooleanField(default=False) volume = models.DecimalField(max_digits=20, decimal_places=2, null=True) emplacement = models.ForeignKey(Emplacement, on_delete=models.CASCADE, null=True) views.py def product_detail(request, pk): product = get_object_or_404(Product, id=pk) if request.method == 'POST': form = ValidateProductForm(request.POST, instance=product) if form.is_valid(): product = form.save(commit=False) product.volume = form.cleaned_data['longueur'] * form.cleaned_data['largeur'] * form.cleaned_data['hauteur'] product.is_disponible = True all_emplacements = Emplacement.objects.all() i=1 while i <= product.quantity: for emplacement in all_emplacements: if product.volume < emplacement.volume: product.emplacement = emplacement emplacement.volume -= product.volume i+=1 product.save() return redirect('print-barcode', product.id) else: form = ValidateProductForm(instance=product) context = { 'product': product, 'form': form, } return render(request, 'dashboard/product_detail.html', context) -
Connection refused setting up Nginx + Gunicorn/Django REST
I have a setup with Nginx as web server, Gunicorn as application server serving a Django REST API, all of this inside a docker container. Within the container, I launch gunicorn using this command: gunicorn --bind 0.0.0.0:8000 cdm_api.wsgi -t 200 --workers=3 and I am able to access to the API running for instance: curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:8000/api/concept However, when I run the same from outside the container I get: curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused Nginx is listening to port 80 inside the container which maps to port 8080 outside the container in localhost. I am able to access nginx but it seems nginx is unable to act as reverse proxy and redirect calls to 8000 (outside the container) to 8080 (inside the container). Here is my nginx conf file: server { listen 80; listen [::]:80; server_name 127.0.0.1; location /api/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_connect_timeout 360s; proxy_read_timeout 360s; } location / { root /usr/share/nginx/html; index index.html index.htm; } } Let me know if more information is needed. Thanks in advance! -
PYTHON 3.6.0 & DJANGO 3.5.0 'module' object is not iterable when running django website to the server
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these: Exception in thread django-main-thread: Traceback (most recent call last): File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file … -
Is there a way I can pass the context using return redirect in Django?
I wanted to pass the context using return redirect since using return render will send the post again when refreshing the page. This is my code for my return render: context = { 'file_path': file_path+'reviews_processed.csv', 'file_name': 'reviews_processed.csv', } messages.add_message(request, messages.SUCCESS, 'Processing done!') return render(request, 'vlookup/vlookup.html', context) and this is what I am trying to achieve: # return redirect(vlookup, context) Thanks! -
No such file or directory: 'profile_pics/img.jpg'
When a user attempts to upload a profile picture this error is displayed. However the image is successfully uploaded to the database and displayed in the app. I believe the error is something to do with the redirection after the form submits but I couldn't figure it out. I recently set my app up with aws s3 buckets so that might also have something to do with it but the images are successfully uploaded and pulled from the bucket so likely un related. view: def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'p_form': p_form } return render(request, 'users/profile.html', context) model: class Profile(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') .... def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.name) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Update Profile</legend> {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="action-btn" type="submit">Update</button> </div> </form> -
Dynamically add a particular field by button in django?
I have a form, and i need to keep a function like when user click on "Add button" a particular field needs to created again below it. Likewise new field should be created on each click. On a research i found that, we can use def __init__(self, *args, **kwargs): method can be used to do that, but how to do that for a particular field ? Am planning to follow this question, and it has function to create dynamic forms but i need dynamic fields not the whole form. And i cant use formsets, as its create whole form i belive ! -
Check if User sending request is in different model
I'm trying to create an API using the REST Framework. I ran into a little problem. I want to be able to get a list of events for a specific user by sending a request to the API. Is there a possibility to check if the User sending the request is in the team the event belongs to when an event list is requested? class Teams(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000, blank=True) Users = models.ManyToManyField(User, blank=True) class Event(models.Model): created = models.DateTimeField(auto_now_add=True) eventTime = models.DateTimeField() title = models.CharField(max_length=100, default='') description = models.TextField(max_length=1000, blank=True) group = models.ForeignKey(Teams, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) those are the realtionships between the models i implemented so far -
Django Model Inheritance to miultiple apps
class People(models.Model): # Utility Fields - auto fill # Timestamp # Base Fields # Methods, e.g save, get_absolute_url class Meta: abstract = True App clients: inherit from People model + its own Fields Vendor clients: inherit from People model + its own Fields Q1: Where should i place the code for People model, since i want to use it for more than 2 apps? Q2: Is this practice acceptable? Q3: Will it work in production environment efficiently? -
Does Django support custom language codes?
I need longer language codes for my project than two or five character long ones. By default Django support languages which have language code like "en" for English and "en-GB" for English (British). Is there way to use longer language codes (8 characters). This is needed for my project which uses Glottolog cataloque https://glottolog.org/glottolog/language for languages. I have tried add LANGUAGES = [("aari1239", "Aari"),] in project settings. With this language I can create po-files. But when I try to switch language with POST-request to /i18n/setlang/ default language English is set to language. -
Django DetailView don't show data in template
Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.[https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing][1] Here the code: models.py: class School(models.Model): name = models.CharField(max_length=125) principal = models.CharField(max_length=125) location = models.CharField(max_length=125) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=70) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) def __str__(self): return self.name views.py: class School_List(ListView): context_object_name = 'schoollist' model = School class School_Detail(DetailView): contex_object_name = 'schooldetail' model = Student template_name = 'basicapp/School_detail.html' detail.html: {% block content %} <h1>Site showing School Detail</h1> <div class="container"> <div class="p-5 text-white bg-dark rounded-3 container"> <p>Name: {{schooldetail.name}}</p> <p>Principal: {{schooldetail.principal}}</p> <p>Location: {{schooldetail.location}}</p> <h2>Student: </h2> {% for student in schooldetail.students.all %} <p>{{student.name}} who is {{student.age}} years old</p> {% endfor %} </div> </div> {% endblock %} Thank you -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'User.Users' (django)
I want to get User in shell, i have custom User and UserMnager models. this is my code- > from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): validate_email(email) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class Users(AbstractUser): username = models.CharField(max_length=30, unique=True,verbose_name=_("ზედმეტსახელი")) email = models.EmailField(_('ემაილი'), unique=True) first_name = models.CharField(max_length=30, verbose_name=_("სახელი")) last_name = models.CharField(max_length=50, verbose_name=_("გვარი")) mobile = models.CharField(max_length=9, verbose_name=_("მობილური")) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.get_full_name() My user model's name is User's' and manager's name is UserManager. i thinked this is problem but no. also i have AUTH_USER_MODEL = 'User.Users' in settings.py in shell i call --> from django.contrib.auth import get_user_model and after i run Users.objects.all() -> NameError: name 'Users' is not defined and User.objects.all() -> AttributeError: Manager isn't available; 'auth.User' has … -
Django retrieve filter value in views.py
I would like to prompt the user a dropdown box with all the values of a specific attribute, and retrieve this value in views.py to use it as function argument (to filter the output of a view function). Example: models.py class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) address = models.CharField(max_length=30) def __str__(self): return self.name views.py def users(request): users= User.objects.all() context = {'users': users} return render(request, 'users.html', context) users.html {% block content %} <div> <table style="width:100%" class="table table-hover table-sm table-stripped"> <thead class="thead-dark"> <tr> <th>Name</th> <th>E mail</th> <th>Address</th> </tr> </thead> {% for i in users%} <tr> <td>{{i.name}}</td> <td>{{i.email}}</td> <td>{{i.address}}</td> </tr> {% endfor %} </table> </div> {% endblock content%} I would like to display in my html a dropdown with all the User.name values, and when selected use the selected_user value as an argument in views.users() to filter the displayed table. Any idea on how to proceed ? -
Why is my django code for POST Method not working?
I am working on a django website and I am trying to receive data from the user through POST Method. The error message is : MultiValueDictKeyError at /prediction/ 'date1' Request Method: GET Why is the request Method still GET even though I have POST in my views.py? Views.py : from django.shortcuts import render from apple.models import predictions # Create your views here. def home_view(request): pre = predictions.objects.filter(date='2021-01-15') return render(request, 'homepage.html', {'prediction': pre}) def read(request): final_date = str(request.POST["date1"]) price = predictions.objects.filter(date=final_date) return render(request, 'results.html', {'price':price}) This is my 2nd HTML page Results.html : <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <title>Prediction Page</title> </head> <body> <h1>"The Predicted price for this date is:" + "{{price}}"</h1> </body> </html> <style> @import url(https://fonts.googleapis.com/css?family=Open+Sans); html { width: 100%; height: 100%; overflow: hidden; } body { width: 100%; height: 100%; font-family: 'Open Sans', sans-serif; background: #331952; color: #fff; font-size: 18px; text-align: center; letter-spacing: 1.2px; } </style> This is the main HTML Page - homepage.html ( from where 'date1' is coming from ) : <!DOCTYPE html> <html> <head> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <title>Apple Stock … -
Tried to update field with a model instance, <SimpleLazyObject:<<>>. Use a value compatible with CharField
I am trying to over ride the save method in my model to store the currently loged in user. I am using the django-current user to get the authenticated user. I wrote this code from django_currentuser.middleware import ( get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False) def save(self, *args, **kwargs): user = get_current_authenticated_user() self.uploaded_by = user super(Citation, self).save(*args, **kwargs) But I am getting this error Tried to update field professional.Citation.uploaded_by with a model instance, <SimpleLazyObject: <CustomUser: staff@gmail.com>>. Use a value compatible with CharField. Please suggest me what should I do as I want to store the currently loged in user in the model save method and aslo keep this field non editable.