Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
book appointment functionality
I have Django project, which contains two classes in model.py file, one is clinic(which has a contact number as a field) and other one is patient. I have rendered all the clinics in cards and each card has a button book-appointment. here is my model.py: class Clinic(models.Model): clinic_name = models.CharField(max_length=200, blank=True, verbose_name='Name') poster = models.ImageField(blank=True, null=True, upload_to='uploads/%Y/%m/%d', verbose_name='Picture') address = models.TextField(max_length=500, blank= True) contact_no = models.CharField(max_length=12, blank=True, verbose_name='Mobile') def __str__(self): return self.clinic_name class Patient(models.Model): clinic = models.ForeignKey(Clinic, on_delete=CASCADE) patient_name = models.CharField(max_length=200, blank=True) contact_no = models.CharField(max_length=12, blank=True) appointment_time = models.DateTimeField(auto_now=True) def __str__(self): return self.patient_name Now what I want is, when a authentic user which is patient in this case, clicks on book-appointment , A message should be sent on the clinics phone number saying this guys have booked an appointment with you on this date. how this can be achieved??? please guide me. -
convert django fileobject.chunks() into image
i am trying to create a progress bar for my file upload, so I need a way of know the state of the file been uploaded at any point in time. def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] fs = FileSystemStorage() for chunk in file.chunks(): image = ImageFile(io.BytesIO(chunk), name=file.name) filename = fs.save(file.name, content=image) I am looking for a way of saving the chunk and later converting them into an image to be saved, I don't want to use the python read and right interface because i will be uploading the file to aws. can someone point me in the right direction. -
How to validate Django forms and show validation error in front-end?
My models.py class Room(models.Model): room_category = models.ForeignKey(Cat, on_delete=models.CASCADE) number = models.IntegerField(unique=True) people = models.IntegerField() picture = models.ImageField(upload_to = 'room/', null=True, blank=True) actual_price = models.IntegerField() offer_price = models.IntegerField() class Booking(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room=models.ForeignKey(Room, on_delete=models.CASCADE) check_in=models.DateTimeField() check_out=models.DateTimeField() payment_status_choices = { ('SUCCESS', 'SUCCESS'), ('FAILURE', 'FAILURE'), ('PENDING', 'PENDING')} HTML file : <form id="booking-form" action="" method="POST"> {% csrf_token %} <div class="group"> <input type="hidden" name="category" id="id_category" class="input" value="{{ cat }}"> </div> <div class="group"> <label for="id_check_in" class="label">Check In</label> <input type="datetime-local" name="check_in" id="id_check_in" class="input"> </div> <div class="group"> <label for="id_check_out" class="label">Check Out</label> <input type="datetime-local" name="check_out" id="id_check_out" class="input"> </div> <div class="group"> <label for="id_people" class="label">People</label> <input type="number" name="people" id="id_people" class="input"> </div> <div class="group"> <button type="submit" class="button" style="font-family: Century Gothic;">Book</button> </div> </form> Views.py : def Explore(request, **kwargs): category=kwargs.get('category') room_list=Room.objects.filter(room_category=category) cat1 = Cat.objects.get(category=category) if request.method == 'POST': form=AvailabilityForm(request.POST) if form.is_valid(): data=form.cleaned_data else: return HttpResponseRedirect(reverse('system:homepage')) room_list = Room.objects.filter(room_category=category, people=data['people']) available_rooms = [] for room in room_list: if check_availability(room, data['check_in'], data['check_out']): available_rooms.append(room) if len(available_rooms) > 0: room = available_rooms[0] booking = Booking.objects.create( user=request.user, room=room, check_in=data['check_in'], check_out=data['check_out'], amount=100 ) booking.save() return HttpResponseRedirect(reverse('system:BookingList')) else: form=AvailabilityForm() context={'category':category, 'cat':cat1, 'room_list':room_list,} return render(request, 'system/explore.html', context) My forms.py class AvailabilityForm(forms.Form): category = forms.CharField(max_length=100) check_in = forms.DateTimeField(input_formats='%Y-%m-%dT%H:%M', required=True) check_out = forms.DateTimeField(input_formats='%Y-%m-%dT%H:%M', required=True) people = forms.IntegerField(required=True) def clean(self): cleaned_data = super().clean() room_list = … -
django "detail": "Method \"GET\" not allowed." (one to many relationship)
models.py from django.db import models class User(models.Model): username = models.CharField(max_length=64) class Games(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) game = models.CharField(max_length=128) serializers.py from rest_framework import serializers from . import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = '__all__' class GameSerializer(serializers.ModelSerializer): class Meta: model = models.Games fields = '__all__' views.py from django.shortcuts import render from . import models from . import serializers from rest_framework import generics, status from rest_framework.views import APIView from rest_framework.response import Response class UserView(generics.ListCreateAPIView): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer class CreateUser(APIView): # this works just fine def post(self, request): serializer = serializers.UserSerializer(data= request.data) if serializer.is_valid(): username = serializer.data.get('username') queryset = models.User.objects.filter(username) if queryset.exists(): user = queryset[0] user.username = username user.save(update_fields=['username']) else: user = models.User.objects.create(username=username) user.save() return Response(serializers.UserSerializer(user).data, status=status.HTTP_200_OK) return Response({'BAD REQUEST': 'INVALID DATA'}, status=status.HTTP_400_BAD_REQUEST) class CreateGame(APIView): # this is causing problems def post(self, request): serializer = serializers.GameSerializer(data= request.data) if serializer.is_valid(): game = serializer.data.get('game') user = serializer.data.get('user') game = models.Games.objects.create(user=user, game=game) game.save() return Response(serializers.GameSerializer(game).data, status=status.HTTP_200_OK) return Response({'BAD REQUEST': 'INVALID DATA'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.UserView.as_view(), name='view'), path('user', views.UserView.as_view(), name='user-view'), path('game', views.CreateGame.as_view(), name='create-game') ] Basically I have 2 models, the User and Game model, I want there to be … -
Django: include a url with no namespace
I have an a Django app, with respect to the project root at applib/hw/apps.py The name attribute of the config class within this apps.py is applib.hw. The app controls how a user is logged in. I wish it's urls to its own app url.py so its modular, but it fails: # applib/hw/urls.py url_patterns = [ path('accounts/login/', UserLoginView.as_view(), name='login'), path('version/', views.version_view, name='version'), ] This fails because then the login name for reversal is applib.hw.login, whereas Django expects just login I could place it in the project url.py but this defeats the modularity of the django app. -
When attempting to loaddata - get error problem installing fixture
I am trying to load data from a db.json file I created (Sqlite db was the source). The original database is Sqlite, and I am try to migrate to Mysql. Everything works fine under Sqlite. I get the following error: django.db.utils.OperationalError: Problem installing fixture '/home/balh/blah/db.json': Could not load trackx_site.Segment(pk=1): (1054, "Unknown column 'program_id' in 'field list'") It seems like the Mysql tables do not have the foreign key or something?.... The models look like this: class Program(models.Model): air_date = models.DateField(default="0000/00/00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00",blank=True) running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00",blank=True) remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) locked_expiration = models.DateTimeField(null=True,default=None,blank=True) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(max_length=64) producer = models.CharField(max_length=64) editor = models.CharField(max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) class Segment(models.Model): class Meta: ordering = ['sequence_number'] program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190, blank=True) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField() seg_length_time_delta = models.DurationField(default=timedelta) seg_run_time = models.TimeField(default="00:00:00",blank=True) seg_run_time_delta = models.DurationField(default=timedelta) seg_remaining_time = models.TimeField(default="00:00:00",blank=True) seg_remaining_time_delta = models.DurationField(default=timedelta) author = models.CharField(max_length=64,null=True,default=None,blank=True) voice = models.CharField(max_length=64,null=True,default=None,blank=True) library = models.CharField(max_length=190) summary = models.TextField() audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) … -
Django version not found when running docker-compose with python3.9 alpine image
Hi I'm trying to build out a basic app django within a python/alpine image. I am getting en error telling me that there is no matching image for the version of Django that I am looking for. The Dockerfile in using a python:3.9-alpine3.14 image and my requirements file is targeting Django>=3.2.5,<3.3. From what i understand these should be compatible, Django >= 3 and Python 3.9. When I run docker-compose build the RUN command gets so far as the apk add commands but fails on pip. I did try changing this to pip3 but this had no effect. Any idea what I am missing here that will fix this issue? requirements.txt Django>=3.2.5,<3.3 uWSGI>=2.0.19.1,<2.1 Dockerfile FROM python:3.9-alpine3.14 LABEL maintainer="superapp" ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN mkdir /app COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache --virtual .build-deps \ build-base \ gcc \ linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .build-deps && \ adduser --disabled-password --no-create-home rsecuser && \ mkdir -p /vol/web/static && \ chown -R rsecuser:rsecuser /vol && \ chmod -R 755 /vol && \ chmod -R +x … -
How to add a journal reference to a django template
I want to add references from a list to a django template. Are there any extensions available that let me cite a reference from a list in a django template? -
Heroku - gunicorn timeout for simple Django app
I know there are several questions about that on SO but none of them solved my problem. I don't understand why there is a timeout in heroku (code=H12 desc="Request timeout") when I try to deploy my app knowing that this is a very lite Django app. Any idea of what could be the problem ? -
How to show some local information by clicking on the Folium marker, No popup, just out side the map box
I have about 1000 marker points on the folium map on my Django application. I would like to show the information of each point by clicking on the Marker. I tried the popup and it works well. But the information of each point is very detailed and I would like to show the information outside of the map box. Do you have any idea or any keywords to search for? -
Image not showing in Gmail - Using django
After testing sending an email from the local machine and get this URL https://ci4.googleusercontent.com/proxy/HtWaUlJqlZOG14quifhHYMFq5Br1BurGYqsuwPFVS2j8LTQeUxlce2SSqo8TLtszqF6Qf_jYdJJoADpgwn1OaVoAk-dJH14LZUyj5UMMAh7hrvZ8Xk0iDTQzEbJq03w9cn-86dJ7c_Q9T-oPVjaJDiXjWkGz_GKxs3HQ2uGGd_OMTF6BOA=s0-d-e1-ft#http:///media/products/397349892806/www.vivamacity.com6image_43794f79-7fa4-4a05-939b-7b0fbabe651c_900x_MaS1ucL.jpg Can you give me the solution to fix this issue??? -
annotate missing grouping keys with zero
I have models: class Deviation(models.Model): class DeviationType(models.TextChoices): TYPE1 = 'type1', TYPE2 = 'type2' COMMON = 'common' type = models.CharField( _('deviation type'), choices=DeviationType.choices, max_length=25, default=DeviationType.COMMON, ) class Task(models.Model): name = models.CharField() deviation = models.ForeignKey(Deviation) ORM request: res = Task.objects.values('deviation__type')\ .annotate(type=F('deviation__type'), count=Count('pk'))\ .values('type', 'count') As you can see the aim is to count Tasks grouping by deviation__type. If there is no Tasks with specific deviation__type, they will not be in res. For example if there no Tasks with deviation__type=COMMON the res will be: [ { "type": "type1", "count": 9 }, { "type": "type2", "count": 10 } ] Is that possible to add missing records in res like that: [ { "type": "losses", "count": 9 }, { "type": "personnel", "count": 10 }, { "type": "common", "count": 0 } ] ? -
Why is the inline formset not validating
I have two models with foreign key relation models.py from django.db import models # Create your models here. class Project(models.Model): STATUSES = ( ('Ongoing', 'Ongoing'), ('Completed', 'Completed') ) YEARS = ( (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022) ) name = models.CharField(max_length=200) client = models.CharField(max_length=100) year = models.SmallIntegerField(choices=YEARS) status = models.CharField(max_length=10, choices=STATUSES) picture = models.ImageField(blank=True, null=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Photo(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name="images", blank=True, null=True) image = models.ImageField() description = models.CharField(max_length=100, blank=True, null=True) slide = models.BooleanField(default=False) I want photos and project to be created on the same form so I've used inline_formset_factory forms.py from django.forms import inlineformset_factory from projects.models import Photo, Project from django.forms import ModelForm class ProjectModelForm(ModelForm): class Meta: model = Project fields = ( 'name', 'client', 'year', 'picture', 'status', 'description', ) class PhotoModelForm(ModelForm): class Meta: model = Photo fields = ( 'image', 'slide', 'description' ) PhotoFormset = inlineformset_factory(Project, Photo, form=PhotoModelForm, extra=1) I used the generic CreateView views.py from django.contrib.auth.mixins import LoginRequiredMixin from projects.forms import PhotoFormset, ProjectModelForm from django.shortcuts import redirect, reverse, render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Photo, Project # Create your views here. class ProjectCreateView(LoginRequiredMixin, CreateView): template_name = 'projects/project_create.html' form_class = ProjectModelForm … -
How can i color change a <div> in a django template depending on a model field?
i have a model in models.py containing a field which indicate its default color (green) and with a method its supposed to change to amber if the future date(another field) is equal to timezone.now(). However whenever i run the webapp, all objects display green even if the dates are the same. what can i change or {% for prestamo in prestamos %} <style> .activo{ text-align: center; background-color: {{prestamo.color_id}}; margin: 50px; padding: 20px; border-radius: 25px; } </style> <div class="activo"> <ul style="list-style-type:none;"> <li>{{prestamo.item}}</li> <li>numID: {{prestamo.num_serie}}</li> <li>Equipo: {{prestamo.nom_equipo}}</li> <li>Nombre: {{prestamo.empleado}}</li> <li>Departamento: {{prestamo.departamento}}</li> <li>{{prestamo.correo}}</li> <li>Engrega: {{prestamo.fecha}}</li> <li>Expira: {{prestamo.entrega}}</li> </ul> </div> {% endfor %} def return_date_time(): now = timezone.now() return now + timedelta(days=15) class prestamo(models.Model): item = models.CharField(max_length=100) num_serie = models.CharField(max_length=100, default='') nom_equipo = models.CharField(max_length=100, default='') empleado = models.CharField(max_length=100) correo = models.CharField(max_length=100,default='') departamento = models.CharField(max_length=100) fecha = models.DateField(auto_now_add=True) entrega = models.DateField(default=return_date_time) color_id = models.CharField(max_length=100, default='#1DB03C', editable=False) def prestamoExpirado(): if prestamo.entrega != timezone.now(): prestamo.color_id ='#1DB03C' elif prestamo.entrega == timezone.now(): prestamo.color_id = '#FFBF00' return prestamo.color_id def __str__(self): return self.item -
Django - Add form validation to inlineformset_factory
So, I'm trying to validate some fields from an inlineformset_factory object, but I don't see how to do that in a clean way from this view (not using a Form class). Would it be possible to override the .is_valid() method in this case? Any help would be appreciated. def tenant(request, id): tenant = Tenant.objects.get(id=id) DealerFormset = inlineformset_factory(Tenant, Dealer, fields=('name', 'phone_number'), extra=0) formset = DealerFormset(instance=tenant) if request.method == 'POST': formset = DealerFormset(request.POST, instance=tenant) if formset.is_valid(): # <--- How to add custom validations here? formset.save() return redirect('tenant_details', id=tenant.id) context = { 'formset': formset, } return render(request, 'tenant_details.html', context) -
Django - social_auth - How could I separate social_auth_facebook_scope to request different scope
I am a new web developer using django framework and I try to set multiple scope for social_auth_facebook_scope in the django framework. What I have done is ref from this link : How can I ask for different permissions from facebook at different times? But I didn't know how to do it so First,I put the FACEBOOK_SCOPE and FACEBOOK_CUSTOM_SCOPE in the setting.py file SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link'] SOCIAL_AUTH_FACEBOOK_CUSTOM_SCOPE = ['instragram_basic'] Second, I don't know where to put this code in. class CustomFacebookOAuth2(FacebookOAuth2) : name = 'facebook-custom' Is it have to use in views.py or apps.py, I don't have any ideas. Next I want my 2 button separate each request First button is to log in with Facebook only Second button is to request a permission for Instagram business account so how do I config in my html file Now what I am config is set the url to call Facebook-custom to request different scope but it doesn't work and return Error pages not found http://localhost:8000/social-auth/login/facebook-custom/ Instagram business Account html class="nav-link" href="{% url 'social:begin' 'facebook-custom' %}">Instragram business account How can I fix it , Anyone have an idea. -
How to use PostgreSQL's stored procedures or functions in Django project
I am working on one Django project. And I decided to write logic code in PostgreSQL instead of writing in Python. So, I created a stored procedure in PostgreSQL. For example, a stored procedure looks like this: create or replace procedure close_credit(id_loan int) language plpgsql as $$ begin update public.loan_loan set sum = 0 where id = id_loan; commit; end;$$ Then in settings.py, I made the following changes: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pawnshop', 'USER': 'admin', 'PASSWORD': password.database_password, 'HOST': 'localhost', 'PORT': '', } } So the question is, How can I call this stored procedure in views.py? p.s. Maybe it sounds like a dumb question, but I really couldn't find any solution in Django. -
How to generate a download link for a file stored in the flask server rather than directly downloading the file?
I have built a flask app wherein the user uploads a file, it gets processed and thereafter, gets stored in a particular folder on the flask server itself. Now, I wanted to generate a download link for this file (a link I would be emailing to the user) instead of directly allowing the user to download the file. Any ideas how I should go about it? Thank You. -
How to set class of OrderingFilter's widget in Django?
I want to set class of OrderingFilter's in Django framework. I can add class to ModelChoiceFilter like that: from django_filters import OrderingFilter, ModelChoiceFilter user_status_filter = ModelChoiceFilter(queryset=UserStatus.objects.all(), label="Status", widget=Select(attrs={'class': 'form-control'})) But adding class to OrderingFilter results in error: 'ChoiceExactField.widget' must be a widget class, not <django.forms.widgets.Select object at 0x000001FA0C6BCA48>' order_by_filter = OrderingFilter( fields=( ('score', 'Score'), ('money', 'Money'), ), label="Sort by", widget=Select(attrs={'class': 'form-control'}) ) What is the proper solution to set class of this widget? -
Implementing case-insensitive username and email with class base view in Django 3
I'm trying to implement a registration mechanism with class base view in a Django project. I tried many methods but none of them worked. Anybody Has A Solution?? views.py: class RegisterView(FormView): template_name = 'users/user_register.html' form_class = UserRegistrationForm redirect_authenticated_user = True success_url = reverse_lazy('index') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterView, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('index') return super(RegisterView, self).get(*args, **kwargs) forms.py: class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
Render Variable Form Fields
I'm attempting to created a vehicle project and when I select a brand I would like it to only list the models associated with that brand within my form. Currently, if I select a Make, all models from all other Makes also appear. I would like to filter the options down to only the Models associated with that Make. class CarMake(models.Model): name = models.CharField(max_length=100) country_of_origin = CountryField(null=True) slug = models.SlugField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('make-profile', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class CarModel(models.Model): name = models.CharField(max_length=100) make = models.ForeignKey('CarMake', on_delete=models.CASCADE) slug = models.SlugField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('model-profile', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify('%s %s' % (self.make, self.name)) return super().save(*args, **kwargs) -
How to pass dict info to plotlyjs pie chart?
From my views I have {{data}} which is [1, 1, 2, 1, 1] and {{labels}} which is ['CONTAINERSHIP', 'TANKER', 'TUGBOAT', 'FISHING BOAT', 'CHEMICAL TANKER'], but when adding to plotly.js pie chart, it does not read the labels, my code is: {% block content %} <div id="myDiv" style="width:600px;height:250px;"></div> <script> var data = [{ values: {{data}}, labels: {{ data }} , type: 'pie' }]; var layout = { height: 500, width: 500, }; Plotly.newPlot('myDiv', data, layout); </script> {% endblock %} I am pretty sure my problem is on how to pass this info to plotlyjs, but I have no idea what is the proper way? Any assistance is deeply appreciated. -
Django modeling - need advise on Guest, Host, Invitations relation model
I have the following case, which I can't turn into Django models on my own, hence asking the community: A party Host sends out invitations for an Event to multiple Guests and wants to track whom they send Invitations. A Host may host different Events and send out an invitation for each Event to the same Guest. Guest needs to track his invites too. I.e. can ignore or accept an invitation, and be able to see their history of invitations. Host needs to track down responses too, i.e. view who responded for each Event. So, I have so far the following model (simplified here): class Host(models.Model): name = models.CharField(max_length=20) class Guest(models.Model): name = models.CharField(max_length=20) class Event(models. Model): name = models.CharField(max_length=20) one) date = models.DateField() host = models.ForeignKey(Host, related_name="invatations" ) invitations = models.ManyToManyField(Guest, related_name="invatations", ) So this gives me: Host can access a list of invited Guests. Guest can access their invitations via a related name. But I can't figure out how to make invite management by Guest and Host separately. I.e. they should have their own lists, it seems. I.e. if a guest may trash an invite, a Host still needs to see this invite as sent out on his … -
pycharm django install mysqlclient failed
I start a Django project by Pycharm and require to use the Mysql as database, there is somthing wrong with installing the mysqlclient package.I have searched the info and downloaded the package from www.lfd.uci.edu.When I pip install the .whl file,it told me not match the platform. But I use the same package to pip install in cmd sucessfully. I wonder there is something different between the venv and local? the detail screenshot as below: my venv Python version: Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 I have try some different version mysqlclient pip install mysqlclient-1.4.6-cp38-cp38-win32.whl pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl both of above are wrong as below: mysqlclient-1.4.6-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. I don`t have the enough reputation to post the image,I just can let them as a tags.I hope someone can help me out.Thanks for reading this question. -
django Inherit from base Model form and add extra fields (doesn't exist in model fields) is not working
I'm trying to Inherit from BaseModelForm and add extra fields doesn't exist in the Model fields but it doesn't work. # forms.py class BaseConditionForm(forms.ModelForm): class Meta: model = Condition fields = ['nid', 'amount', 'donation'] class ConditionForm(BaseConditionForm): date_type = forms.ChoiceField(choices=ConditionChoices.DATE_TYPE_CHOICES) save_type = forms.ChoiceField(choices=ConditionChoices.SAVE_TYPE_CHOICES) class Meta(BaseConditionForm.Meta): fields = BaseConditionForm.Meta.fields + ['data_type', 'save_type'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) def clean(self): cleaned_data = super(ConditionForm, self).clean() print(cleaned_data['cchi']) pass and models.py class Condition(models.Model): def __str__(self): return str(self.id) # .zfill(10) nid = models.CharField(max_length=10, null=False, blank=False, db_index=True) amount = models.IntegerField(null=True, blank=True) donation = models.IntegerField(default=0, null=True, blank=True) but I got this error . . . File "/mnt/data/programming/projects/lean/shefa/condition/forms.py", line 74, in <module> class ConditionForm(BaseConditionForm): File "/mnt/data/programming/projects/lean/shefa/venv/lib/python3.8/site-packages/django/forms/models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (data_type) specified for Condition if it is not applicable please suggest me another solution. thanks in advance for you all.