Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to push to Heroku due to pkg-resources version
I've created my heroku repo. On an attempt to push to the master branch, the push fails due to pkg-resources. ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) (from versions: none) ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) ! Push rejected, failed to compile Python app. ! Push failed requirements (pip freeze > requirements.txt) asgiref==3.2.7 astroid==2.4.1 beautifulsoup4==4.9.1 dj-database-url==0.5.0 Django==3.0.6 django-bootstrap4==1.1.1 django-heroku==0.3.1 gunicorn==20.0.4 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 pkg-resources==0.0.0 psycopg2==2.7.7 pylint==2.5.2 pytz==2020.1 six==1.14.0 soupsieve==2.0.1 sqlparse==0.3.1 toml==0.10.1 typed-ast==1.4.1 whitenoise==5.1.0 wrapt==1.12.1 runtime uses python-3.6.9 -
Upload image tab is not displayed with django_tinymce and django-filebrowser
Task: set up django_tinymce and django-filebrowser for adding posts via admin panel. I have done all my best, and don't know the reason of missing upload tab for images. My set up: requirements.txt django==3.0.6 Pillow==7.1.2 django-bootstrap4==1.1.1 django-tinymce==3.0.2 django-filebrowser==3.13.1 django-grappelli==2.14.2 settings.py INSTALLED_APPS = [ 'filebrowser', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'blog', 'tinymce', 'grappelli', 'django.contrib.admin', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') AUTH_USER_MODEL = 'blog.User' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' TINYMCE_DEFAULT_CONFIG = { 'plugins': "advlist,autolink,lists,link,image,charmap,print,preview,anchor, searchreplace,visualblocks,code," "fullscreen,insertdatetime,media,table,paste,code,help,wordcount", 'theme': "silver", "toolbar": "undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | " "bullist numlist outdent indent | image removeformat | help", 'menubar': 'false', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, } urls: urlpatterns = [ path('admin/filebrowser/', site.urls), path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), path('tinymce/', include('tinymce.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Model is: class Post(models.Model): class PostType(models.IntegerChoices): BLOG = 1 NEWS = 2 DOG = 3 author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) post_type = models.IntegerField(choices=PostType.choices, default=PostType.BLOG) title = models.CharField(max_length=200) text = HTMLField() seo_title = models.CharField(max_length=200, blank=True) seo_desc = models.CharField(max_length=200, blank=True) dog_id = models.ForeignKey(Dog, on_delete=models.CASCADE, blank=True, null=True) breed = models.ForeignKey(Breed, on_delete=models.CASCADE, null=True, blank=True) published_date = models.DateTimeField(blank=True, null=True, editable=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) Read official docs … -
Django cannot find template stored at app_name/templates/app_name
I'm trying to build a recipe website. I have two apps, account (user auth stuff) and recipe. The templates for account are stored in account/templates/registration. Django can find these without a problem, my login, logout, register, etc views are working without an issue. However, in my recipe app I have one simple view so far: def index(request): return render(request, 'recipe/index.html') This file exists at recipe/templates/recipe/index.html. When I try to access it I get the following error: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/justinobrien/Desktop/recipeSite/website/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/justinobrien/Desktop/recipeSite/website/account/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/justinobrien/Desktop/recipeSite/env/lib/python3.6/site-packages/crispy_forms/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/justinobrien/Desktop/recipeSite/env/lib/python3.6/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/justinobrien/Desktop/recipeSite/env/lib/python3.6/site-packages/django/contrib/auth/templates/index.html (Source does not exist) It is clear it is not looking at the right path, I am just not sure how to tell it to look there? I also made a change to the DIRS part of the TEMPLATES variable, so that Django could find the base.html file I have stored at project_root/templates/base.html: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I am thinking that might be causing an issue. Thanks for … -
django MultiValueDictKeyError error, MultiValueDictKeyError at /signup 'username'
I created a signup page but when I tried to signup it gives a MultiValueDictKeyError error my HTML looks like <form action="/signup" method="post"> <div class="form-group"> <label for="username">User Name</label> <input type="text" class="form-control" id="username" placeholder="user name"> </div> <div class="form-group"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" placeholder="First name"> </div> <div class="form-group"> <label for="lname">Last Name</label> <input type="text" class="form-control" id="lname" placeholder="Last name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" placeholder="name@example.com"> </div> <div class="form-group"> <label for="pass1">Password</label> <input type="password" class="form-control" id="pass1" placeholder="Enter a password"> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> {%csrf_token%} <button type="submit" class="btn btn-primary">Submit</button> </div> </form> here is my views.py def handleSignup(request): if request.method == 'POST': #get the post parameters username = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] #check for error inputs # create the user myuser = User.objects.create_user(username,email,pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request,"account Created") return redirect('home') URLs are: urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('search', views.search, name='search'), path('signup', views.handleSignup, name='handleSignup') ] and the error looks like MultiValueDictKeyError at /signup 'username' Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 3.0.6 Exception Type: MultiValueDictKeyError Exception Value: 'username' Exception Location: /home/tanmoy/.local/lib/python3.6/site-packages/django/utils/datastructures.py in getitem, line 78 Python Executable: … -
Slicing strings in django-tables2 cells
I'm trying to slice strings in django-tables2. Here's my model: #models.py class Claim(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(default=timezone.now) member = models.ForeignKey(User, on_delete=models.CASCADE) Here's my view: #views.py class ClaimsView(tables.SingleTableView): table_class = ClaimsTable queryset = Claim.objects.all() template_name = "portal/claims.html" Here's my table: #tables.py class ClaimsTable(tables.Table): class Meta: model = Claim fields = ('id', 'product', 'member', 'date_added', 'text') And this is how I render the table in my template file: {# claims.html #} {% render_table table %} My goal is to display only the first 30 characters of text in the table for each claim. When I was building this table earlier without django-tables2, I did this with {{ claim.text|slice:":30" }}. How can I replicate this in django-tables2? I looked through the documentation and other posts here but I couldn't figure it out unfortunately. -
CSS class not applying style
In regard to the first CSS rule, it works when i use the 'p' tag by itself. When I apply the 'article' class with or without the 'p' tag, it doesn't work. Why is that? Also the 'hr' tag with the class of 'one' works (which means CSS file is working). This seems so basic. I don't understand why it isn't working. Any ideas? HTML <p class=article>{{ post.body|truncatewords:30|linebreaks }}</p> -- Also tried this <p class="article">{{ post.body|truncatewords:30|linebreaks }}</p> external CSS file p.article { color:red; } hr.one { border:none; height: 2px; background: #cec4c4; } -
Static file location setup problem of shuup ecommerce in djngo.conf file aws ec2 instance for testing purpose
I am facing problem to setup shuup ecommerce static files location in django.conf file in my aws ec2 instance for testing purpose. location /static/ { autoindex on; # could not understand what path should i write in here for alias; } Anyone can help me out, please. -
authenticate function in django always give's me none?
i have this problem .. authenticate function in django give me none while passing username and password here is my model from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class myUserExtensionManager(BaseUserManager): def create_user(self, username, email, TypeOfUser, password=None): if not username: return ValueError("user must have username") if not email: return ValueError("user must have an email address") if not TypeOfUser: return ValueError("user must have type novice or expert") user = self.model( username=username, email=self.normalize_email(email), TypeOfUser=TypeOfUser, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, TypeOfUser): user = self.create_user( username=username, email=self.normalize_email(email), password=password, TypeOfUser=TypeOfUser ) user.is_superuser = True user.is_admin = True user.is_staff = True user.save(using=self._db) return user # Create your models here. class UserExtensionApi(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(verbose_name='email', max_length=60, unique=True) TypeOfUser = models.CharField(max_length=6) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' # for using for login REQUIRED_FIELDS = ['email', 'TypeOfUser'] Manager = myUserExtensionManager() objects = myUserExtensionManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): # permation return self.is_admin def has_module_prems(self, app_label): # they permation if they admin return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, … -
Trying to combine Django inline-formset, django-select2 and django-dynamic-formset
I am trying to combine all mentioned in the title with always something missing. I've gone through all possible posts that I could find and still am not sure what to do. So I basically have two models, which are master-detail. When I use plain django stuff - everything is OK, but in detail model I have more than 10000 elements, and classic select field is impossible to use. So I switched to select2 through django-select2 module. I somehow managed to put everything together, but then had to add django-dynamic-formset to be able to dynamically add new rows if I need more than three that django renders by default. Again, I managed to make everything work, had some issues while I put everything together, but now I have two issues. If I leave this peace of code in jquery.formset.js: insertDeleteLink(row); I will get this message: jquery.formset.js:67 Uncaught ReferenceError: deleteButtonHTML is not defined at insertDeleteLink (jquery.formset.js:67) at HTMLTableRowElement.<anonymous> (jquery.formset.js:146) at Function.each (jquery-2.2.4.min.js:2) at n.fn.init.each (jquery-2.2.4.min.js:2) at n.fn.init.$.fn.formset (jquery.formset.js:124) at HTMLDocument.<anonymous> (1:92) at i (jquery-2.2.4.min.js:2) at Object.fireWith [as resolveWith] (jquery-2.2.4.min.js:2) at Function.ready (jquery-2.2.4.min.js:2) at HTMLDocument.J (jquery-2.2.4.min.js:2) If I remove it, delete links for rows are not generated, even though I have in … -
Execute commands from Python to Java jar
im trying to execute commands. So, lets say someone bought a product on the website that is hosted on the webserver, it will need to contact the game server saying smthing like this but coded: Webserver -> GameserverHey: Someone bought X Package and the command for X package is Y, may you execute it please? Gameserver -> Webserver: Ok, executing command... Finished successfully! Webserver -> Gameserver: Ok, thank you, marking order as finished. Django Rest API not an option since I know how it will work and it does alot of http requests and my hosting doesnt like it. RCON not an option since its less secure. To be more exact, im running a minecraft network. I can set up in which server it will get executed. -
How to transfer the pk of one model to another
I have two models task and subtask. First, a user is supposed to create a task, then the user can create subtasks for the previously created task. In the model for subtask, I created a foreignkey for task. The easy way would be to get task name(or id) front the user while making a new subtask to create the link between the two. But I want to do it the following way. User creates a task and is redirected to a page where all tasks are listed. The user selects a certain task and then is sent to a page that shows all subtasks for the selected task. There is a link to create a new subtask on this page and when the user uses this link, a new subtask can be created which automatically gets associated with the selected task. Forgive me if this question might is trivial. Thanks in advance!!! -
Post data from button value to views in Django
I have a button in my template and I need to post the value of the button to my views. Unfortunately, my request.POST returns 'None'. How can I retrieve the information from my HTML template? Thank you. My template: {% extends 'vocab/base.html' %} {% load crispy_forms_tags %} {% block content %} <form action="{% url 'card' %}" method="POST"> {% for document in documents %} <button type ='submit' value="{{ document.file }}" class='btn btn-outline-info' > {{document.file}} </button> {% endfor %} </form> {% endblock content %} My view: def card_view(request): if request.method == 'POST': context = {'request.POST':request.POST} return render(request, 'vocab/card.html', context) -
Django - Filter queryset by another queryset through related field
Suppose I have the two models below and I want to get a queryset of all developers that have games where the platform field matches a certain value. How would I go about that? class Developer(models.Model): name = models.CharField(max_length=100, default="Unknown") class Game(models.Model): name = models.CharField(max_length=300) developer = models.ForeignKey(Developer, related_name="games", on_delete=models.CASCADE) platform = models.CharField(max_length=40) I tried a few approached but can't seem to figure anything out that works. -
Middleware to make dictionary available to all views
I would appreciate if someone could help me by sharing a middleware code snippet that will allow me to create a dictionary that is accessible and updatable by all Django views. {‘a’ : ‘a’, ‘b’ : ‘b’, etc.} Thanks in advance. -
Django, virtual keyboard covers my textfield when opend
I got my Django website. When I want to type something in my textfield, the textfield gets squeezed together and it also gets covered by the virtual keyboard. I already searched here on stackoverflow but I only found solutions for iOS and no general solution. Thank you for reading! HTML <form id="field"action="" method="post" style="position: relative;"> {% csrf_token %} <div class="txtfield"> <input type="text" class="field" name="other_name" placeholder="username" maxlength="30" pattern="[a-z.0-9_]+" title="Please only write the username - No '@' or uppercase letters"/> </div> </form> .field{ border: 20px blue; border-radius: 10px; width: 35%; height: 8%; font-size: 280%; margin-top: 1%; } -
Use the modified admin template only for one Image app
Django 3.0.6 For one model I need a modified admin site template. Namely, I want to modify this template: admin/includes/fieldset.html I have copied the fieldset.html from django package directory and placed it like this: /my_project/image/templates/admin/includes/fieldset.html Here image is my application. It is this application that needs a modified admin template. The problem is that all other models also get this template. And the used template filters don't receive necessary params and explode. Documentation: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#set-up-your-projects-admin-template-directories Well, I got confused and fail to organize the necessary directories structure. Could you help me how to use the modified template only for one Image app. -
Best practice for for creating a user based token for 3rd party apps in Django
I have an application that needs users to give access to a 3rd party application. The requirements are that the 3rd party application has the same permissions as the user (acts on the user's behalf) The 3rd party application has no frontend, so the oauth2 redirection flow doesn't quite work. My initial thought was to create a model for 3rd-party applications and the User can add their own apps. By adding an app, the user would receive a app ID (or client id) and a app Secret (or client secret). The user gives the 3rd party app this information and it can request a Bearer Token once (After that, this combination of ID and Secret won't work). That Bearer Token will live for X seconds, but the application can refresh the Token with a Refresh Token it will get back as well. I realize this looks almost identical to Oauth2, but I haven't figured out how to achieve it with Django Oauth Toolkit at least. Any recommendations? Thanks! -
SSL Certificate works in browser but can't be verified by Postman
I have an AWS EC2 instance running Ubuntu 18.04, with python 3, Django, a bunch of project dependencies, Daphne running with ASGI, with a certificate by Let's Encrypt. Daphne is using port 8000 for HTTP and por 4430 for HTTPS, iptables is configured to redirect requests from port 80 to 8000 and from port 443 to 4430. Django is configured to enforce secure connections with SECURE_SSL_REDIRECT=True in the settings.py file. There's a "Site in Construction" temporary page being served, and it's properly accessible from every browser and every device I tested so far. If I explicitly type http, I get redirected to https and the certificate is accepted. Every browser I tested (Firefox, Brave, Chrome, Chrome for Android) says cert is good. Curl outputs the HTML content returned from the server. I don't know if it accepts the certificate or ignores it. The Problem Postman, however, says "Error: unable to verify the first certificate". Only works when I disable "SSL certificate verification", which doesn't answer my question: why Postman is unable to verify my Let's Encrypt certificate? I'm building an API that runs on the same server, using the same domain, and it's meant to be consumed by a mobile … -
Reset Password Option in Django Admin Login Page
I am trying to create an option to reset password at the login page of the Django dashboard. I would like there to be a link underneath the typical username and password fields that redirects the user to a reset password link where they are prompted to enter their phone number (not email ID) for the reset to take place. Is there a way to do that? I am new to using Django and have no clue as to how to approach this. -
How to show quiz results using Angular (and Django as backend)?
I'm writing a quiz program. Im using Django for backend and Angular for frontend. I don't know how to display quiz score in Angular. The score is calculated in Django and now it must me shown after submiting all the answers in Angular This is my code Django api.py ... class SubmitQuizAPI(generics.GenericAPIView): serializer_class = QuizResultSerializer permission_classes = [ permissions.IsAuthenticated ] def post(self, request, *args, **kwargs): quiztaker_id = request.data['quiztaker'] question_id = request.data['question'] answer_id = request.data['answer'] quiztaker = get_object_or_404(QuizTaker, id=quiztaker_id) question = get_object_or_404(Question, id=question_id) quiz = Quiz.objects.get(slug=self.kwargs['slug']) if quiztaker.completed: return Response({ "message": "Quiz zakonczony."}, status=status.HTTP_412_PRECONDITION_FAILED ) if answer_id is not None: answer = get_object_or_404(Answer, id=answer_id) obj = get_object_or_404(UsersAnswer, quiz_taker=quiztaker, question=question) obj.answer = answer obj.save() quiztaker.completed = True correct_answers = 0 for users_answer in UsersAnswer.objects.filter(quiz_taker=quiztaker): answer = Answer.objects.get(question=users_answer.question, is_correct=True) print(answer) print(users_answer.answer) if users_answer.answer == answer: correct_answers += 1 quiztaker.score = int(correct_answers / quiztaker.quiz.question_set.count() * 100) print(quiztaker.score) quiztaker.save() settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'knox', 'nested_admin', 'accounts', 'quiz', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), 'UNICODE_JSON': False } Angular quiz-detail.component.ts import { QuizzesService } from 'src/app/services/quizzes.service'; import { ActivatedRoute, Router } from '@angular/router'; import { Component, … -
How to use date picker with python django crispy form with bootstrap 4 ui
I am using python django crispy form from model with postgres database. My model has date field. The crispy form on ui is using bootstrap4 theme. And when i specify field as date in django form, the browser shows default date picker. it uses mm-dd-yyyy format. I just want to change date format to dd-mm-yyyy. I am open to all option with django form crispy with bootstrap 4 theme. -
make a record by slug
I have a model which has a slug, but when trying to register it does not allow it, generating the following error not null constraint failed: commentaries_commentarie.post_id. this is model: class Commentarie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) commentarie = models.TextField() created_at = models.DateTimeField(auto_now_add=True) this is urls: urlpatterns = [ path('<slug:slug>/', views.CommentarieCreateView.as_view(), name='add_commentarie'), ] this is view: class CommentarieCreateView(CreateView): template_name = 'commentaries/commentarie.html' model = Commentarie form_class = CommentarieForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return redirect('posts:post') also try to create the relation, getting directly by the kwarg but it generates an error, because it turns out that it is waiting for a pk object, and it slug it is generated correctly -
Creating template links in js
I'm creating microblogging site and I have a questiong about creating links. I have model Post with content_post - textField. When someone write @username or #tag then I want to create links there to user profile or specific tag. I wrote js script which looping over content words and when word contains @ or # then it replace word to <a href=/profile/${userId} and same for tags. It's working, but is it acceptable if I work with django? I mean good practices etc. I know it probably should be <a href={% url 'profile' user %}, but what if i'm out of variable scope? -
Django: Can't get current logged in user in DRF RetrieveUpdateDestroyAPIView
I want to return the reports written by the currently logged in author. I have defined a custom user model through AbstractBaseUser. I want to use RetrieveUpdateDestroyAPIView so that the author can retrieve as well as edit and delete reports. I defined these models: CustomUser, used as default user model and for authentication. ReporterProfile, users need to fill this model when they promote themselves as authors. . The Report model stores all submitted reports. The reporterprofile field in Report model has a ForeignKey relationship with the ReporterProfile model, which in turn, has a ForeignKey relation with CustomUser model. This is my view: class MyReportsView(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ReportSerializer(request.user) queryset = Report.objects.all() # need to get the currently logged in user With this, I am getting the error: NameError: name 'request' is not defined. This is my serializer: class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = ('reporterprofile', 'slug', 'title', 'column', 'summary', 'body', 'created', 'modified', 'published',) How do I fetch the reports submitted by the currently logged in user? -
Image isn't uploading to database from form django
images which are collected through the form are not uploaded to the database how to fix this issue please help me views.py class club(ListView): model = UserProfile template_name = "club.html" def post(self, *args ,**kwargs): if self.request.method == 'POST': self.request.user.userprofile.userphoto = self.request.FILES.get('image') self.request.user.userprofile.phone_number = self.request.POST.get('userphonenumber') self.request.user.userprofile.Isclubmem = True self.request.user.userprofile.save() return redirect('core:home') club.html <div class="container"> <form action="." method="POST"> {%csrf_token%} <b>Register:<br><br></b> Profile Pic: <input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage><br><br> Phonenumber: <input name="userphonenumber" type="number" placeholder="+91 9876543210" ><br><br> <input type="submit" value="submit" class="btn btn-success"> </form> </div> models.py class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) Isclubmem = models.BooleanField(default=False) one_click_purchasing = models.BooleanField(default=False) userphoto = models.ImageField(upload_to='images/', null=True) phone_number = models.IntegerField(default=False) usermoney = models.FloatField(default=0.0) def __str__(self): return self.user.username