Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I customize the display of username field of default User Model in Django ModelForm without extending User Model?
I have a default User Model, with which I have connected a ModelForm. In the ModelForm, I am accessing the username field of the default User Model. It works fine as usual, it shows the username(s) of the users. But I don't want it to just show username, instead I want to show the custom content of each user. I want to show first_name, last_name and username of the user in the following format: {first_name last_name - (username)} Current display of the username filed: user1 user2 user3 user4 # # # Desired display of the `username field: John Doe - (user1) Doni Marquart - (user2) Geoff Roberts - (user3) Alice Woods - (user4) # # # Does anyone know how can I accomplish it without extending the default User Model? Thanks -
Receiving Integrity Error from CustomUserModel form
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer. class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, … -
Django | Error when insert imageName with for into static url
Error when we want to insert image file name into static url. No all has imageName. Error: Invalid block tag Code: <img width="40%" src="{% static 'files/img/ {% for i in questions %} {% i.imageName %} {% endfor %} ' %}"> -
How to Create a Model for to complex Json Strucuture in django Rest Framework
I am using Latest Django 3.0 and Database: Postgress and frontend Angular using for this This is my example Json can we able to create for this Complex Json { 'id' : '1', 'name' : 'A Walk Amongst Friends - Canvas Print', 'handle' : 'a-walk-amongst-friends-canvas-print', 'description' : 'Officia amet eiusmod eu sunt tempor voluptate laboris velit nisi amet enim proident et. Consequat ', 'categories' : [ 'Canvas Print', 'Nature' ], 'tags' : [ 'canvas-print', 'nature' ], 'featuredImageId' : 1, 'images' : [ { 'id' : 0, 'url' : 'assets/images/ecommerce/a-walk-amongst-friends.jpg', 'type': 'image' }, { 'id' : 1, 'url' : 'assets/images/ecommerce/braies-lake.jpg', 'type': 'image' }, { 'id' : 2, 'url' : 'assets/images/ecommerce/fall-glow.jpg', 'type': 'image' }, ], 'priceTaxExcl' : 9.309, 'priceTaxIncl' : 10.24, 'taxRate' : 10, 'comparedPrice' : 19.90, 'quantity' : 3, 'sku' : 'A445BV', 'width' : '22', 'height' : '24', 'depth' : '15', 'weight' : '3', 'extraShippingFee': 3.00, 'active' : true }, Please Help On this to create a list of string and json objects in the django Thanks in Advance -
Why FormView not saving data within a DetailView?
I have a DetailView Based on a model ( A ) and on the same template I have a ModelFormView from a model B which has FK to model (A) The data from form doesn't get saved to the database. This is the DetailView: class LocationView(DetailView): template_name = "base/stocks/location.html" model = LocationStock def get_context_data(self, **kwargs): context = super(LocationView, self).get_context_data(**kwargs) context['form'] = OutsModelForm return context def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(LocationStock, id=id_) This is the FormView: class OutsAdd(FormView): form_class = OutsModelForm success_url = reverse_lazy('base:dashboard') def form_valid(self, form): return super().form_valid(form) This is the url.py: path('locations/<int:id>', LocationView.as_view(), name='location-detail'), path('locations/outs', require_POST(OutsAdd.as_view()), name='outs-add'), This is the template: <form method="POST" action="{% url 'outs-add' %}" > <div class="modal-content"> {% csrf_token %} {% render_field form.quantity placeholder="Quantity"%} {% render_field form.id_year placeholder="Year"%} {% render_field form.id_location placeholder="ID Location"%} </div> <div class="modal-footer"> <input class="modal-close waves-effect waves-green btn-flat" type="submit" value="Save"> </div> </form> The data gets POSTED in the /locations/outs but is not saving to the actual database.How can I save it ? -
Python / Dajngo App deployed using WSGI is getting stuck to generate the HTTP response
I'm using Heroku to deploy my application, I'm using gunicorn. For some requests, we're facing a really long time to generate the HTTP response, generated by the WSGI handler. The logs don't provide any insights and checking new relic I found this information: [Transaction chart][1] [1]: https://i.stack.imgur.com/9vt0p.png [Transaction breakdown][2] [2]: https://i.stack.imgur.com/P1f98.png [Transaction trace][3] [3]: https://i.stack.imgur.com/AJkKQ.png Do you know what could be happening? or do you have any advice about how to approach these kinds of problems? thanks! -
Django: render included template automatically
So I include 'navbar.html' in my 'base.html' Django template. I know that you can render it in each view function separately, but is there a way to create its own view function that will render it at its own without a call in urls.py? -
How to configure UPLOADS behind SSL
I am having an issue with retrieving uploaded images from my server. I have the following configurations: project/urls.py urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ path('adminx/', admin.site.urls), path('admin_app/', include('admin_app.urls')), path('app/', include('app.urls')), re_path(r'^(?:.*)/?$', include('app.urls')), # THIS ROUTE IS TO LOAD MY REACT APP ] settings.py MEDIA_ROOT = '/home/ubuntu/uploads' MEDIA_URL = '/uploads/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") Nginx config: upstream gunicorn{ server unix:/home/ubuntu/mysite/project.sock fail_timeout=0; } server { listen 443 ssl http2; server_name *.mysite.com; ssl_certificate /etc/ssl/private/ssl-bundle.crt; ssl_certificate_key /etc/ssl/private/briefing_key.pem; # path for static files root /home/ubuntu/mysite/project/project; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://gunicorn; } } server { # if a request is made on port 80 to your domain, it will be redirected if ($host = mysite.com) { return 301 https://$host$request_uri; } if ($host = www.mysite.com) { return 301 https://$host$request_uri; } listen 80; server_name *.mysite.com; return 404; } On my DEV rig, it all works perfectly. On my PROD rig, I can upload images, no problem. However, when I try to link to them, Django wants to spit out the HTML for my React app instead of the image. How can I adjust this so it pulls the image … -
Django dependant form fields from 2 forms
I've searched a bit but I can not find any problem/solution similar to what I have. I hope you can help me out. I know I will need to use Django's clean function, but I'm lost in what way I can get this to work. The answer will be pretty straight forward, but I'm oblivious. Now I have two models, ContractInfo and PersonInfo. class ContractInfo(models.Model): ... contract_nr = models.CharField(max_length=20, blank=False, null=False) person = models.ForeignKey(PersonInfo, blank=True, null=True, on_delete=models.CASCADE) class PersonInfo(models.Model): ... person_firstname = models.CharField(max_length=25, blank=True, null=True) person_prefix = models.CharField(max_length=15, blank=True, null=True) person_lastname = models.CharField(max_length=50, blank=True, null=True) They both have their own forms. I want to be able to either pick an existing name that is already registered, or make a new one if the name isn't registered yet. It has to be on the same page. My original views.py before I had this bright idea: def addcontract(request): addcontract = AddContractForm() addperson = AddPersonForm() if request.method == "POST": form = AddContractForm(request.POST) if form.is_valid(): contract = form.save(commit=False) contract.user = request.user contract.contract_warning = vehicle.contract_end-datetime.timedelta(days=30) contract.contract_active = True contract.save() return HttpResponseRedirect(reverse('contracts')) else: form = AddContractForm() else: form = AddContractForm() return render(request,'addcontract.html',{'addcontract':addcontract}) I've tried finding some examples, but either my searching as become worse or there … -
MakeMigrations persisted
Here's the model!! from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Migrations for 'blog': blog\migrations\0001_initial.py - Create model Post Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File Blockquote "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 182, in handle self.write_migration_files(changes) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 271, in serialize return serializer_factory(value).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 339, … -
How to manage slug in views.py django
I'm having trouble dealing with slugs: I have defined different slugs for every article in admin panel but on my website, if I type any random slug(e.g- fvrryybr,34,d4g5tg5) on any page of my app it takes me to the webpage of article function of views.py I don't know how to deal with as I a beginner in Django ____view.py___ def article(request,slug): allarticles = Article.objects.all() context = {'allarticles':allarticles} return render(request,"news/Home/tnews/blog-single.html",context) models.py class Post(models.Model): no = models.CharField(max_length=1000,primary_key=True) title = models.CharField(max_length=100) content = models.TextField() cover = models.ImageField(upload_to='images/') timeStamp = models.DateTimeField(blank=True) slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title class Article(models.Model): heading = models.CharField(max_length=1000) player = models.CharField(max_length=100) article = models.TextField() source = models.CharField(max_length=50) date = models.DateTimeField(blank=True) image = models.ImageField(upload_to='images/') def __str__(self): return 'Article on '+ self.player urls.py path("<slug:slug>",views.article,name='article') -
Is it really possible to build a tree user system in Django?
So i'm trying to create an app that allows me to add users (from here i will call them "clients") and some of these clientes will have the ability to add their own clients. Every client would have "virtual money" on their account and if they have the ability to add clients, they can transfer from his money to their clients. (This may be irrelevant, but you may have to know it just in case). So i create a model (Profile) that has one to one field so everytime i add an user, a profile will be created related to them. class Profile(models.Model): //This one creates a profile with one single users user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE) //Money users have in their accounts money = models.IntegerField(default=0, blank=True) // Some others fields i need like adress, etc //If this is True, this client can add his own clients that should be below him in the tree add_clients = models.BooleanField(default=False) // This client should have a parent, as im (superuser) will be the first user, i should be the parent of every client i add, but then if this client can add clients, the parent should be him instead of me, in … -
How can I pass in a char field that is basically a random string of 32 length characters in the django urls?
Ok, so I created a model which is basically this: class Code(models.Model): unique_id = models.CharField(default=get_random_string(length=32), max_length=32) def __str__(self): return self.unique_id This just creates a random string like "bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa." The thing is I'm trying to get the unique id to be passed through a url so that the creator can make their own poll. I went about it using this code: urlpatterns = [ path('', homepage, name='homepage'), path('create/<str:new_code>', create_poll, name='create_poll') ] Now, for the homepage html template, I have a button that does this: <button class="btn btn-outline-secondary btn-work"><a href="{% url "create_poll" new_code.unique_id %}">Create Poll</a></button> Whenever I click on it, django gives me this error: ValueError at /create/bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa Field 'id' expected a number but got 'bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa'. I know how to pass in pk and ids, but later on down the road, I'll need to create another template where people will enter a code and be redirected to questions that were made that relate to the unique id. What am I missing here? Sorry if this is kinda long, but I tried to read the django docs and looked up how to pass in model char fields to URl, but nothing helps. Thanks in advance -
Getting error when running heroku and django
followed a tutorial setting up an app with django and using heroku. I got everything uploaded, but am getting an error that prevents the app from fulling working. ModuleNotFoundError: No module named 'djangoproject' at=error code=H10 , status=503 gunicorn.errors.HaltServer: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers From research that I have done there is talk about Apache and python version conflict. I am using python: 3.7.7 and Apache: Server version: Apache/2.4.41 (Unix) my operating system is macos. Not sure how to fix this issue. -
how to add log traces for django's API dispatcher (django 1.11)
I have an old (Django 1.11) over complicated Django application with overlapping and funnily ordered url matching rules and I want to update it to newer Django versions and to simplify / refactor. For better understanding Id' like to navigate through the application (manually) and retrieve some traces Would it be possible to achieve following without having to add log statements in every view. I'd like to get traces telling me which rule was picked by the url dispatcher (and if possible, but not really necessary), which view with which parameter was called. I'm for example sure, that some rules can just be deleted as they're no more used. decorators, monkeypatches, whatever will do as long as I don't have to change all individual rules and all views to get my traces. -
How to redirect properly in Django URL , I am having issue in redirecting
Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" , Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code. Here is my URL.py of my app: from django.contrib import admin from django.urls import path,include from . import views from django.contrib.auth.models import User urlpatterns = [ path('login/', views.login, name='Login-Page'), path('register/', views.register, name='Registeration-page'), path('logout/', views.logout), path('verify/', views.verify, name='verification page') Here is my View.py for registration and profile: from django.shortcuts import render, redirect import requests from django.contrib.auth.models import User, auth from django.contrib import messages from datetime import date import smtplib import random from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request, "Username already taken") return redirect('accounts/register') elif … -
How choose random record from DB Django and render result into template?
User on index.html choose Theme question (q_category in models.py), tap on button and get Question(question in models.py). DB of questions already exists (300 questions and 12 themes). How to random question, which filtred by q_category and get result in template? I heard about .objects.order_by('?')[0], but i cant figured it out in my project. Models.py: class Questions(models.Model): question = models.CharField('Вопрос',max_length=200) q_category = models.CharField('Тема',max_length=200) class Meta: verbose_name = "Question" verbose_name_plural = "Questions" def __str__(self): return self.question Views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'cards/index.html', {}) index.html: {% extends 'base.html' %} {% block content %} <div> <h1>Question generator</h1> <p>Theme question</p> # choose q_category in models.py <button>Get your question</button> </div> {% endblock %} -
python: can't open file 'manage.py
i just finishing running the makemigration & migrate command it's OK but when i run python manage.py createsuperuser i receive this message : python: can't open file 'manage.py': [Errno 2] No such file or directory i did not know what is my mistake this is my python file: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() maybe (i'm not sure) i change some code or anything -
Django admin page not showing user models
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users. I have made custom models as shown below. Database is MySQL. models.py class User(AbstractUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) food_pref = models.CharField(max_length=10, default='veg') class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) restaurant_name = models.CharField(max_length=100, blank=False) -
waypoint infinite scroll loads the next page only once
Html: <div class="loading" style="display: none;"> <div id=circle2></div> <img class=virus id=incircle2 src="{% static 'icons\virus.png' %}" alt="virus"> </div> {% if entries.has_next %} <a class="infinite-more-link" href="?page={{ entries.next_page_number }}"></a> {% endif %} JS: var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); Well I found only one similar question and the recommended solution was to wrap the tag in span as: <span><a href="load-more.php" class="infinite-more-link">More</a></span> But that solution didn't work for me, thank you all for reading. -
TypeError 'builtin_function_or_method' is not iterable during heroku deployment
I'm trying to deploy my first django app to heroku. I have followed all the settings steps in the guide but I run into the following Traceback during deployment: if 'DATABASES' not in config: TypeError: argument of type 'builtin_function_or_method' is not iterable If I disable collectstatic then deployment runs without errors but as soon as I try to migrate my database it raises the same error. Can anyone help please? -
Django Sort By Model Function Not By Model Field
In the CourseForm I would like to sort by the longest total_duration, shortest total_duration, most total_lesson_views and least total_lesson_views. These are all Course parent class functions being done on the Lesson child class inside of the models.py file. Since these are not model fields to sort on, and instead are functions, it makes things a bit more challenging. How would you go about doing this? Courses App Forms.py: class CourseForm(forms.Form): sort = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'sort'}), choices = ([('','- - - - - - - -'), ('name','Ascending'), ('-name','Descending'),('-date','Newest'), ('date','Oldest'), ('-views','Most Popular'), ('views','Least Popular'), ]), required=False) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['sort'].label = "Sort:" Courses App Views.py: class CourseListView(ListView): model = Course template_name = 'courses/course_list.html' sortable_attributes = ['name', 'views', 'date'] def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): sort_query = self.request.GET.get('sort') if sort_query: match_query = sort_query if '-' not in sort_query else sort_query[1:] if match_query in self.sortable_attributes: qs = qs.order_by(sort_query) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form return context Courses App Models.py: class Course(models.Model): slug = models.SlugField() name = models.CharField(max_length=120) date = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) @property def total_duration(self): seconds_dictionary = Lesson.objects.filter(course=self).aggregate(Sum('duration')) sec = seconds_dictionary['duration__sum'].total_seconds() if sec >= 3600: return '%2d:%02d:%02d' % (int((sec/3600)%3600), … -
building a django app using docker: libpython3.8.so.1.0 no such file or directory
I'm trying to build my django app using Docker but I'm getting the following error while executing docker-compose up: /usr/local/bin/python: error while loading shared libraries: libpython3.8.so.1.0: cannot open shared object file: No such file or directory Actually python is not installed at /usr/local/bin Here's my docker-compose.yml file: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: Django/ command: python manage.py runserver volumes: - .:/code ports: - "8000:8000" depends_on: - db and my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip3 install -r requirements.txt COPY . /code/ -
How to update only specific fields in django model?
I want to update only specific fields in my model. This is my models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='teacher/images') phone = models.CharField(max_length=15) address = models.CharField(max_length=25) salary = models.DecimalField(max_digits=20, decimal_places=2) joindate = models.DateField(auto_now_add=True) status = models.BooleanField(default=True) And this is my forms.py class TeacherForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] class TeacherExtraForm(forms.ModelForm): class Meta: model = models.Teacher fields = ['phone', 'address', 'salary', 'status', 'image'] And this is my views.py def update_teacher(request, pk): teacher = models.Teacher.objects.get(id=pk) user = models.User.objects.get(id=teacher.user_id) form1 = forms.TeacherForm(instance=user) form2 = forms.TeacherExtraForm(instance=teacher) context = { 'teacher': teacher, 'user': user, 'form1': form1, 'form2': form2 } if request.method == 'POST': form1 = forms.TeacherForm(request.POST, instance=user) form2 = forms.TeacherExtraForm(request.POST, instance=teacher) if form1.is_valid() and form2.is_valid(): user = form1.save() # user.set_password(user.password) user.save(update_fields=['first_name', 'last_name', 'email', 'username']) f2 = form2.save(commit=False) f2.status = True f2.save(update_fields=['phone', 'address', 'salary', 'status']) return redirect('Teacher:teacher_index') return render(request, 'Teacher/update_teacher.html', context) Here I only want to update the first_name, last_name, email, username, phone, address, salary and status without affecting the password and image field. When I add the password and image field also, it works but I do not want to update password and image here. -
django csrf verification failed in android webview
I design a Django web app and then I create an android webview.in android webview, all functions work properly.in the Django web app, I use a payment gateway. payment gateway working in all browsers but it's not working in the android web view.android webview its return a forbidden(403) CSRF verification failed error.