Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication to my app does not work when I deploy on heroku
Here is my code def connexion(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password"] matricule = form.cleaned_data["matricule"] user = authenticate(email=email, password=password) if user is not None: user = User.objects.get(email=email) if Agent.objects.filter(user=user, matricule=matricule).exists(): agent = get_object_or_404(Agent, user=user) profile = agent.profile if user.is_active: login(request, user) request.session["profile"] = profile return redirect(reverse("elec_meter:home")) else: messages.add_message(request,messages.WARNING,"Votre profile n'est pas " "encore activé! Veuillez contacter l'administrateur.") return render(request, "elec_meter/login.html", {"form": form}) else: messages.add_message(request,messages.ERROR,"Utilisateur non existant !") return render(request, "elec_meter/login.html", {"form": form}) else: messages.add_message(request,messages.ERROR,"Utilisateur non existant !") return render(request, "elec_meter/login.html", {"form": form}) else: form = LoginForm() return render(request, "elec_meter/login.html", {"form": form}) This is the code that allows authentication to my app. It works very well locally. But when I deploy the application on heroku it doesn't work anymore. It always sends me back to the login page without any messages. Sometimes it sends me a 403 forbidden while I have {% csrf_token%} in the form. Are there any configurations to add ? How can I solve this problem ? -
Many-to-many relationship between 3 tables in Django
I have the following models: class Project(models.Model): project_name = models.CharField(max_length=50) project_users = models.ManyToManyField('Users.UserAccount', related_name='project_users', blank=True) .... class UserAccount(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) .... class Discipline(models.Model): name = models.CharField(unique=True, max_length=27, choices=discipline_choices) The DB table for project_users looks like this: *--------*----------------*---------------------* | ID | project_id | user_account_id | *--------*----------------*---------------------* I want to have an extra relationship in project_users field/table with the Discipline model. Is that possible in Django? I have been looking at intermediary-manytomany relationships in Django, but that's not exactly what I want. In my application, there are a set amount of disciplines, and what I'm trying to achieve is to give each user multiple disciplines in a single project. So something like this: *--------*----------------*---------------------*-------------------* | ID | project_id | user_account_id | discipline_id | *--------*----------------*---------------------*-------------------* Is this possible? -
Python (Django) how to assign a default value in case of error
Hey I'm using django in a project, using a POST method, the view in Django receives data, it works fine if the data is received but if no data is received I want to assign a default value instead of getting an error here is my code. I tried to use the if assignement but it doesn't work. @api_view(['POST']) def getPacsPatients(request): data = json.loads(request.body.decode('utf-8')) if request.method == 'POST': PatientName = data["patientName"] if data["patientName"] else "*" #it works fine if data["patientName"] is present, but if not I get an error -
How can i use Exists with WHEN CASE in Django
I am trying to write ORM in Django something like this: DECLARE @vari1 INT = 2 DECLARE @vari2 INT = 0 SELECT *, CASE WHEN EXISTS (SELECT B_id FROM dbo.Subscription WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) THEN @vari1 ELSE @vari2 END) FROM dbo.Subscription; -
How to authorize IoT device on Django channels
I have a real-time API based on Django channels and IoT devices that expects commands and data from API. The IoT devices are not related to any kind of user model and have only the unique UUID as an identifer. How to implement the authorization middleware with the ability to reject some of the devices if they are compromised? -
How to create a table using raw sql but manage it using django's ORM?
I am using django for my backend, and I want to use table partitioning and composite primary key for postgresql, but, django's ORM does not support these features yet (or at least I couldn't find them). So, I have decided to use raw sql code in django, but I would like to manage it using django's ORM (only the creation would be in raw sql, and this table would have many-to-many relationships with other tables). I would like to know if this is possible and if yes, what would be the best way to do it? Thank you in advance for your time. -
Django. How to return error 500 without sending mail to admins
I am using standard error handling in production - if there are server errors I am getting mails. However, on certain APIs I want to have a response with HTTP code 500 as part of the "valid flow". (It's done for some learning purposes) So my view for that looks like this: from rest_framework.response import Response from rest_framework import status def give_me_error(request): return Response("This is expected error", status=status.HTTP_500_INTERNAL_SERVER_ERROR) And what I want is not to get email of this particular response (because I wanted it to be 500) I've also tried this way: from django.http import JsonResponse def give_me_error(request): return JsonResponse({'error': 'expected error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But it also generates mail. Is there a way to have a view returning error 500 that will not trigger e-mail send? (without disabling the e-mail functionality system-wide) -
Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag?
I'm upgrading mezzanine/django application form python 2.7/Mezzanine 4.3.1 to python 3.7/mezzanine 5.0.0. When when running the application in 3.7/mezzanine 5.0.0. I get the error django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag? I guess it must come from the file myProject/myProject/templates/admin/base_site.html: {% overextends "admin/base_site.html" %} {% block extrahead %} {{block.super}} <style type="text/css"> div.cke_chrome { margin-left: 130px; } </style> <link rel="stylesheet" href="{{ STATIC_URL }}css/statfi-editor.css" /> <script src="{{ STATIC_URL }}js/statfi_csrf.js"></script> {% endblock %} since if I remove the 1st line {% overextends "admin/base_site.html" %} the borwser shows empty admin/-page. I tried to fix by adding buildins key into TEMPLATES setting: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'builtins': ['overextends.templatetags.overextends_tags'], } }, ] but that would require installing overextends-module. When installing it I got: django-overextends 0.4.3 requires django<2.0,>=1.8, but you have django 2.2 which is incompatible. Are there any other means to solve the problem than just downgrading both mezzanine and django version in order to get that overextends module into use ? -
Django - Profile() got an unexpected keyword argument 'username'
I'm trying to make when a user access the website url / username e.g http://127.0.0.1:8000/destiny/ but it throws the Profile() got an unexpected keyword argument 'username' error. I have tried adding a username argument in my profile views. I also tried geting the username when the user signup, to use it in the profile view but it still doesnt work. i'm a django newbie that's why i don't really know where the error is coming from views.py def UserProfile(request, username): user = get_object_or_404(User, username=username) profile = Profile.objects.get(user=user) url_name = resolve(request.path).url_name context = { 'profile':profile, 'url_name':url_name, } return render(request, 'userauths/profile.html', context) #register view def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.filter(active=True) categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): new_user = form.save() username = form.cleaned_data.get('username') messages.success(request, f'Hurray your account was created!!') new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return redirect('elements:home') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) first_name = models.CharField(max_length=1000, null=True, blank=True) last_name = models.CharField(max_length=1000, null=True, blank=True) email = models.EmailField(null=True, blank=True) phone = models.IntegerField(null=True, blank=True) bio = models.CharField(max_length=1000, null=True, blank=True) aboutme = … -
richtext_filters in Mezzanine 5.0.0
I've been trying to upgrade a mezzanine/django application form python 2.7/Mezzanine 4.3.1 to python 3.7/mezzanine 5.0.0. When running my application in python 3.7/mezzanine 5.0.0 I get the error "django.template.exceptions.TemplateSyntaxError: Invalid filter: 'richtext_filter'", which didn't appear in python 2.7/Mezzanine 4.3.1. What can I do to fix this ? That filter has been used for instance in richtextpage.html: {% extends "pages/page.html" %} {% load mezzanine_tags %} {% block base %} {% editable_loader %} {% if has_site_permission %} {% include 'includes/editable_toolbar.html' %} {% endif %} {% editable page.richtextpage.content %} <div id="blankko_page"> {{ page.richtextpage.content|richtext_filters|safe }} </div> {% endeditable %} {% endblock %} below also the referenced page.html {% extends "base.html" %} {% load mezzanine_tags keyword_tags %} {% block meta_title %} {{ page.title }}{{ news.title }}{{ registerdescpage.title }} | {% if page.basicpage.lang == "en" or news.lang == "en" or page.registerdescpage.lang == "en" %} myOrg {% elif page.basicpage.lang == "sv" or news.lang == "sv" or page.registerdescpage.lang == "sv" %} myOrg {% else %} myOrg {% endif %} {% endblock %} {% block meta_keywords %}{% metablock %} {% keywords_for page as keywords %} {% for keyword in keywords %} {% if not forloop.first %}, {% endif %} {{ keyword }} {% endfor %} {% endmetablock %}{% endblock … -
django custom user filed not getting saved
I have a create user function as shown below def partner_signup(request): form = PartnerProfileForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user_qs = User.objects.filter(username=username).exists() context = { "form": form, } if not user_qs: try: user = User.objects.create_user( username=username, email=email, password=password ) user.business_partner = True, user.save() except IntegrityError as e: pass return redirect('partner_profile_create') return render(request, 'signup.html', context) and a custom user model as below class User(AbstractUser): business_partner = models.BooleanField(default=False) But business partner is always saved as false, how I can make it true. -
How to use combination of annotate and aggregate sum in Django ORM
from the below table I need the output has, [(Apple,21.0), (Orange,12.0) ,(Grapes,15.0) ] basically fruits grouped with the sum of their cost date in (dd/mm//yyyy) Fruits Table date item price 01/01/2021 Apple 5.0 01/01/2021 Orange 2.0 01/01/2021 Grapes 3.0 01/02/2021 Apple 7.0 01/02/2021 Orange 4.0 01/02/2021 Grapes 5.0 01/03/2021 Apple 9.0 01/03/2021 Orange 6.0 01/03/2021 Grapes 7.0 ........... .... I tried the below code its not working as expected fruit_prices = Fruits.objects.filter(date__gte=quarter_start_date,date__lte=quarter_end_date) .aggregate(Sum('price')).annotate('item').values('item','price').distinct() -
Django- login_required decorter not working please help me
Working on a simple project using Django and the loqin_required decorator is not working. i just want when a user is logged in and refresh page or click "back" then it should logged out. here is my code : views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. @login_required(login_url='/authentication/login') def index(request): return render(request,'expenses/index.html') def add_expense(request): return render(request,'expenses/add_expense.html') urls.py from .views import RegistrationView,UsernameValidationView,EmailValidationView, VerificationView, LoginView ,LogoutView from django.urls import path from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('register',RegistrationView.as_view(),name="register"), path('login',LoginView.as_view(),name="login"), path('logout',LogoutView.as_view(),name="logout"), path('validate-username',csrf_exempt(UsernameValidationView.as_view()), name="validate-username"), path('validate-email', csrf_exempt(EmailValidationView.as_view()), name='validate_email'), path('activate/<uidb64>/<token>',VerificationView.as_view(),name="activate"), -
How to get imagefield path in models?
Happy new year and hello,i've got a problem with resizing images in django. I need to find out the way to get Imagefield path from model during loading images, how do i get? I wrote a func which changing upload path for Imagefield, i'd like to get an url to that file and past it in imagekit generator for resize. This is a func for changing upload path for Imagefield def get_file_pathM(instance, filename): extension = filename.split('.')[-1] new_name = 'new_name' filename = "%s.%s" % (new_name, extension) print('geeeeeeeeeeeeeeeeet', os.path.join('photos/project_photo/%y/%m/%d')) date_now = date.today().strftime("%Y/%m/%d").split('/') path = 'photos/project_photo/{}/{}/{}'.format(date_now[0], date_now[1], date_now[2]) return os.path.join(path, filename) Here's my class of ImageSpec for resize class Thumb(ImageSpec): processors = [ResizeToFill(100, 50)] format = 'JPEG' options = {'quality': 60} photo = models.ImageField(upload_to=get_file_pathM, verbose_name='Фото', blank=True, null=True) source_file = open('here should be an url to photo','rb') image_generator = Thumb(source=source_file) result = image_generator.generate() dest = open('media/photos/project_photo/2022/01/03/avtolider_new.jpg', 'wb') dest.write(result.read()) dest.close() And another question, it's said in imagekit documentary that's it's possible to use Imagefield as source in image_generator without using open, but it doesn't work somehow and shows an error, like Imagefiled can't open or close file. -
Can an APIView group multiple GET and POST methods?
I am implementing an API for a game using DRF view (more specifically APIViews). I have figured out how to use more than one serializer for a view but I need this view to combine multiple models and think that I need more than one GET as well as more than one POST method. Is this even possible? My code so far looks like this: class GameView(APIView): """ API View that retrieves the game, allows users to post stuff and finally a game session is posted as well once the 5 game rounds have been completed """ serializer_class = GametypeSerializer serializer_class = GamesessionSerializer serializer_class = GameroundSerializer serializer_class = ResourceSerializer serializer_class = VerifiedLabelSerializer serializer_class = LabelSerializer def get_serializer_class(self): if self.request.method == 'POST': return YOUR_SERIALIZER_1 elif self.request.method == 'GET': return YOUR_SERIALIZER_2 else: return YOUR_DEFAULT_SERIALIZER def get_queryset(self): gametypes = Gametype.objects.all().filter(name="labeler") return gametypes def get(self, request, *args, **kwargs): # gets a resource and an empty game round object to be completed (according to the game type chosen by the user) def post(self, request, *args, **kwargs): # users post a label, that is saved in the label model, a verified model is saved in the verified label model. Once 2 game rounds have been completed, … -
TypeError: unsupported operand type(s) for /: 'float' and 'decimal.Decimal'
Let us consider my views.py def ajax_add_other_order_item(request,id): client = request.user.client def _convert(from_currency, to_currency, price): custom_rate_obj = client.custom_rates.filter(currency=to_currency).first() if custom_rate_obj is None or custom_rate_obj.exchange_rate in (0, None): custom_rate_obj = ExchangeRates.objects.latest('created') return custom_rate_obj.convert(from_currency, to_currency, price) if request.method == 'POST': unit = request.POST.get('u_price') or 0 purchase_price = _convert(currency, 'GBP', float(unit)) try: exchange_price = float(unit)/purchase_price except ZeroDivisionError: exchange_price = 0 Here i am getting error TypeError: unsupported operand type(s) for /: 'float' and 'decimal.Decimal' Please help to solve this issue -
Which one is better pgpool vs pgBouncer for Database connection Pooling
Currently working on monolithic Django Service. Want to use a Database pool so which one is better pgpool vs pgBouncer. p -
Unbound Local Error: local variable 'files' referenced before assignment
Unbound Local Error: local variable 'files' referenced before assignment Getting error above: Please tell me where I am getting wrong in this code. I am beginner in Django. And I tried so many times. In this project, I am doing multiple file upload using model forms. Please help me to solve this. views.py: from Django. shortcuts import render from user master. forms import Feed Model Form, File Model Form from .models import Feed File def create_ to_ feed(request): user = request. user if request. method == 'POST': form = Feed Model Form(request .POST) file_ form = File Model Form(request. POST, request. FILES) files = request. FILES. get list('file') #field name in model if form.is_ valid() and file_ form.is_ valid(): feed_ instance = form. save(commit=False) feed_ instance. user = user feed_ instance. save() for f in files: file_ instance = Feed File(file=f, feed=feed_ instance) file_ instance. save() else: form = Feed Model Form() file_ form = File Model Form() return render(request,' user master/multiplefile.html',{'form': form, 'file_ form': file_ form, 'files': files, 'user': user}) urls.py: path('multiple/', views. create_ to_ feed, name='create_ to_ feed'), ]+static(settings. MEDIA_ URL, document_ root= settings. MEDIA_ROOT)+static(settings. STATIC_URL, document_ root=settings. STATIC_ROOT) models.py: from Django. d b import models Create your … -
Create dynamic action URL form in Django python
whenever I submit the form it takes me to the testformresult page like https://www.studnentdetail.com/student/testformresult but What I want is, when someone enters the name of the student in the form.html page then data of that student is fetched from the mysql database and displayed on another page something like https://www.studentdetail.com/student/<student_name>. Also I want to know how like many railway site when we search for particular train like 10029 then in the next page it shows url something like https://www.train/10029-running-status. form.html <form method="POST" action="{% url 'testformresult' %}"> <label for="fname">First Name</label> <input type="text" id="fname" name="firstname" placeholder="Your name.."> <input type="submit" value="Submit"> </form> views.py def testform(request): return render(request, 'testform.html') def testformr(request): fname = request.POST.get('firstname') return render(request, 'testformresult.html') urls.py path('testform', views.testform, name='testform'), path('student/testformresult/<slug:student>', views.testformresult, name='testformresult'), -
Django. Retrieving data from a related model for use in a form
How can I automatically associate a user with an id_ ticket and fill in a field in the form? Sample form - https://i.stack.imgur.com/9YMUv.png models.py class Ticket(models.Model): ticket_id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') ticket_title = models.CharField(max_length=100) ticket_date_open = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='User') class TicketMessage(models.Model): ticket_mes = models.TextField(verbose_name='Message') ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) forms.py class TicketMessageForm(ModelForm): ticket_mes = forms.CharField(label='Answer', required=True) class Meta: model = TicketMessage fields = ('ticket_mes', 'ticket') views.py class Ticket(DetailView, CreateView): model = Ticket form_class = TicketMessageForm ticket_message = TicketMessage template_name = 'support/ticket.html' context_object_name = 'one_ticket' allow_empty = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ticket_message'] = TicketMessage.objects.filter() return context def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user return super(Ticket, self).form_valid(form) success_url = reverse_lazy('ticket_list') I assume that need to somehow take the data from the template and pass it to form_valid. Tried adding a hidden field where passed the necessary information. This is works, but it looks wrong and unsafe. <select class="d-none" name="ticket" required="" id="id_ticket"> <option value="{{ one_ticket.ticket_id }}" selected="">{{ one_ticket.ticket_id }}</option> </select> -
Async Request with OpenAPI Generator Python
Happy New Year EveryOne I have a particular Case in which i am using OpenAPI generator for calling the api in another Microservice. I have two microservices ie User and Customer so in Customer im am getting the information of the multiple users from User below is the example code from user.api_clients import User user_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] user_list = [User.api.get(id=i) for i in user_id] and the above code will give me the user_data from User. In short it will hit user api from User 9 times one by one. So is there any way to hit this in a single shot with asyncio. I am new to this async thing in python. So ill really appreciate if anyone can give me an idea about how to do this. There is also a similar case like i want to get object from User model in oneshot for these user_id list. Yes i can use id__in=user_id but is ther anyway to hit the below code in oneshot like below code user_id = [1, 2, 3, 4, 5, 6, 7, 8, 9] user_obj = [User.objects.get(id=i) for i in user_id] Thanks for helping -
How to add property decorator with return url path in existing model field how?
I am make a model with the md5_name field but i want to return a share_url key using property decorator in django python how. -
using method 'build_standard_field(self, field_name, model_field)' to overcame the error [<class 'decimal.InvalidOperation'>]
I'm writing a Django Rest Framework, and I want to use a generics.CreateAPIView to create an operation in my database. my models.py: class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField("Email Address", unique=True) first_name = models.CharField("First Name", max_length=150) last_name = models.CharField("Last Name", max_length=150) mobile = models.CharField("Mobile Number", max_length=150, blank=True) balance = models.DecimalField(max_digits=9, decimal_places=2, default=0.0, verbose_name=("Balance")) created_at = models.DateTimeField("Created at", auto_now_add=True, editable=False) class Operation(models.Model): sender = models.ForeignKey("User", related_name=("Sender"), on_delete=models.CASCADE) receiver = models.ForeignKey("User", related_name=("Receiver"), on_delete=models.CASCADE) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.0, verbose_name=("Amount")) created_at = models.DateTimeField("Created at", auto_now_add=True, editable=False) I want to send uuid values when creation the operation and handle the users filter in the backend using the view. So I added extra fields to the serializers as this: class OperationCreateSerializer(serializers.ModelSerializer): sender_uuid = serializers.UUIDField(format='hex_verbose') receiver_uuid = serializers.UUIDField(format='hex_verbose') amount = serializers.DecimalField(max_digits=9, decimal_places=2, coerce_to_string=False) class Meta: model = Operation fields = ["sender_uuid", "receiver_uuid", "amount"] write_only_fields = ["sender_uuid", "receiver_uuid"] class OperationListSerializer(serializers.ModelSerializer): class Meta: model = Operation fields = ["sender", "receiver", "amount"] The Problem is when I try to create the transfert operation I get error [<class 'decimal.InvalidOperation'>] for the field 'amount' in the view. The logic I'm using in my view is: class TransferView(generics.CreateAPIView): serializer_class = OperationCreateSerializer queryset = Operation.objects.all() def create(self, request, *args, … -
Dict columns extraction using for loop
There is a dict named 'data' { "error":false, "message":"Ok", "data":{ "numFound":1845, "start":0, "numFoundExact":true, "docs":[ { "sub_farmer_id":0, "grade_a_produce":320, "commodity_image":"red_carrot.jpg", "farm_image":"", "batch_status":"completed", "batch_count":30, "franchise_type":"TELF", "sr_assignee_id":0, "farm_status":"converted", "state_name":"RAJASTHAN", "farmer_id":1648, "grade_a_sell_price":0, "id":"11", "commodity_name":"Carrot Red", "acerage":1, "soil_k":0, "lgd_state_id":8, "soil_n":0, "unique_key":"11_8", "historic_gdd":0.41, "farm_type":"soiless", "soil_test_report":"", "user_id":1648, "expected_yield_delivery_date":"2020-04-30T00:00:00Z", "current_gdd":0, "soil_p":0, "expected_grade_a_produce":636, "water_ph":0, "end_date":"2020-04-30T00:00:00Z", "batch_id":8, "expected_delivery_date":"2020-04-30T00:00:00Z", "previous_crop_ids":"0", "batch_updated_at":"2021-12-29T17:50:58Z", "grade_c_rejection":0, "water_test_report":"", "farm_updated_at":"2021-12-29T17:51:00Z", "water_ec":0, "start_date":"2019-10-30T00:00:00Z", "assignee_id":0, "pest_problems":"", "expected_production":1060, "is_active":true, "mobile":"7015150636", "grade_b_sell_price":0, "irrigation_type":"drip", "total_acerage":0, "current_pdd":0, "commodity_id":68, "stage":"flowering", "farm_health":"0", "expected_grade_b_produce":424, "grade_b_produce":740, "historic_pdd":0.31, "username":"Agritecture", "variety_name":"", "sr_assignee_name":"", "lng":0, "locality":"", "assignee_name":"", "subfarmer_mobile_no":"", "commodity_image_96px_icon":"", "subfarmer_name":"", "batch_end_date":"", "lat":0, "_version_":1720553030989906000 } But I am trying to extract data from list and append in a new csv with different columns so that it looks neat and clean so, Here I am trying code writer = csv.DictWriter(response_data, fieldnames=['Farmer Name', 'Mobile', 'Irrigation Type', 'Batch Status', 'Soil Parameters', 'Water Parameters', 'Crop Name', 'Farm Status', 'Farm Type', 'Franchise Type', 'Farm Total Acerage', 'Batch Acerage', 'Farm Health(%)', 'Historical Yield(/Acre)', 'Expected Produce', 'Actual Yield(/Acre)', 'Actual Produce', 'Crop health(%)', 'Stage', 'SOP Adherence', 'Assignee', 'Sub Farmer', 'Last Activity Update', 'Exp. Delivery Date'], delimiter=",") writer.writeheader() for docs in data.keys(): writer.writerow( {"Farmer Name": docs.get('username'), "Mobile": docs.get('mobile') "Irrigation Type": data.get('irrigation_type'), "Batch Status": data.get('batch_status'), "Soil Parameters": {'N:-': data.get('soil_n'), 'P:-': data.get('soil_p'), 'K:-': data.get('soil_k')}, "Water Parameters": {'ec:-': data.get('water_ec'), 'pH:-': data.get('water_ph'), }, "Crop Name": data.get('commodity_name'), … -
how to create multiple object in list using loop
So, I want to create different objects every time loops run, my object is [name, age, dob] which is appended in an empty list data = [] I am using class class PersonsData(object): # Object constructor def __init__(self): print("Person Data") self.name = '' self.age = 0 self.doB = 0 # Input Method def enter_data(self): size = int(input("Enter the number of data")) for i in range(size): self.name = str(input("Enter Your Name" + " ").upper()) try: self.age = int(input("Enter Your Age" + " ")) except: print("\n**Enter value in Number**") self.age = int(input("Enter Your Age" + " ")) self.doB = (input("Enter Your DOB" + " ")) print("\n") # Display Method def display(self): print("Name:", self.name) print("Age:", self.age) print("DOB:", self.doB) the problem is instead of creating new object its just overwritting other, so ho I can create new object my other half of the code while True: print() print(""" 1.Add New Detail 2.Display Detail 3.Quit """) choice = int(input("Enter Choice:" + " ")) if choice == 1: info = PersonsData() info.enter_data() print(info.name) data.append(info) print(data) elif choice == 2: for i in data: print("--------------------------------") i.display() print("--------------------------------") elif choice == 3: quit() else: print("Invalid choice") I am new to python so, please don't judge me on the …