Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access time control system for exams in Django-based online examination platform
I am a beginner in Django. Trying to create an online exam platform and prefer to use Bootstrap based frontend. Now I am very confused about the right way to implement the time inspection system for any test. Here, the time inspection system means, suppose that an experiment called "Bose Memorial 2nd Science Fest" will be held on 02-05-2021 at 8:30 am and the duration of the examination is 2 hours. Now my problem is, how can I ensure that the examinee can only enter the exam on 02-05-2021 from 8:30 am to 10:30 am? How can I implement a dynamic countdown timer on the question paper page so that the examinee can see the time limit? I know my problem is not directly code/error based. And it has a variety of solution strategies. So, you do not need to provide the full code. Please just give me some references or suggest some way so I can learn it by looking at the reference myself. -
problem with receiving emails with Django
i have a simple contact Page in my Django App that receive emails when user submit the form but when i check my Gmail it shows that i received email from my email, like i sent email from my email to myself Here is my views.py: def Contact(request): form=ContactForm(request.POST or None) if form.is_valid(): email=form.cleaned_data["email"] subject=form.cleaned_data["subject"] message=form.cleaned_data["message"] send_mail( subject, message, settings.EMAIL_HOST_USER, [email], fail_silently=False, ) messages.success(request,"your message has been sent successfully") context={"form":form} return render(request,"contact.html",context) and here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '**********' EMAIL_HOST_PASSWORD = '*********' EMAIL_USE_TLS = True EMAIL_USE_SSL= False EMAIL_PORT = '587' but when i check my Gmail it shows that i received email from my email, like i sent email from my email to myself -
How to make button to change CSS permanent between hrefs?
On my main base_generic.html I have put a button to change between two css. {% load static %} <link rel="stylesheet" type="text/css" href='{% static '/css/style.css' %}?{% now "U" %}'> <script> function toggleTheme() { var theme = document.getElementsByTagName('link')[0]; if (theme.getAttribute('href') == '{% static '/css/style.css' %}?{% now "U" %}') { theme.setAttribute('href', '{% static '/css/style_access.css' %}?{% now "U" %}'); } else { theme.setAttribute('href', '{% static '/css/style.css' %}?{% now "U" %}'); } } </script> <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Title to change</title>{% endblock %} </head> <body> Accessibility switch:<br /> <button onclick="toggleTheme()">Switch</button> <br/> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) -->{% endblock %} </body> </html> And it works fine, but when you chance css and click href to another url, it goes back to default css. How can I make it work, so if one person click the change button, then css is persistent? F.e. if I click 'switch css' button on login page it switches is to second css, but once I am logged in (and href'fed to different url), it goes back every page to original one. I would like it to work in a … -
problem in django:unable to create process
I installed django successfully and created a new project with the command: .\django-admin startproject myproject It worked fine but when I try to run the server via the command: py manage.py runserver it throws an error telling me "unable to create process using 'C:\Users\Apanoup Edward\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' " I have python 3.9 installed and django 3.2 as well what is the issue .. can any one please help? -
Django can't to open shape_predictor_68_face_landmarks.dat. RuntimeError: Unable to open shape_predictor_68_face_landmarks.dat
My Django application can't open a shape_predictor_68_face_landmarks.dat in views. But in simpy .py file this code works. Please help to solve this problem. I have tried to use a threads and asycno, but it is doesn't work. class Main(View): def post(self, request): images = Images.objects.all() image = request.FILES.get('image') name = request.POST.get('name') if not image and not name: # images = Images.objects.all() return render(request, 'find_photo/main.html', context={'images': images, 'result': True, }) group = Groups.objects.create(photo=image, title=name,) find_photos("../" + group.photo.url) # x = threading.Thread(target=find_photos, args=("../" + group.photo.url,)) # x.setDaemon(True) # x.start() # # print(x.is_alive()) # mypath = '/find_photos/' # onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] # # for file in onlyfiles: # print(file) # group.find_images.add(file) # group.save() return render(request, 'find_photo/main.html', context={'images': images, }) find_photos function: def find_photos(image): sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") face_rec = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat') detector = dlib.get_frontal_face_detector() min_distance = 2 f1 = get_face_descriptors(image, sp, face_rec, detector)[0] files = getfilelist(dirpath) flag = 0 for f in files: flag = flag + 1 print('Анализ ' + f + ' - ' + str(flag) + ' фото из ' + str(vsego)) if os.path.exists(f): try: findfaces = get_face_descriptors(f) print('На фото: ' + str(len(findfaces)) + ' лиц') for f2 in findfaces: if (f2 != []): euc_distance … -
Multiply two fields in django
I have two different models class Part(models.Model): partno = models.CharField(max_length=50) price = models.PositiveIntegerField(default= 0) tax = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) class PurchaseOrder(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) po_quantity = models.PositiveIntegerField(default= 0) amount = models.PositiveIntegerField(default= 0) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) I'd like to multiply price from Part with po_quantity and result show in the amount. e.g amount = price * po_quantity Can someone assist me to solve this? -
receive pdf from an api instead of pdf in unicode format Python/Django
I have a problem when consuming an API that returns a pdf to me, said pdf is returning it to me I think in unicode format, the point is that I can't make it simply return the normal pdf, that is, put it in some view or method so that a normal pdf is simply downloaded to the client, I don't know if I explain it well def volante_individual_empadronamiento(request): if request.method == 'POST': document_identity = request.POST.get('identification') url = f"https://pre-interpublicaapi.interpublica.es/api/padron/volanteindemppdf?filtros[0].Nombre=NumDocumento&filtros[0].Valor={document_identity}&filtros[1].Nombre=TipoPlantillaPadron&filtros[1].Valor=10" token_value = access_token() print(token_value) payload={} headers = { 'Authorization': f'Bearer {token_value}' } response = requests.request("GET", url, headers=headers, data=payload) volante_individual = response.text print(volante_individual) return render(request, 'volante_individual_empadronamiento.html') -
Django raise ValidationException on id field when testing abstract model
I have an abstract django model like this: from django.db import models class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True When testing this class using following code: from django.test import TestCase from django.db import models from core.models import BaseModel class BaseModelTest(TestCase): def test_1(self): class SimpleClass(BaseModel): name = models.CharField(max_length=10) simple = SimpleClass(name="test") simple.save() simple.full_clean() ... I get following error: django.core.exceptions.ValidationError: {'id': ['“6072d8ce3c23022d0694ae8e” value must be an integer.']} I'm using mongodb as my database. There is no such error when I delete abstract = True. -
Django 2FA works locally but fails (silently) on server
The Problem I need to implement two factor authentication for a Django project. I am using Django Two-Factor Authentication which works just fine locally both with Google Authenticator and our own SMS gateway. The issue occurs when I publish the app to the test server. The login works as normal but when I fill inn the token it will simply redirect me back to the initial login step to fill inn my credentials again. It does not give me any error messages in the ui and, as far as I can see, none in the logs either. Don't know if it's relevant but the app is running as a Docker Swarm service on the server. What I have tried Due to the lack of feedback and knowledge of the 2FA library as well as the OTP-library I don't really know where to start. I'm pretty sure the settings are as good as identical between my local machine and the test environment. The package version are the same. I even made sure the time and timezones are identical between my machine and the server. Looking in the database in the tables for the OTP library the failure count is 0 and … -
Pass variable value to form field
How can I pass the value of a variable to the value attribute of a field in my form? I have tried overriding the init method but I can't get it to work. This is my code. models.py: class Profile(models.Model): user = models.OneToOneField(UserManegement, related_name='user', on_delete=models.CASCADE) avatar = models.ImageField(upload_to=custom_upload_to, null=True, blank=True) first_name = models.TextField(user, null=True, blank=True) last_name = models.TextField(user, null=True, blank=True) phone = models.TextField(user, null=True, blank=True) forms.py: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar', 'first_name','last_name', 'phone'] widgets = { 'avatar': forms.ClearableFileInput(attrs={'class': 'form-control-file mt-3'}), 'first_name': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder': 'Nombre'}), 'last_name': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder': 'Apellidos'}), 'phone': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder':'Teléfono'}), } In this case, I would like to add the first time the form is loaded, the first_name field with the value of request.user.first_name. Thank you very much! -
passing data to JavaScript via python
I wanted to make my first frontend project by making a website which can take some inputs e.g. ticker symbol, interval, period and observation. after you give the website these inputs it would need data from a python file which scrapes the data from yahoo finance after it got the data I want it to send it to my JavaScript file which I use to generate the graph. I then want the js file to send the graph to my website which can show the client data about the stock My problem is that I don't understand how all these files can communicate. Here is all my code: python: import pandas as pd import yfinance as yf import matplotlib.pyplot as plt def stock_data(stock, period, interval, observation): ticker = yf.Ticker(stock) ticker_history = ticker.history(period, interval) sf = ticker_history[observation] df = pd.DataFrame({'Date':sf.index, 'Values':sf.values}) x = df['Date'].tolist() y = df['Values'].tolist() HTML: <html> <head> <link rel="stylesheet" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.2/helpers.esm.min.js"></script> </head> <body> <div class="options"> <div> <select> <option value="Period">Period</option> <option value="1 day">1 day</option> <option value="5 days">5 days</option> <option value="1 month">1 month</option> <option value="2 month">2 month</option> <option value="3 month">3 month</option> <option value="6 month">6 month</option> <option value="1 year">1 year</option> <option value="2 years">2 years</option> <option value="5 years">5 years</option> <option value="10 … -
Django messages + bootstrap toast. How to make it work?
Trying to get bootstrap popup and django messages to work. The problem is that I do not understand how to do it correctly so that if there is a message in the context, it would be displayed in the upper right part of the site. Documentation: https://getbootstrap.com/docs/4.3/components/toasts/ Django v3.1.6 and Bootstrap v4.5 In the static files of the project there is bootstrap.bundle.js, it is also included in the base template. I'm not good at django in layout, so I will be very grateful for the most detailed answer. -
Django alternative for model.Choicefield
I have in my template a TextInput field, which shows customer name and not the ID for choosing a customer, but if I have 200 Customers a dropdown field is not working for me, so I have a disabled text field and over another form I can choose the customer and it works, but now the form is not valid because the form need the ID is there a alternative? my form: class EditOrderForm(forms.ModelForm): OrderNo = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True, 'readonly': True})) Created_Date = forms.DateTimeField(widget=forms.DateTimeInput( attrs={'class': 'form-control', 'data-provide': 'datetimepicker', 'data-time-format': 'dd.mm.yyyy - HH:M', 'data-date-autoclose': 'true', 'readonly': True}, format='%d.%m.%Y %H:%M'), initial=datetime.datetime.today) Customer = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'autofocus': True, 'readonly': True})) my model: class Orders(models.Model): ID = models.AutoField(primary_key=True) OrderNo = models.IntegerField('OrderNo', blank=False, null=False) Customer = models.ForeignKey('Customers', on_delete=models.DO_NOTHING) -
Fetching Values from models including duplicates
I have my models designed like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) The data stored in the authors field is like this: authors Author A Author A Author B Author B Author C Now in my views.py file I am trying to query the data like this: allAuthors = Books.objects.all() for a in allAuthors(): print(a) The output displayed is : Author A Author B Author C Why are the duplicates not displayed? How can I show the duplicates as well? Sorry if I am missing the obvious. Thanks for your time in advance. -
Django template not rendering at all
I have all my django views and templates working, however, when i tried to make this new, simple one it simply wouldn't render. views.py: def ListRefView2(request): return render(request, "reference/test.html", context) urls.py: from django.urls import path from .views import ( ListRefView, ListRefView2, CreateRefView, DetailRefView, UpdateRefView, DeleteRefView, ) urlpatterns = [ path('', ListRefView), path('test2/', ListRefView2), path('<str:slug>/delete/', DeleteRefView), path('<str:slug>/edit/', UpdateRefView), path('<str:slug>/', DetailRefView), path('test2/', ListRefView2) ] test.html <h1>Hello </h1> I am trying to get "Hello" to show up via the "ListRefView2" view -
Adding to multiple foreign keys at once from Django Admin
I have this FAQ model which has a foreign key to Organization. `# Create your models here. class Faq(BaseModel): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) faq_title = models.CharField(max_length=100) faq_content = models.CharField(max_length=1000) faq_category = models.CharField(max_length=50) class Meta: unique_together = (("organization", "faq_title"),)` From the Django Admin I can add an FAQ to an Organization. How can I make it so that I can add to all Organizations at once in the Django Admin? The goal is to have some FAQ's available to all organizations, and some FAQ's to just one or two organizations. -
Django runserver not working after adding channels
I get an error when trying to run my server. Error: PS C:\Programming\Python\Django\Messager> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 11, 2021 - 18:17:54 Django version 3.1.7, using settings 'Messager.settings' Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\routing.py", line 28, in get_default_application module = importlib.import_module(path) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'messager' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run application=self.get_application(options), File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\management\commands\runserver.py", line 132, in get_application return StaticFilesWrapper(get_default_application()) File "C:\Users\lazyb\AppData\Local\Programs\Python\Python38\lib\site-packages\channels\routing.py", line 30, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION … -
How to set password to user in database directly?
I have a website for university timetable connected to microsoft sql server, there I have django table auth_user. Users can't register by themselves, university provides them with username and password. So in the table auth_user I have to fill data manually, but how can I fill the field which is responsible for password since it has to be hashed? I found only way to set password is to log in as admin, and change passwords in admin site, but that is not quite correct in terms of working with database as if I had to fill more than 100 students, it would be tiresome to do so. Maybe there is another approach to fill passwords directly in the database? -
Chaining Queries in Django
I am building a data processing app which allows user to upload multiple excel sheets, which is processed and returned back to user. I have created 3 models - 1st model is overall, 2nd model is capturing individual excel workbooks, in the 3rd model excel workbooks are opened and data for each excel sheet (sheets within workbooks) is captured. I need advise on 3 things: Is my model structure efficient given that users will be uploading multiple excel sheets? Given that users may do upload multiple times in a day, how do I retrieve the latest batch of files for processing? I need to take user inputs against each sheet uploaded by user (3rd model) in a single view while parallelly showing a preview of the table to the user? Please help with your opinions. class UserUpload(models.Model): number_of_workbooks = models.IntegerField(blank=True,null=True) file_size = models.FloatField(blank=True,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE,null=False,blank=False) multiple_sheets = models.BooleanField(blank=False,default=False) var_1 = models.BooleanField(blank=False,default=False) class FileUpload(models.Model): file_field = models.FileField(blank=False,upload_to=user_directory_path) userupload = models.ForeignKey(UserUpload,related_name='user_uploads',on_delete=models.CASCADE) class FileSheetData(models.Model): fileupload = models.ForeignKey(FileUpload,related_name='file_sheets',on_delete=models.CASCADE) sheetname = models.CharField(blank=False,max_length=256) var_2 = models.BooleanField(blank=False,default=False) var_3 = models.PositiveIntegerField(blank=False,default=0) -
Is there any way to get request data in django serializer?
This is the sample view where I am taking some query_params and I want to access the same in serializer which will I use in this view accordingly. class SomeApi(APIView): def get(self, request): username = request.query_params.get('username') page = request.query_params.get('page') phone = request.query_params.get('phone') if username and page and phone: return Response({'message':'some message'}, status=status.HTTP_200_OK) return Response({'message':'error'}, status=status.HTTP_400_BAD_REQUEST) This is a sample Serializer where I want to get query_param phone if available and write some logic to return an extra method field. class SomeSerializer(serializers.ModelSerializer): class Meta: model = Some fields = '__all__' def get_isPhone(self, obj): phone = ??? #HERE I WANT TO GET phone query_params which is passed in API call if phone: return phone else: return 0 -
How to display the foreign key and many-to-many fields in Django admin `list_display`?
How to display the foreign key and many-to-many fields in Django admin list_display? models.py: class Book(models.Model): title = models.CharField(max_length=150, blank=False) class Character(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='character') name = models.CharField(max_length=50) class Author(models.Model): book = models.ManyToManyField(Book, related_name='author') name = models.CharField(max_length=50) admin.py: class BookAdmin(admin.ModelAdmin): list_display = ('title', 'characters', 'authors') def characters(self, obj): ??? def authors(self, obj): ??? -
No 'Id' in the results of the Orderdict although id field is present in the serializers in Django Rest Framework
I tried to create an update api for Orders but in the result of the postman, I am getting this error KeyError at /api/updateorder/260 'id' I have put the id field both in OrderUpdate Serializer and OrderItemUpdateSerializer as you can see below. Also, I have printed the validated_data.pop('order_items'). In the result of print, I get Orderdict which has no id field. I don't know why id is not showing. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): return sum([_.price for _ in self.order_items.all()]) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property def price(self): total_item_price = self.quantity * self.order_variants.price return total_item_price My serializers: class OrderItemUpdateSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = OrderItem fields = ['id','order','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 class OrderUpdateSerializer(serializers.ModelSerializer): order_items = OrderItemUpdateSerializer(many=True) billing_details = BillingDetailsSerializer() class Meta: model = Order fields = ['id','ordered','order_status','order_items','total_price','billing_details'] def update(self, instance, validated_data): instance.order_status = … -
Cloudinary shown incorrect url in Django
I have created a model with upload img to cloudinary but shown the incorrect link in django template which has 2 https:// inside of it. Please help. models.py: class Product(models.Model): img = models.ImageField(upload_to='product', height_field=None, width_field=None, max_length=100, default='https://res.cloudinary.com/dgdhnbsae/image/upload/vxxxx/product/xxxx.jpg') def get_img(self): return f"{'/media/product/'+self.img}" I have set the related configuration according to the tutorial setting.py: INSTALLED_APPS = [ xxxx 'cloudinary_storage', 'cloudinary', ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'xxxx', 'API_KEY': 'xxxxx', 'API_SECRET': 'xxxxx' } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' templates: <div class="featured__item__pic set-bg" data-setbg="{{ product.img.url }}"> However, turned out: https://res.cloudinary.com/xxxx/image/upload/v1/media/https://res.cloudinary.com/vxxxx/image/upload/xxxxx/xxxxx.jpg there has two https in side the url -
Store the last edited name of user after edited
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to store the last edited name of the user after edited the name. I mean, I want to store previous name after edited the new name. BUT when i try to access the name then it shows the updated name. I also tried by saving previous name while editing but it didn't worked for me. I also tried Tracking Who Made the Last Changes to a Model BUT i don't know how it works. Any help would be Appreciated. Thank You in Advance. -
Django Save image without using Django Forms?
I am trying to save the image without using Django forms in the media folder. The image should save in the media\seller_profile folder and its path has to be entered in a database like seller_profile\abc.png but somehow I am getting only abc.png missing seller_profile. Models.py class SellerProfile(models.Model): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, default=None, null=True) seller_profile_picture = models.ImageField(upload_to='seller_profile', default="seller_profile/empty_profile.png") def __str__(self): return self.email Views.py def profile(request): if request.method == "POST": profile_data = SellerProfile.objects.filter(email = str(request.user)).update( first_name = request.POST.get("First name"), seller_profile_picture = request.FILES["seller profile picture"], ) print("object File --->", request.FILES["seller profile picture"]) return redirect("/seller/profile") else: user_data = SellerProfile.objects.filter(email=str(request.user)) if len(user_data) == 0: SellerProfile.objects.create(email = str(request.user)) data_entered = {"First name": "Value not Provided"} else: data_entered = dict() data_entered["First name"] = user_data[0].first_name return render(request, "seller/profile.html", {"data_entered":data_entered}) seller/profile.html {% extends 'general/layout.html'%} {% block body %} <div class="container"> <div class="jumbotron"> <form method="post" enctype=multipart/form-data> {% csrf_token %} {% for attribute, placeholder in data_entered.items %} <div class="form-group"> <dt><label for="{{attribute}}">{{attribute}}</label> <dd><input class="form-control" id="{{attribute}}" name="{{attribute}}" type="text" placeholder="{{placeholder}}" required> </dd> </div> {% endfor %} <dt><label for="seller profile picture">Profile Picture</label> <dd><input class="form-control" id="seller profile picture" name="seller profile picture" type="file" required> </dd> </dt> <div class="form-group text-center"> <p> <input class="btn btn-primary " type="submit" value="Update"> </p> </div> </form> </div> </div> {% endblock%}