Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how django browsableapi generate html form automatically?
i am learning DRF and i am stuck on how DRF serializer generate HTML form in browsableapi. i have UserRegistrationAPIView and UserRegistrationSerializer. class UserRegistrationAPIView(CreateAPIView): authentication_classes = () permission_classes = () serializer_class = UserRegistrationSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) user = serializer.instance token, created = Token.objects.get_or_create(user=user) data = serializer.data data["token"] = token.key headers = self.get_success_headers(serializer.data) return Response(data, status=status.HTTP_201_CREATED, headers=headers) class UserRegistrationSerializer(serializers.ModelSerializer): # password = serializers.CharField(write_only=True, style={'input_type': 'password'}) confirm_password = serializers.CharField(write_only=True, style={'input_type': 'password'}) confirm_password1 = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = User fields = ("id", "username", "email", "password", "confirm_password", "date_joined","confirm_password1") def create(self, validated_data): del validated_data["confirm_password"] del validated_data["confirm_password1"] return super(UserRegistrationSerializer, self).create(validated_data) def validate(self, attrs): if attrs.get('password') != attrs.get('confirm_password'): raise serializers.ValidationError("Those passwords don't match.") return attrs i am confused when i go to url of this view it automatically generate HTML form field. so, does it mean its uses serializer to generate HTML field. Actually, i don't understand the request flow of it how serializer is used to render HTML form. Please help me out or suggest me what to learn first to get on this. Thanks in advance. -
How can I save each array data to database? one data as one row
I used Django Rest Framework It's only store the last element of array not all 3 elements @api_view(['POST']) def add(request): serializer = modelSerializer(data=request.data) arr = ['a','b','c'] if serializerVariant.is_valid(): obj = serializer.save() for foo in arr: obj.value = foo obj.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializerVariant.errors,status=status.HTTP_400_BAD_REQUEST) -
Django - how to handle Http requests correctly in views.py
I have a beginner question here. Let's suppose that I have url which returns JSON array of objects from my database. Something like that: def my_model_as_json(request): print "request to retrieve the rules list" if request.method == "GET": object_list = Policy.objects.all() #or any kind of queryset json_response = serializers.serialize('json', object_list, fields=('name', 'last_update')) return HttpResponse(json_response, content_type='application/json') I know for sure that the request is GET, so is there any need to check any other conditions here? Do I need to return something if the request method is not GET? -
missing foreign key in django admin
I want to edit a model in admin that has a foreign key to another model that in turn has a foreign key to the base modell: from django.contrib import admin from .models import Role from .models import Address from .models import Date from .models import Person from .models import Name # Register your models here. admin.site.register(Role) admin.site.register(Address) admin.site.register(Date) #admin.site.register(Name) #admin.site.register(Person) class RoleInline(admin.TabularInline): model=Role extra=3 class NameInline(admin.TabularInline): model=Name extra=3 class PersonInline(admin.ModelAdmin): fieldsets=[ (None,{'fields': ['mail','firstName','lastName','phoneNumber','streetAdress','zipcode','city']}), ] inlines = [RoleInline,Name] search_fields = ['firstName'] #admin.site.register(Name,NameInline) admin.site.register(Person,PersonInline) the problem is that name is related to role, not directly to person. How can I fix this? -
django paypal ipn - how should I know that a payment process has been started?
I'm trying to implement a checkout system with django-paypal. The system is working, but regarding the work flow I am quiet confused. django-paypal uses a form to post to PayPal, only after the payment has been processed I get a notification via IPN. Unfortunately this does take a lot of time (going from seconds to minutes). Now it would be nice to log a pending state in my database so that I could tell the user to wait until the IPN has been received... but as django-paypal posts directly to PayPal and gives no feedback to my server I am stuck as there is no information being sent to the server. I could implement a switch to "pending" when opening the return url, but a GET shouldn't modify the state if the database... -
Django celery-beat cant run periodic task
I making a simple app for compressing images, when user download image, both image saves - with old size, and with new size. I want to set a periodic task, that will delete images that was loaded more that hour ago. So i have two models in models.py: from django.db import models class image(models.Model): name = models.CharField(max_length=20, blank=True) image = models.ImageField(upload_to="media") time = models.DateTimeField(auto_now_add=True, null=True) delete_time = models.DateTimeField(null=True) class Meta: verbose_name = 'Картинки' verbose_name_plural = 'Картинки' def __str__(self): return self.name class imagenew(models.Model): name = models.CharField(max_length=20, blank=True) image = models.ImageField(upload_to="media") time = models.DateTimeField(auto_now_add=True, null=True) delete_time = models.DateTimeField(null=True) class Meta: verbose_name = 'Картинки новые' verbose_name_plural = 'Картинки новые' def __str__(self): return self.name time - when they were added by user, delete time = time + 1 hour. So i try use celery to make task work. My settings.py with celery and redis config: INSTALLED_APPS = [ 'main', 'django_celery_results', 'django_celery_beat', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ........ CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Moscow' CELERY_BEAT_SCHEDULE = { 'delete_old_foos': { 'task': 'main.tasks.delete_old_foos', 'schedule': crontab(minute=5) } } redis_host = os.environ.get('REDIS_HOST', 'localhost') CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": … -
Django: How can i detect object request in admin panel?
To be more detailed, i have got list of objects in admin panel named Images class Image(models.Model): image = models.ImageField(upload_to='products/%Y/%m/%d/', verbose_name=_('Image'), default='default.png') album = models.ForeignKey('Album', related_name='images') category = TreeForeignKey(Category, null=True) likes = GenericRelation('Like', related_name='image_likes', null=True) is_main = models.BooleanField(default=False) is_slider = models.BooleanField(default=False) seen = models.IntegerField(default=0) seen_by_admin = models.BooleanField(default=False) class ImageAdmin(admin.ModelAdmin): list_display = ['album', 'get_owner', 'is_main', 'is_slider','total_likes', 'seen', 'image_tag', ] list_filter = ['album', 'album__owner', 'is_main', 'is_slider', 'album__created_at'] search_fields = ['album__name'] list_per_page = 15 and whenever admin or any other superuser enters to any Images.object the seen_by_admin field should be changed to seen_by_admin = True -
Build request URL to filter Django queryset multiple times by the same field
I want to filter Django queryset by the same field multiple times using Q to include/exclude records with specific value in this field. I'll use sample model to illustrate my case. Say I have a Record model with field status. This field can be one of three states A, B, C. class SampleModel(models.Model): STATUS_A = 'A' STATUS_B = 'B' STATUS_C = 'C' SOME_STATUSES = ( (STATUS_A, 'Something A'), (STATUS_B, 'Something B'), (STATUS_C, 'Something C'), ) status = models.CharField( max_length=1, choices= SOME_STATUSES, default= STATUS_A, ) I have a DRF ViewSet that's responsible for returning filtered queryset of SampleModel objects. Right now I'm filtering query set by a single status, so my URL looks something like: .../?status=A .../?status=B .../?status=C But say I want to filter queryset by multiple statuses: Return all records with status A and B. Or instead I want to return all the records except those with status C. I'm not sure how to build URL in those cases. I know that duplicating parameters in URL is a very bad practice: .../?status=A&status=B How does one request A AND B or NOT C? The remaining part of the question how to handle those multiple values is unclear probably because I don't … -
Wagtail: Add image to custom user model
I'm following the Wagtail documentation to customize the user model. I want to add an image to the user model. Problem In Settings > User in the Wagtail admin interface, the window to choose an image does not open. Console shows following JS error: Uncaught ReferenceError: createImageChooser is not defined Code models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): display_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') forms.py from django import forms from django.utils.translation import ugettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm from wagtail.images.widgets import AdminImageChooser class CustomUserEditForm(UserEditForm): display_image = forms.ImageField( widget=AdminImageChooser(), label=_('Autorenbild')) class CustomUserCreationForm(UserCreationForm): display_image = forms.ImageField( widget=AdminImageChooser(), label=_('Autorenbild'))} edit.html {% extends "wagtailusers/users/edit.html" %} {% block extra_fields %} {% include "wagtailadmin/shared/field_as_li.html" with field=form.description %} {% include "wagtailadmin/shared/field.html" with field=form.display_image %} {% endblock extra_fields %} {% block extra_js %} {{ block.super }} {% include 'wagtailadmin/pages/_editor_js.html' %} {% endblock extra_js %} create.html similar What I've tried so far The idea to use the AdminImageChooser widget I found here. I had to adjust the forms by adding an forms.ImageField so that the User page displays without error. Questions Anyone know why the error occurs and how to fix it? As stated in the above Google group thread, it seems … -
Do Django filters increases ram consumption per user : Python
I don't know where else I could have asked this question, thus asking it here. I want to know that if I impose multiple Django filters on a page which are using multiple db tables, will that effect ram consumption whenever a user visits this page because before the user only filtered data will get reflected. I'm using django with postgresql on a ubuntu based VM, also if there are any documentation which can be helpful in understanding ram utilization, please suggest. -
Handling a filter form along with other get parameters in Django
I have a django form with 2 required fields and some optional fields which filters the data presented in a view. This view uses some GET parameters apart from the ones for the filter form and I'm initialising my filter from like form = MyFilterForm(farm, request.GET or None) [see (1) in the code below]. I'm finding when my view is first loaded and there are no GET parameters this works fine as request.GET is falsey so the form doesn't get bound (and therefore we use the initial values for the required fields). If the filter form gets used then request.GET gets populated with the form parameters and all works well again. However if one of my other GET parameters (namely one used to sort the resulting data table) gets passed without the filter form getting used then request.GET is truthy but doesn't have any of the parameters that correspond to the form and so the form gets bound and errors as invalid because my required fields have not been given a value. What should happen here is that data table should be sorted and the form should continue using the initial ('default') values, just like when it is first loaded. … -
Many to many field and get_absolute_url
I try to create a link between lista_libri.html and lista_generi.html, using get_absolute_url. I've create already a link between autore.html and lista_libri.html and it runs well. But if I active a link between lista_libri.html and lista_generi.html, it results blank. Below I share the code strings that define model, view and templates. models.py from django.db import models from django.urls import reverse class Genere(models.Model): nome = models.CharField(max_length=20) def __str__(self): return self.nome def get_absolute_url(self): return reverse("libri_genere", kwargs={"pk": self.pk}) class Meta: verbose_name = "Genere" verbose_name_plural = "Generi" class Autore(models.Model): nome = models.CharField(max_length=20) cognome = models.CharField(max_length=20) nazione = models.CharField(max_length=20) def __str__(self): return self.nome + " " + self.cognome def get_absolute_url(self): return reverse("profilo_autore", kwargs={"pk": self.pk}) class Meta: verbose_name = "Autore" verbose_name_plural = "Autori" class Libro(models.Model): titolo = models.CharField(max_length=100) isbn = models.CharField(max_length=13) autore = models.ForeignKey(Autore, on_delete=models.CASCADE, related_name="libri") genere = models.ManyToManyField(Genere, related_name="generi") def __str__(self): return self.titolo class Meta: verbose_name = "Libro" verbose_name_plural = "Libri" views.py from django.views.generic.detail import DetailView from django.views.generic.list import ListView from .models import Autore, Libro, Genere class AutoreDCBV(DetailView): model = Autore template_name = "autore.html" class LibroLCBV(ListView): model = Libro template_name = "lista_libri.html" class GenereDCBV(DetailView): model = Genere template_name = "lista_generi.html" urls.py from django.urls import path from .views import LibroLCBV, AutoreDCBV, GenereDCBV urlpatterns = [ path('', LibroLCBV.as_view(), … -
How to iterate queryset dictionary in django template
This is my dictionary i get from view: {'questions_in_topic': <QuerySet [{'question_id__description': 'Describe your most significant leadership experience'}, {'questi on_id__description': 'Which kind of leader are you?'}]>} How do I show individual questions in django template? The view is below: def get_question_from_topic(request): if request.method == "GET": questions_in_topic = QuestionTopic.objects.filter(topic_id=request.GET['topicId']).values('question_id__description').order_by('question_id__description') print(questions_in_topic) context = { 'questions_in_topic': questions_in_topic } print(context) return render(request, 'recruiter/add_question_library.html', context) return render(request, 'recruiter/add_question_library.html', context) -
django.contrib.gis.geos.error.GEOSException: Could not parse version info string
I installed goal on Mac as follows: brew install -v gdal However when I run my program that I was able to successfully run on Linux, it gives me the following errors: File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/tesor/Desktop/test/api-server/api-server/lib/python2.7/site-packages/django/contrib/gis/admin/__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "/Users/tesor/Desktop/test/api-server/api-server/lib/python2.7/site-packages/django/contrib/gis/admin/options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "/Users/tesor/Desktop/test/api-server/api-server/lib/python2.7/site-packages/django/contrib/gis/admin/widgets.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "/Users/tesor/Desktop/test/api-server/api-server/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py", line 18, in <module> HAS_GEOS = geos_version_info()['version'] >= '3.3.0' File "/Users/tesor/Desktop/test/api-server/api-server/lib/python2.7/site-packages/django/contrib/gis/geos/libgeos.py", line 196, in geos_version_info raise GEOSException('Could not parse version info string "%s"' % ver) django.contrib.gis.geos.error.GEOSException: Could not parse version info string "3.6.3-CAPI-1.10.3 80c13047" I cannot figure out what's happening. The version of python is Python 2.7.15. I understand that the issue is related to the version of GDAL, but how can I solve this problem? I need gdal 1.10.1. -
Internal Server Error in django and uwsgi + nginx
I deployed a Django application on server. I used nginx and uwsgi as web server. I didn't have any problem first, but I see "Internal Server Error" when I add rest_framework to project. I guess It has problem with rest_framework but I don't know its reason. I think you should know when I remove rest_framework from project, It's working. I should say when I run project with python manage.py runserver, It's working. I guess there are any problems with nginx or uwsgi. I put my settings below: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'emh6)d=!db$6dunhkdo-2wz*r^w**@)w8((@1*$prrgr9m8un7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'tagulous', 'django_render_partial', 'ckeditor', 'ckeditor_uploader', 'allauth', 'allauth.account', 'allauth.socialaccount', # 'easy_thumbnails', # 'filer', 'mptt', # 'anymail', 'core.apps.CoreConfig', 'blog.apps.BlogConfig', 'sitebuilder.apps.SitebuilderConfig', 'rest_framework', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'boofeh.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'sitebuilder','templates'), os.path.join(BASE_DIR, 'sitebuilder','templates', 'allauth')], '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', ], }, }, ] WSGI_APPLICATION = 'boofeh.wsgi.application' # … -
Can I somehow use the endpoint override django.settings
In the settings, I have several variables, these are strings. Can I somehow rewrite them with the help of some endpoint in jango? My thanks! -
Define abstact django models field
I need to create an abstract Django model and I want to enforce all models-inheritors redefine that field. I've tried that but got an exception: from django.db import models class AbstractField(models.Field): description = "Abstract Field" def __init__(self): raise NotImplementedError("You have to redefine your field in model.") class MyAbstractModel(models.Model): id = models.AutoField(primary_key=True) redefine_me_please = AbstractField() class Meta: abstract = True class MyNotAbstractModel(MyAbstractModel): redefine_me_please = models.CharField(verbose_name='Name', max_length=255) An exception was NotImplementedError on makemigrations action. Any idea how to imitate abstract field? -
Difference in foreign key lookup through object.fk.id and object.fk_id
I have not found this question on SO. Is there a speed difference between the following two variants of doing foreign key lookup in django's object model? I only need the foreign key. class A(models.Model): x = models.PositiveIntegerField(null=True) class B(models.Model): a = models.ForeignKey(A, null=True, on_delete=models.CASCADE) y = models.PositiveIntegerField(null=True) b = b.objects.last() Which is faster or are they the same? b.a_id b.a.id edit: Actually I think I can answer it myself... the second variant should be slower since it creates the whole object from the db, right? -
View class dispatch() doesn't find method?
I'm trying to use single url with two views. I found an example of that on official django documentation. I have something like this: class DetailOrderView(View): """Combines form and detail parts into one and in darkness binds them.""" # import pdb; pdb.set_trace() def get(self, request, *args, **kwargs): view = DisplayDetailOrderView.as_view() return view(self, *args, **kwargs) def post(self, request, *args, **kwargs): view = FormDetailOrderView.as_view() return view(self, *args, **kwargs) And in urls.py I refer to DetailOrderView.as_view() However, when I try to run this I get this error: .... lib/python3.6/site-packages/django/views/generic/base.py", line 84, in dispatch if request.method.lower() in self.http_method_names: AttributeError: 'DetailOrderView' object has no attribute 'method' Which basically means when dispatch(self, request, *args, **kwargs) tries to call request.method.lower() it finds that request has no attribute method! Which is kinda strange right? request should be defined in as_view() right? This is pretty much c/p from the official documentation and it should work so I must be doing something stupid.. -
Why do I get a ForeignKey constraint violation
As can be seen below, I have 2 models connected via an intermediary model to form a ManyToMany relationship. The problem is that, when I delete a Tender object in get this error. update or delete on table "tender_details_tender" violates foreign key constraint "user_account_company_tender_id_984ea78c_fk_tender_de" on table "user_account_companyprofile_assignedTenders" DETAIL: Key (id)=(1) is still referenced from table "user_account_companyprofile_assignedTenders". I thought by adding on_delete=models.CASCADE in the ForeighKeys (i.e. in the intermediary model) would solve this problem, but apparently not. class CompanyProfile(models.Model): assignedTenders = models.ManyToManyField(Tender, through='UsersTenders', related_name='UserCompanies') # connects users to the tenders they match. class UsersTenders(models.Model): user = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, related_name='userTenderLink') tender = models.ForeignKey(Tender, on_delete=models.CASCADE, related_name='userTenderLink') sent = models.BooleanField(default=False, blank=False) class Meta: unique_together = ("user", "tender") class Tender(models.Model): tenderCategory = models.ManyToManyField(Category, blank=False) #this field holds the tender category, e.g. construction, engineering, human resources etc. tenderProvince = models.ManyToManyField(Province, blank=False) #this is the province the tender was a How can I resolve this problem. -
Why I'm getting an error while creating a new model class in django?
I have read similar questions but couldn't come to a solution or a conclusion about it. I got this error while creating a new model class in the same app as well as creating a new model class in a new app. The error django.db.utils.IntegrityError: UNIQUE constraint failed: auth_permission.content_type_id, auth_permission.codename my models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave')) STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) MANAGER_CHOICES = (('0001_manager', '0001_manager'),('0002_manager', '0002_manager')) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) def __str__(self): return self.name class B(models.Model): state = models.CharField(max_length=50) -
Adding a domain to a django webapp running on digital ocean
I have a Django Web App that is currently live on digital ocean with an IP address say w.x.y.z, I have also bought a domain name say example.com, how can i add this to my app so that, when i go to example.com , I get to my website which currently is only accessible through the IP. Any advice is appreciated. I'm new to this -
JWT authentication between Django and ReactJS
I am currently using Django (2.1) to build an API, and I have added djangorestframework-jwt to manage JWT. Here is the configuration: JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', } and the endpoints: urlpatterns = [ path('auth/get-token/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), ] The client is built with ReactJS. I use an axios instance as a client to communicate with the API. This instance is created that way : import axios from 'axios' import jwt_decode from 'jwt-decode' // eslint-disable-line import { signOut } from '../actions/authActions' const signOutOn401 = (statusCode) => { if (statusCode === 401) { signOut() window.location = '/signin' } } const client = axios.create({ baseURL: process.env.API_URL, headers: {'Authorization': ''} }) /* * This interceptor is used for: * - adding Authorization header if JWT available * - refreshing JWT to keep user authenticated */ client.interceptors.request.use((config) => { if (window.localStorage.getItem('token')) { let token = window.localStorage.getItem('token') // Calculate time difference in days // between now and token expiration date const t = ((jwt_decode(token).exp * 1000) - Date.now()) / 1000 / 60 / 60 / 24 // Refresh the token if the time difference is // smaller than 13 days (original token is … -
Django formset with no initial data
I am a Django rookie and I am developing a small app to register time (duration) and quantity of activities per user per day. Sort of like a work log. My problem is this: My “add entry” view displays and updates old records rather than adding new records to the db. I need a view to add new records, not replace old ones. From searching around and from the #django IRC channel, I understand that the formset-way by default draws on old data rather than setting the client up for adding new data. I have, however, not found anything about how to avoid this behaviour and have the client provide a blank form for "appending new data" rather than "editing existing data". My deadline is drawing really close and all help is greatly appreciated. Here are the relevant code snippets: From models.py class Activity(models.Model): name = models.CharField(max_length=200) description = models.TextField() class Workday(models.Model): entrydate = models.DateField() worker = models.ForeignKey(User, on_delete=models.CASCADE) class Entry(models.Model): duration = models.DurationField() quantity = models.PositiveIntegerField() activity = models.ForeignKey(Activity, on_delete=models.CASCADE) workday = models.ForeignKey(Workday, on_delete=models.CASCADE) From forms.py class EntryForm(ModelForm): activity = ModelChoiceField(queryset=Activity.objects.order_by('name'), initial=0) class Meta: model = Entry fields = ['activity', 'duration', 'quantity', ] class WorkdayForm(ModelForm): class Meta: model = … -
ValueError at /studentform/ ModelForm has no model class specified
I am getting an error while running the following form. please help me to fix the error. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class student(models.Model): name = models.CharField(max_length=50) emailid = models.EmailField(max_length=60) marks = models.CharField(max_length=11) date = models.DateTimeField() def __str__(self): return self.name forms.py from django import forms from .models import * class student_form(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(), required=True, max_length=100) emailid = forms.EmailField(widget=forms.EmailField(), required=True) class Meta(): model = student fields = ['name','emailiid'] I have tried many things but no solution. please look at in this code and help to sort this out. so confusing for me as i am new to Django.