Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gson ruturns code instead of null in android
I am working on an android project and Django as its backend. The endpoint works fine and it returns an empty array for a certain field "[ ]". When the gson serialize it to kotlin class (in which the field is defined as integer array) it returns this code: [Ljava.lang.Integer;@39da238. I need to perform a null check on this field. -
Context from 'views.py' not showing on 'base.html' - Django
I can't find where is the problem, so I want to create li element for each of my categories. Here are my codes: views.py: def categories(request): context = { 'category_list': Category.objects.all(), } return render(request, 'base.html', context) base.html: <nav id="header-nav"> <ul id="nav-ul" class="menu font-reg clearfix"> <li class="menu-item menu-item-has-children"> <a href="">Blog<span class="sub-drop-icon fa fa-angle-down"></span></a> <ul class="sub-menu sub-menu-first"> {% for category in category_list %} <li><a href="#">{{ category.name }}</a></li> {% endfor %} </ul> </li> <li class="menu-item menu-item-has-children"> <a href="about-1.html">About</a> </li> <li class="menu-item menu-item-has-children"> <a href="contact-1.html">Contact</a> </li> </ul> </nav> -
Problems with the response in API REST django
I try to link django API-REST with a form that has an associated model. Everything works well until I do the: return response.Response (serializer.data, status = status.HTTP_201_CREATED) JavaScript // To Save the Suggestion let ajax_suggestion_save = function (type, url, data, context) { let name_dm = $('#name-db-saved').val(); $.ajax({ type: type, url: url, data: data, context: context, beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, success: function (response) { $.niftyNoty({ type: "success", container: 'floating', title: 'Your information was saved successfully.', message: 'We much appreciate your interest of contact us, part of the growth of this platform it is base on your collaboration through your ideas.', closeBtn: true, timer: 4000 }); }, error: function (response) { if (Object.keys(response.responseJSON).length >= 1) { $.each(response.responseJSON, function (key, value) { $.niftyNoty({ type: 'danger', container: 'floating', title: 'Ups, apparently we have problems saving your information.', message: 'Please check the following ' + 'Error in <strong> ' + key + ' </strong>, with the following error <strong> ' + value + ' </strong>.', closeBtn: true, timer: 4000 }); }); } else { $.niftyNoty({ type: 'danger', container: 'floating', title: 'Ups, apparently we have problems saving your information.', message: 'Ups, apparently we have problems saving … -
How can I get data between for instance 14:00 and 18:00 in Django filter?
> AvailableDate.objects.filter(start_time__gte=start_time, end_time__lte=end_time, status='1') That is the filter method. But it doesn't work -
Django model select players to play
i have Match and Game table, i want to choose players who will play in this match (bacause a team include more than 5 players. However a match play 5vs5) class Match(models.Model): name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) team1=models.ForeignKey('Team',related_name='team1',on_delete=models.PROTECT) team2=models.ForeignKey('Team',related_name='team2',on_delete=models.PROTECT) class Game(models.Model): name = models.CharField(max_length=255) match = models.ForeignKey(Match, on_delete=models.CASCADE) team1players=models.ManyToManyField(match.team1.player.all()) team2players=models.ManyToManyField(match.team1.player.all()) Error: 'ForeignKey' object has no attribute 'team1' -
'0' In Routing path is causing NoReverseMatch error
I have the following URL route defined: url( regex=r'^edit_meal/(?P<menu_item_id>\d+)/(?P<parent_item_id>\d+)/$', view=EditMealView.as_view(), name='edit_meal', ) When I pass the following URL, it gets the error posted just below it: http://localhost:8000/menu_manager/edit_meal/0/5/ Reverse for 'edit_meal' with arguments '(0,)' not found. 1 pattern(s) tried: ['menu_manager/edit_meal/(?P<menu_item_id>\\d+)/(?P<parent_item_id>\\d+)/$'] However, if I change the '/0/5/' to '/1/5/' (or any number other than '0'), it works fine. Also, if I use '/1/0/', there is no issue. How can I get the router to accept '0' in the first argument? Tag in template: {% url 'menu_manager:edit_meal' 0 menu.id %} -
django Static files in production server
my problem is with static files (img , styles)...my code working fine with no error with static files and the images appears when i run the server , but when i make the (debug = False) the images and styles disappear i ran my code on linux server ubntu.... how i make the static files appear with the (debug=false) ...thanx in settings.py that is my code STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'music/templates/'), ) in my html file the image tage is just like this <img src="{% static 'music/login.jpg' %}" width="300" height="300"> -
How to send a email from a form django
As the title says i am trying to send a email from a form, but is not working: As you can see: <form method="POST" action=''> {% csrf_token %} <div class="control-group form-group"> <div class="controls"> <label>Nombre completo:</label> <input type="text" class="form-control" id="nombre" required data-validation-required-message="Introduzca su nombre."> <p class="help-block"></p> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Asunto:</label> <input type="text" class="form-control" id="asunto" required data-validation-required-message="Introduzca el asunto del correo."> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Correo Electrónico:</label> <input type="email" class="form-control" id="email" required data-validation-required-message="Introduzca su correo electrónico."> </div> </div> <div class="control-group form-group"> <div class="controls"> <label>Mensaje:</label> <textarea rows="10" cols="100" class="form-control" id="contenido" required data-validation-required-message="Escriba su mensaje" maxlength="999" style="resize:none"></textarea> </div> </div> <button type="submit" class="btn btn-primary">Enviar mensaje</button> </form> This is my view: def contact(request): contactdata = contactData.objects.get() members = teamMembers.objects.filter(existencia=True) templates = Templates.objects.get(isSelected=True) categoria = Clasificacion.objects.filter(existencia=True) enterprise = enterprisedata.objects.get() content = request.POST.get('contenido', '') name = request.POST.get('nombre', '') email = request.POST.get('email', '') subject = request.POST.get('asunto', '') if request.method == 'POST' and email and name: send_mail(subject, content, email, ['kike1996@hotmail.com'], fail_silently=False) contexto = {'categoria':categoria,'templates':templates,'members':members, 'contactdata':contactdata,'enterprise':enterprise} return render(request, 'contact/contact.html', contexto) I am calling the form with the POST request, but is not sending anything!. Hope you can help me, thank you!. -
How to create a follow-system in Django 2
I am trying to create a following system, where users can see each others posts on their timeline. But i'm stuck on the follow system. I've tried to use a ManyToManyField class Friends(models.Model): users = models.ManyToManyField(User) I expect it to let me follow other people. -
id of my user table is increased unnaturally
I am using graphene-django library and I have a User model that is inherited from AbstractUser. The username attribute is unique and it's ok for me. But The problem is that when I try to add a user with duplicated username id of user table in database increases. What's your idea? -
Django Custom Management: trouble in writing command to pupulate data
I am new to django management commands! I am trying to write a commands to populate author... My models.py is: from django.db import models class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField(unique=True, blank=False, null=False) class Book(models.Model): book_name = models.CharField(max_length=10) summery = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) and i am tried to write a command but i failed.. this is my blog/management/commands/populate_author.py below: from django.core.management.base import BaseCommand, CommandError from blog.models import Author, Book class Command(BaseCommand): help = 'Populate author' def add_arguments(self, parser): def handle(self, *args, **options): Can anyone please help me to make it happen? -
Unusual behavior of form during the creation of a blog post and during the update of itself
I'm developing the backend of my personal blog and, using this tutorial for the date and time, I've created a form for the creation of a blog post. I notice two things: Even if I select one or more tags, they aren't added to the post. The post after the pubblication using this form doesen't have tags. But if I do the same thing via django admin I can't create a post without the tags. If I try to update an existing post the publishing date field is blank into the form but I can see the publication date in the details of the post. create_post.html <form class="" method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-sm-9"> <div class="form-group mb-4"> <div>{{ form.title }}</div> <label for="id_title"> <span class="text-info" data-toggle="tooltip" title="{{ form.title.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.title.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.description }}</div> <label for="id_description"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.description.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.description.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.contents }}</div> <label for="id_contents"> <span class="text-info" data-toggle="tooltip" data-placement="bottom" title="{{ form.contents.help_text }}"> <i class="far fa-question-circle"></i> </span> <small class="text-danger">{{ form.contents.errors }}</small> </label> </div> <div class="form-group mb-4"> <div>{{ form.header_image_link }}</div> <label … -
Django modelform widget attributes replaced or disregarded
I've been scratching my head over this for the last little while. I have been able to change the modelfield's field queryset and widget attributes, well somewhat! class InvoiceItemForm(ModelForm): UOM = forms.ChoiceField (choices = site_defaults.UOM) class meta: model = InvoiceItem fields = ['name', 'costcode', 'rate', 'quantity',] labels = {'name': 'Item', 'rate': 'Cost Per Unit', 'quantity': 'Base Quantity'} widgets = {'UOM': forms.Select(choices = site_defaults.UOM )} def __init__(self, current_user, current_project, *args, **kwargs): ''' Rendering custom ModelForm ''' super(InvoiceItemForm, self).__init__(*args, **kwargs) the_title = None the_instance = kwargs.get('instance', None) if the_instance: the_costcode = the_instance.costcode if the_costcode: the_title = the_costcode.title self.fields['costcode'].queryset = CostCode.objects.filter(project = current_project, item = 0) self.fields['costcode'].widget = forms.TextInput(attrs={'class': 'site-flex-select-large', 'value': the_title}) When this is rendered, the costcode field takes the right instance. Also, the class is shown as site-flex-select-large, but the title is shown as the instance.id and not the_title which is the instance.title (a text field is displayed with value of 192 instead of the title of the invoice item). Why is Django ignoring some changes and accepting some other changes to the field? I'm not sure if it is a relevant detail or not, but the modelform is used in an inlineformset: expenses_forms = self.InvoiceItem_InlineFormSet(instance = the_invoice, prefix='expenses', form_kwargs={'current_user': user, … -
Reverse for 'patient_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['patients/update/(?P<pk>[0-9]+)$']?
I made a view where users can edit the patients information and as I'm using a custom user model I had to make a custom update/delete view.The views are working when i enter them manually by the url but when i put a link reference to them by an anchor tag i get an error that it can't access the pk,I tried following many answers here and vids on YT but the error is still there Views.py def PatientUpdateView(request,pk=None): patient = get_object_or_404(models.Patient, pk=pk) form = forms.PatientForm(request.POST or None ,instance=patient) if form.is_valid() : patient = form.save(commit=False) patient.save() messages.success(request,"patient updated!") context = { 'patient': patient, 'form': form } return render(request,'patients/patient_edit_form_success.html',context) else: context = { 'patient' : patient, 'form': form, } return render(request, 'patients/patient_edit_form.html', context) and here's how i call it in an anchor tag <a class="btn btn-info btn-sm" href="{% url 'patients:patient_update' patient.pk %}">Open</a> I tried pk = patient.pk pk = pk and many other ways of calling it. -
How do you use downloaded templates in Django
I have found these really cool templates online and I would like to use them for building my website. Is there any way of not copying the links for bootstrapping but for me to use the templates downloaded and tweak them? I have looked online and all they suggested was bootstrapping. -
Django - How to serialize inheritance
I walked through the documentation at https://django-model-utils.readthedocs.io/en/latest/managers.html to learn more about the InheritanceManager.I won't add the models.py because it is the same as in the documentation. So, here is my views.py: class PlaceList(generics.ListAPIView): serializer_class = PlaceSerializer def get_queryset(self): return Place.objects.select_subclasses() As you can see, the line return Place.objects.select_subclasses() returns all the Bar, Restaurant or Place instance stored in the database. My serializers.py looks like the following: from rest_framework import serializers from genericRelations.models import Place, Restaurant, Bar class PlaceSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id', 'location') class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id', 'location', 'restaurant_name') class BarSerializer(serializers.ModelSerializer): class Meta: model = Bar fields = ('id', 'location', 'bar_name') I do not know how to modify the PlaceSerializer so that it also serializes/deserializes the subclasses of Place. E.g. something like 'if a Bar instance is encountered, then use the BarSerializer' and 'if a Restaurant instance is encountered, then use the RestaurantSerializer'. Note: When the URL is .../places/ then PlaceList is performed which results in this output: { "places": [ { "id": 1, "location": "Köln" }, { "id": 2, "location": "Köln" }, { "id": 3, "location": "Köln" }, { "id": 4, "location": "Köln" }, { "id": 5, "location": "Köln" … -
How to connect REST API built using Django Rest Framework with Flutter app
I am building an application to register details of user for which I have used Django rest framework for backend and Flutter for frontend. I am having no idea on connecting these two. Please help me. -
How do I validate a field based on it's initial value in forms.py?
I have a custom self.clean method in forms.py which contains a check on whether the POSTed date values overlap with existing records. In the case where the user edits their record, but does not change the dates, this validation stops the record update. How can I change the validation with If statement or otherwise dependant on if the user has modified the start_date or end_date fields? I've tried looking at things like self.get_initial() and self.has_changed() which seem to only be applicable in the view function? I'd rather validate in forms.py. If I could filter out the record currently being edited from my "overlap" validations, that may be the neatest solution. forms.py: class EditBookingForm(ModelForm): class Meta: model = Bookings #user not included as that is handled in views fields = ['start_date', 'end_date', 'type', 'approved', 'members', 'guests'] ... def clean(self): form_data = self.cleaned_data #check if dates overlap by more than one day (ie. can start/end on the same day) overlap_in = Bookings.objects.filter(start_date__lt=form_data['start_date'], end_date__gt=form_data['end_date']).count() overlap_st = Bookings.objects.filter(start_date__lt=form_data['start_date'], end_date__gt=form_data['start_date']).count() overlap_end = Bookings.objects.filter(start_date__lt=form_data['end_date'], end_date__gt=form_data['end_date']).count() overlap_same = Bookings.objects.filter(start_date=form_data['start_date'], end_date=form_data['end_date']).count() overlap_over = Bookings.objects.filter(end_date__gt=form_data['start_date'], start_date__lt=form_data['end_date']).count() overlap = overlap_end + overlap_in + overlap_same + overlap_st + overlap_over if overlap > 0: self._errors["start_date"] = ["Your dates overlap with an existing … -
display user profile images of chats
All is working good except of the fact that, i am trying to display user profile images of user who sent a chat message in a chat room . chatSocket.onmessage=function(e){ var tag_img=document.createElement('img'); var get_user=document.querySelector('#user').value var tagname=document.createElement('li'); var data =JSON.parse(e.data); // get the image and display document.querySelector('.img_tag').src=data.message.sender_img This is my consumer.py messaage_json={ 'user':me.username, 'message':message_object.message, 'sender':message_object.sender.username, 'sender_img':str(message_object.sender.profilepicture), 'created':str(message_object.created) } data_array=await self.get_data() #coverting data to string myResponse={ "message":messaage_json, } #broad cast the message event to be send # in the layaer await self.channel_layer.group_send( self.room_group_name,{ # call the chat_message method "type":"chat_message", #covert string data to json objects "text":json.dumps(myResponse), } ) It prints out the user profile image path in the media file, but cannot display the image using javascript. Note i am using django . -
I have a field: forms.CheckboxSelectMultiple(). How can I access it's options in JS?
I'm setting up a form, which has a field = forms.CheckboxSelectMultiple() The field is a ManyToMany field of a model. It'll display the options that the model has to relate to the other fields. models.py class Tag(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Entry(models.Model): # ...other fields tags = models.ManyToManyField(Tag, related_name='entries', blank=True) #other fields... And the form: class NewEntryForm(forms.ModelForm): # ...other code 'tags': forms.CheckboxSelectMultiple(attrs={ 'class': 'form_new_entry_tags', 'id': '' }), I want to access the text of the options (the options would be all the tags available), in JS, so as to display it on another place when the checkbox is checked. The text is not the input's value, as one might think it'd be. It is html that comes directly from the django form, which seems to not have a selector. I'm trying to do this: let display_when_checked = document.querySelector("#display") let checkbox = document.querySelector("#checkbox") checkbox.addEventListener('change', function() { if (this.checked) { display_when_checked.innerHTML = checkbox_value } } But I can't access checkbox_value. And the HTML is: <ul> <li> <label> <input type="checkbox" value="1" class="form_new_entry_tags"> "text of the option" <--- I want to access this. </label> </li> </ul> When I hover with the dev tools in the browser, the selector for … -
Request attributes
I have a page, and there are 3 types of button(apple,banana, orange), by clicking the first button, a form comes up to get information. The first button should send information to the apple Model, the banana button should send information to the banana Model and so orange! here is my models.py: from django.db import models class Apple(models.Model): first_name = models.CharField(max_length=100) class Banana(models.Model): first_name = models.CharField(max_length=100) class Orange(models.Model): first_name = models.CharField(max_length=100) my forms.py: from django import forms class Fruit(forms.Form): first_name = forms.CharField(max_length=100) my views.py: def fruitForm(request): form = Fruit() if request.method == 'POST' & request.id == 'apple': form = Fruit(request.POST) if form.is_valid(): Apple.objects.create(**form.cleaned_data) elif request.method =='POST' & request.id =='orange': form = Fruit(request.POST) if form.is_valid(): Orange.objects.create(**form.cleaned_data) elif request.method =='POST' & request.id =='banana': form = Fruit(request.POST) if form.is_valid(): Banana.objects.create(**form.cleaned_data) return render(request, 'main/home.html', {'form':form}) my home.html: <button class='btn btn-primary' data-target='#orange'> Add </button> <form action=# method="POST" id = "orange"> {% csrf_token %} {{ form.as_p }} </form> well, when I try go to main page (where the buttons are), I got this error: 'WSGIRequest' object has no attribute 'id' request doesn't have the id attribute, right? So, How can I get specific data to save in relative model? -
AttributeError: module 'asyncio' has no attribute '_get_running_loop'
I am using channels to implement WebSockets. I am trying to send data through websocket from post_save django signal. Below is my code. signals.py @receiver(post_save, sender=CheckIn) def send_data_on_save(sender, instance, **kwargs): channel_layer = get_channel_layer() stats = get_stats() async_to_sync(channel_layer.group_send)( 'dashboard', { 'type': 'send_data', 'message': stats } ) analytics = get_analytics() async_to_sync(channel_layer.group_send)( 'analytic', { 'type': 'send_data', 'message': analytics } ) consumers.py class DashboardConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'dashboard' # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'send_data', 'message': message } ) # Receive message from room group def send_data(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) this same piece of code is working on my local machine(windows) but when i am trying to run this code on server(ubuntu 16.04) i am getting bellow error: Traceback Exception inside application: module 'asyncio' has no attribute '_get_running_loop' File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step result = coro.throw(exc) File "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, … -
The delete view doesn't erase the correspondent object
I'm developing the backend of my personal blog and I've create a view that delete a single tag of the post. views.py from django.shortcuts import get_object_or_404, redirect, render from django.utils.text import slugify from .forms import BlogTagForm from .models import BlogTag def deleteBlogTag(request, slug_tag): if request.method == 'POST': tag = BlogTag.objects.get(slug_tag=slug_tag) tag.delete() return redirect('tag_list') models.py from django.db import models from django.urls import reverse class BlogTag(models.Model): tag_name = models.CharField( 'Tag', max_length=50, help_text="Every key concept must be not longer then 50 characters", unique=True, ) slug_tag = models.SlugField( 'Slug', unique=True, help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents", ) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag}) class Meta: ordering = ['tag_name'] urls.py path("tags/", views.listTagAdmin, name='tag_list_admin'), path("create-tag/", views.createBlogTag, name='create_tag'), path("update-tag/<str:slug_tag>/", views.updateBlogTag, name='update_tag'), path("delete-tag/<str:slug_tag>/", views.deleteBlogTag, name='delete_tag'), tag_list.html <table class="table table-striped"> <thead class="bg-secondary text-white"> <tr> <th colspan="3"><h1 class="text-center"><strong>Tag List</strong></h1></th> </tr> <tr> <th colspan="1">Tag</th> <th colspan="1">Related Posts</th> <th class="text-center" colspan="1">Actions</th> </tr> </thead> <tbody> {% for tag in tag_list %} <tr> <td colspan="1">{{ tag.tag_name }}</td> <td colspan="1"><a href="{{ tag.get_absolute_url }}">{{ tag.tag_blogpost.count }}</a></td> <td colspan="1"> <div class="row justify-content-md-center"> <a class="btn btn-success btn-sm mx-1" href="{% url 'update_tag' slug_tag=tag.slug_tag %}">Update</a> <button class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal" data-target="#deleteModal">Delete</button> <div class="modal fade" … -
Django E.408, E.409 and E.410 errors on runserver
I am installing a new Django project using virtualenv, all in the normal way. My version of Python is 3.7.3, and django is 2.2.3. If I do python manage.py runserver, I get the following errors: ?: (admin.E408)'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. Here is my settings.py, and you can see that those middleware are there. """ Django settings for fcc_new project. Generated by 'django-admin startproject' using Django 1.9.4. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = MY KEY goes here # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django model CreateView does not render form fields in HTML
I am trying to setup a class based 'CreateView' for a model in my django site, but when the create html page renders, the model fields are not rendered. Only the submit button shows up on the web page. However, when debugging, I overrided the 'form_invalid' method in the class view, and the form object had the required HTML for all fields stored in the object. If I take this HTML and manually add it to the HTML of the create page in the browser I can fill out the fields and post the data to the database. At this point I have not found an obvious answer as to why the form fields are not rendered so any help on this would be greatly appreciated. environment used: python 3.7.3, django 2.2.3 models.py: class Alert(models.Model): RAIN = 'Rain' SNOW = 'Snow' COLD = 'Cold' HEAT = 'Heat' WEATHER_CHOICES = [ (RAIN, 'Rain'), (SNOW, 'Snow'), (COLD, 'Cold'), (HEAT, 'Heat'), ] DAILY = 'Daily' WEEKLY = 'Weekly' INTERVAL_CHOICES = [ (DAILY, 'Daily'), (WEEKLY, 'Weekly'), ] weather_type = models.CharField(max_length=15, choices=WEATHER_CHOICES, default=RAIN) interval = models.CharField(max_length=10, choices=INTERVAL_CHOICES, default=DAILY) search_length = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) active = models.BooleanField(default=False) views.py: class CreateAlertView(LoginRequiredMixin, CreateView): template_name = 'users/alert_form.html' …