Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Order by related fields of different models in Django Admin
I want to order by the business_name, but the ordering isn't working due to some relationships, below is my first model : class LoanApplication(models.Model): loan_id = models.CharField( 'Loan Application ID', max_length=40, unique=True, null=True, blank=True) loan_taker = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, null=True, blank=True, verbose_name='Customer Profile', related_name='loan_entries') submitted_date = models.DateTimeField( 'Submitted Date', null=True, blank=True) then, I have the CustomerProfile model as below : class CustomerProfile(models.Model): customer_id = models.CharField( 'Customer Profile ID', max_length=64, unique=True, null=True) cooperation_partner = models.ForeignKey( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Jurisdiction'), related_name='partner_user_profile') user = models.OneToOneField( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('User'), related_name='user_profile') tipster_partner = models.ForeignKey( TipsterPartner, on_delete=models.PROTECT, null=True, blank=True, verbose_name='Tipster Partner') So, I wanted to point to the Business model , it's as below : class Business(models.Model): business_id = models.CharField( 'Business ID', max_length=64, unique=True, null=True, blank=True) business_name = models.CharField(_('Business'), max_length=128) business_address_street = models.CharField( 'Business Address Street', max_length=50, blank=True) then, we have the last one which is the CustomerProfileBusiness as below : class CustomerProfileBusiness(models.Model): business = models.ForeignKey( Business, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Business'), related_name='customer_profile_relation') correlative_id = models.CharField( _('Business ID'), max_length=64, unique=True, blank=True, null=True) customer_profile = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, verbose_name=_('Customer Profile'), blank=True, null=True, related_name='business') Now, I do the ordering in the Admin page of the LoanApplication as below : @admin.register(LoanApplication, site=admin_site) class LoanApplicationAdmin(admin.ModelAdmin): ordering = ( … -
DRF SearchFilter with Multiple Models and Uncommon Search Fields
I am using DRF SearchFilter with Multiple Model View to search across multiple models. However, the models do not share common search fields. DRF gives an error because ModelA does not contain b_name and c_name, etc. My quick and dirty workaround is to add dummy fields to the models as needed. Is there a way to allow fields names in search_fields even if the model doesn't have that field? Another approach is to aggregate 3 separate ListAPIViews with respective search_fields for ModelA, ModelB, and ModelC in to one view. Is that possible? class ModelA(models.Model): a_name = models.CharField(null=True, blank=True) a_title = models.CharField(null=True, blank=True) class ModelB(models.Model): b_name = models.CharField(null=True, blank=True) class ModelC(models.Model): c_name = models.CharField(null=True, blank=True) class SearchListView(ObjectMultipleModelAPIView): querylist = [ { 'queryset': ModelA.objects.all(), 'serializer_class': ModelASerializer, }, { 'queryset': ModelB.objects.all(), 'serializer_class': ModelBSerializer, }, { 'queryset': ModelC.objects.all(), 'serializer_class': ModelCSerializer, }, ] filter_backends = [filters.SearchFilter] search_fields = ['a_name', 'a_title', 'b_name', 'c_name'] -
Allow only emails to access site where logos are (Django)
I have a page mysite.com/logos containing images. I want to be able to link to those emails when sending out news-letters (instead of attaching them), but I don't want users (or others) to be able to access them. Right now people can just go to "mysite.com/logos" - I would prefer that'll throw an 403/404 error for all, apart from the emails (and admins). -
I am creating an ecommerce Website .I am not able to list out products from django using Rest API .i am using axios
The above is the code which I have written in my home.vue , when I run the local server it runs without any error but its not listing out the products . I am usig Django for the Backend and REST API to fetch details about product using api.The problem is that I am not able to list out products on the front-end.The below code is th Home.Vue that portion is not displaying while I am inspecting in Google Chrome. <div class="column is-3" v-for="product in latestProducts" v-bind:key="product.id" > <div class="box"> <figure class="image mb-4"> <img :src="product.get_thumbnail"> </figure> <h3 class="is-size-4">{{ product.name }}</h3> <p class="is-size-6 has-text-grey">${{ product.price }}</p> View Details </div> </div> <script> // @ is an alias to /src import axios from 'axios' export default { name: 'Home', data() { return{ latestProducts: [], } }, components: { }, mounted(){ this.getLatestProducts() }, methods: { getLatestProducts() { axios .get('http://127.0.0.1:8000/api/v1/latest-products/') .then(response => { this.latestProducts = response.data }) .catch(error =>{ console.log(error) }) } } } </script> -
Django HttpResponseRedirect(reverse())
return HttpResponseRedirect(reverse('pollresult', agrs=[str(obj.id)])) return HttpResponseRedirect(reverse('pollresult', agrs=[str(obj.id)])) TypeError: reverse() got an unexpected keyword argument 'agrs' -
How to pass parameters to request during testing?
I run the test via Client(). post, but request.POST does not contain the passed dictionary test.py from django.test import TestCase from django.test.client import Client class AccountTests(TestCase): def setUp(self): self.email = 's@s/com' self.name = 'John' self.mobile = "+799999999" def test_user_login(self): c = Client() response = c.post('/login-otp/', {'email': self.email, 'name': self.name, 'mobile': self.mobile}, follow=True) views.py def login_otp(request): mobile = request.session['mobile'] # the interpreter does not see the "mobile" key context = {'mobile': mobile} if request.method == 'POST': otp = request.POST.get('otp') -
How to resolve Django Administration Problem with "no such table"?
I am able to follow the instructions for Creation and Activation for Database Model from the book "Django for Beginners" by William S. Vincent. I am able to reach the first image, but then after that 'get' and 'post' requests probably are not working. adding my code for models.py : from django.db import models class Post(models.Model): text = models.TextField() The following is from admin.py file: from django.contrib import admin from .models import Post admin.site.register(Post) -
Using a django app as a central authentication system to other django apps
(I am relatively new to Django, so sorry if I was misunderstanding anything ^^") so let say I have app1 and app2, and I want to implement the same groups, roles and permission through these two apps by only having one database. my idea was to create a central back end server that the two app authenticate through and grabs the roles from it. essentially this can be used for SSO(Single sign on) later. but now the target is to authenticate the user logging through one app and get his roles and groups from there. In Django documentation I found "Authentication using REMOTE_USER": which should allow me to do remote authentication (which is my target), was able to make it run but how am I supposed to give it the link of the Django authentication server. my understanding is that after setting this remote user authentication, all groups, roles and permission checks doesn't need to be changed since Django should have access to the remote server that it authenticates through. I hope that I wasn't misunderstanding "Authentication using REMOTE_USER" concept. also if there is any other ideas on how to implement this, please let me know. Thank you ! -
WAGTAIL - users who don't have access to publish pages are also getting option to approve and publish pages in home admin page
I am using wagtail for a website and I have created a group for editors which has add and edit permission for all the pages. Editors have to submit pages for moderation for publishing but they are also getting the Awaiting your review section on the home page and they have the right to publish a page in that section. I don't know why this is happening. Is there any bug or Am I missing something? -
Django Admin Select All in a List
I am working on React DRF project. I have my models designed like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) My Admin Panel for the authors field shows data like this authors Author A Author B Author C Author D Currently, Only one the Author (for example - Author A) is selected by default. Manually, I am able to select multiple authors by holding the control key. Is there any way to automatically select all the Authors in the author list whenever data gets added to this field? Thanks for your time in advance. -
Django - create a list of IDs from Session and filter it
I have a view, where I add products via post request and add it in sessions, but after I filter this list, I didn't get any results: views.py: Artikler_List = Products.objects.filter(UserID_id=user_id) ... if 'add_product' in request.POST: product_id = request.POST.get('product_id') request.session['product_id'] = product_id request.session.modified = True return redirect('add_order_view') try: order_product_ids = request.session.get('product_id', []) print(order_product_ids) order_product_ids.insert(len(order_product_ids), Artikler_List.ID) #print(order_product_ids) choosen_products = Products.objects.filter(ID__in=[order_product_ids]) print(choosen_products) except: choosen_products = None Is it not the correct way to create a list? -
POST http://localhost:16/auth/registration/ 400 (Bad Request) in Django and Reactjs
I am making a registration in django and reactjs project, i use django rest auth for registration api, but i am having a problem, when i send request to server, it responses: POST http://localhost:16/auth/registration/ 400 (Bad Request) I don't know how to fix this, can anyone help me ? this is my code ! Register.js import React from 'react' import axios from 'axios' class Register extends React.Component { constructor(props) { super(props) this.state = { username: '', email: '', password1: '', password2: '', } this.OnChangeUsername = this.OnChangeUsername.bind(this) this.OnChangeEmail = this.OnChangeEmail.bind(this) this.OnChangePassword1 = this.OnChangePassword1.bind(this) this.OnChangePassword2 = this.OnChangePassword2.bind(this) this.OnSubmit = this.OnSubmit.bind(this) } OnChangeUsername(event) { this.setState({ username: event.target.value }) } OnChangeEmail(event) { this.setState({ email: event.target.value }) } OnChangePassword1(event) { this.setState({ password1: event.target.value }) } OnChangePassword2(event) { this.setState({ password2: event.target.value }) } OnSubmit(event) { event.preventDefault() axios.post('http://localhost:16/auth/registration/', { username: this.state.username, email: this.state.email, password1: this.state.password1, password2: this.state.password2, }) .then(res => { alert('Registered !') this.props.history.push('/') }) } render() { return ( <div> <form onSubmit={this.OnSubmit}> <input type="text" name="username" value={this.state.username} onChange={this.OnChangeUsername} /> <br></br> <input type="text" name="email" value={this.state.email} onChange={this.OnChangeEmail} /> <br></br> <input type="text" name="password1" value={this.state.password1} onChange={this.OnChangePassword1} /> <br></br> <input type="text" name="password2" value={this.state.password2} onChange={this.OnChangePassword2} /> <br></br> <button>Register</button> </form> </div> ) } } export default Register; -
Django Filter - how to call a single method for any combination of filter?
I'd like all my filters to route to a single method, so I can look at each and decide logic based on which ones are set. I have this working, but each filter is now calling the same method once, leading below code to print hi 4 times. Is there a best practice way to route all filters to a single method? I'd like hi to be only printed once here, and wondering if I can avoid using a hacky solution. class CityFilter(FilterSet): start_date_i = django_filters.DateTimeFilter(field_name='dept_date', method='filter_city') start_date_j = django_filters.DateTimeFilter(field_name='dept_date', method='filter_city') end_date_i = django_filters.DateTimeFilter(field_name='ret_date', method='filter_city') end_date_j = django_filters.DateTimeFilter(field_name='ret_date', method='filter_city') class Meta: model = models.City def filter_city(self, queryset, name, value): print('hi') data = self.data sdate_i = data.get('start_date_i') sdate_j = data.get('start_date_j') edate_i = data.get('end_date_i') edate_j = data.get('end_date_j') # do expensive stuff and build queryset from all filter name / values return queryset -
how can I change the user and the value of product(Model) after wallet transaction
here is my model.py, Where Customer is the one to make orders and purchase Products. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True) phone = models.CharField(max_length=12, null=True) def __str__(self): return self.name class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) coinid = models.CharField(max_length=255, null=True) digit = models.CharField(max_length=18, null=True) ctp = models.FloatField(max_length=100, null=True) transection_id = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=250, null=True, blank=True) date_created = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.coinid def get_absolute_url(self): return reverse("core:detail", kwargs={ 'slug': self.coinid }) class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) def __str__(self): return self.user.username in views.py, Here I want to replace the user(Product.user) of the product by sender sending amount from wallet def buy_c(request, ok): ctp_val = Product.objects.get(id=ok) msg = "Enter Details" if request.method == "POST": try: username = request.POST["username"] amount = request.POST["amount"] senderUser = User.objects.get(username=request.user.username) receiverrUser = User.objects.get(username=username) sender = Balance.objects.get(user=senderUser) receiverr = Balance.objects.get(user=receiverrUser) sender.balance = sender.balance - float(amount) receiverr.balance = receiverr.balance + float(amount) if senderUser == receiverrUser: return Exception.with_traceback() else: sender.save() receiverr.save() msg = "Transaction Success" return redirect("/user") except Exception as e: print(e) msg = "Transaction Failure, Please check and try again" context = {"coin": ctp_val, "msg":msg} return render(request, 'coinwall.html', context) here is my template coinwall.html <tr> <th>username</th> <th>Coin Id</th> <th>current … -
2 different references from the same object to two different objects from the same class - DJANGO database
I want to have a match object with two team references. I.E(old json database example): I would like to easeliy be able to access each team and possibly swap side. That's why I want to use Django example 2, as then I can reference each team from the Match Object. But example gives an error about each reference duplicating each other... { "dateTime": "", "matchID":"0fb86bcf-c700-4429-b5a9-558ca9b95a03", "team1ID":"e372b7f4-008f-4503-beee-1d6756361fea", "team2ID":"802b4705-d812-4a88-9246-b14bd18938d8", "format":3, "division":"Relegation", "league":leagueRef, "game":leagueRef, } Django example 1: class Match(models.Model): ... team = models.ManyToManyField( Team, on_delete=models.CASCADE, ) Django example 2: class Match(models.Model): ... team1 = models.OneToOneField( Team, on_delete=models.CASCADE, ) team2 = models.OneToOneField( Team, on_delete=models.CASCADE, ) -
Django Exception Type: RelatedObjectDoesNotExist Exception Value: User has no shopper
I am getting the following error: Exception Type: RelatedObjectDoesNotExist ; Exception Value: User has no shopper. below is my models.py file: Below are the given models for this project from django.db import models from django.contrib.auth.models import User class Shopper(models.Model): email = models.CharField(max_length=100,null=True) user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100,null=True) def __str__(self): return self.name class Item(models.Model): itemName = models.CharField(max_length=100,null=True) itemPrice = models.FloatField() img = models.ImageField(null=True,blank=True,upload_to='static\images') def __str__(self): return self.itemName class TotalOrder(models.Model): shopper = models.ForeignKey(Shopper, on_delete=models.SET_NULL,blank=True,null=True) dateOfOrder = models.DateTimeField(auto_now_add=True) isDone = models.BooleanField(default=False,null=True,blank=False) orderId = models.CharField(max_length=100,null=True) def __str__(self): return str(self.id) class ItemToOrder(models.Model): dateOfAdded = models.DateTimeField(auto_now_add=True) item = models.ForeignKey(Item,on_delete=models.SET_NULL,blank=True,null=True) order = models.ForeignKey(TotalOrder,on_delete=models.SET_NULL,blank=True,null=True) quantity = models.IntegerField(default=0,null=True,blank=True) And here is where I am trying to access this in the view.py file: def cart(request): if request.user.is_authenticated: shopper = request.user.shopper order, created = TotalOrder.objects.get_or_create(shopper = shopper,isDone=False) items = order.itemtoorder_set.all() else: items = [] context = {'items':items} return render(request, 'store/cart.html', context) Thank you so much for the help! -
Download videos using django didn't work with Iphone
Why download videos from django doesn't work with Iphone but it's work with android and windows my view def download_videos(request, pk): video = Video.objects.get(pk=pk) response = HttpResponse( video.video, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="fromCubeLinda.mp4"' return response The html template <a id="adown" href="{% url 'video:video_download' video.pk %}" target="_blank">Download</a> -
I get an error when I try to deploy to Heroku with simpleJWT version 4.6.0
When I install djangorestframework-simplejwt 4.6.0 in Django and try to deploy it to Heroku, I get the following error. remote: Downloading djangorestframework-3.12.2-py3-none-any.whl (957 kB) remote: ERROR: Could not find a version that satisfies the requirement djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19)) (from versions: 1.0, 1.1, 1.2, 1.2.1, 1.3, 1.4, 1.5.1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.1, 3.0, 3.1, 3.2, 3.2.1, 3.2.2, 3.2.3, 3.3, 4.0.0, 4.1.0, 4.1.1, 4.1.2, 4.1.3, 4.1.4, 4.1.5, 4.2.0, 4.3.0, 4.4.0) remote: ERROR: No matching distribution found for djangorestframework-simplejwt==4.6.0 (from -r /tmp/build_5927f5b0/requirements.txt (line 19)) I tried installing and deploying 4.4.0 to see if I could find 4.6.0, and I was able to deploy it, but when I tried to start and access it with python manage.py runserver, the 'str' object has no attribute ' decode'. Why does this happen? I would appreciate it if you could tell me how to feed them. -
Django ModelForm is not Displaying Customizations in forms.py
I have created a form that allows users to create a request for a ride that saves to a table in my database. The form works and can save data. Here is my code: forms.py: from django import forms from .models import Post import datetime from django.utils.translation import gettext_lazy as _ DESTINATION_LOCATIONS = [ ('RedMed','Red Med'), ('OOSM','Oxford Bone Doctor'), ('BSMH','Baptist Street Memorial Hosptial') ] class RiderRequestForm(forms.ModelForm): riderLocation = forms.CharField(label='Pickup Location') destination = forms.ChoiceField(widget=forms.Select(choices=DESTINATION_LOCATIONS)) date = forms.DateTimeField(initial= datetime.date.today) addSupport = forms.CharField(max_length=200, required=False) class Meta: model = Post fields = ['riderLocation', 'destination','date','addSupport'] labels = { "riderLocation": _('Pickup Address'), "destination": _("Select Destination: "), "date": _("Enter Time to be Picked Up"), "addSupport": _("List any additional things we should know: "), } models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): riderLocation = models.CharField(max_length=200) destination = models.CharField(max_length=200) date = models.DateTimeField() date_created = models.DateTimeField(default=timezone.now) rider = models.ForeignKey(User, on_delete=models.CASCADE) addSupport = models.CharField(max_length=200, null=True) def __str__(self): return self.destination def get_absolute_url(self): return reverse('request-viewDetail', kwargs={'pk': self.pk}) The HTML for the form post_form.html: {% extends 'homepage/homepageBase.html' %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> <div class="registerField"> {% csrf_token %} <fieldset class='form-group'> <legend … -
Paginating resulted filtered from Django form
I am trying to paginate resulted filtered from Django form GET request. However, when I click the second page it redirects me to the form page. I searched for similar questions and tried several approaches but somehow this still does not work. Below is the screenshots of my code. Any help will be appreciated. view.py def get_pictures_by_filters(request): if request.method == 'GET': form = GetPictureForm(request.GET) if form.is_valid(): name = form.get_name() problem = form.get_problem() language = form.get_language() pictures = Picture.objects.filter(relatedGame=name, language__iregex=r'.*' + language) if problem: for p in problem: pictures = pictures.filter(problem__contains=p) paginator = Paginator(pictures, 1) page = request.GET.get('page') try: pictures = paginator.page(page) except PageNotAnInteger: pictures = paginator.page(1) except EmptyPage: pictures = paginator.page(paginator.num_pages) context = {'list_pictures': pictures, 'page_obj': pictures} return render(request, 'picture/show_pictures_by_filter.html', context) form = GetPictureForm() context = { 'form': form } return render(request, 'picture/get_pictures_by_filter.html', context) urls.py path('pictures/filter', views.get_pictures_by_filters, name='get-pictures'), forms.py class GetPictureForm(forms.Form): def __init__(self, *args, **kwargs): super(GetPictureForm, self).__init__(*args, **kwargs) games = [(g.name, g.name) for g in Game.objects.all().order_by('-id')] problems = [(p.name, p.name) for p in Problem.objects.all()] self.fields['项目名称'] = forms.CharField(required=True, widget=forms.Select(choices=games)) self.fields['语种'] = forms.CharField(required=False) self.fields['问题'] = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=problems) def get_name(self): data = self.cleaned_data['项目名称'] return data def get_problem(self): data = self.cleaned_data['问题'] return data def get_language(self): data = self.cleaned_data['语种'] return data -
Best Django design with constant updating data
I’m making a website with Django framework with MySQL for database to display some data (e.g. daily stock prices for many stocks). Everyday, I would like to refresh all the data in the database to the latest data. There’s a lot data so I want to replace the entire database instead of inserting new entries. Is there an elegant way of achieving this? Is this kind of operation supported by relational databases like MySQL. Thanks! -
Setting cookies in django without a response
I want to be able to set a cookie on my django site when somebody creates an account. This is currently my view: from django import forms from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.core.mail import send_mail CARRIER_CHOICES =( ('@txt.freedommobile.ca', 'Freedom Mobile'), ('@txt.luckymobile.ca', 'Lucky Mobile'), ('none', 'None'), ) class RegisterForm (forms.Form): username = forms.CharField() password = forms.CharField() check_password = forms.CharField() email = forms.EmailField() phone = forms.IntegerField(required=False) carrier = forms.ChoiceField(choices=CARRIER_CHOICES, required=False) def register (request): form_error = 'none' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] check_password = form.cleaned_data['check_password'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] carrier = form.cleaned_data['carrier'] phone = str(phone) if password == check_password: phone_email = phone + carrier user = User.objects.create_user(username, email, password) user.is_staff = False user.is_active = True user.is_superuser = False send_mail( 'TachlisGeredt.com Account', 'Congrats! You have succesfully created an account with TachlisGeredt.com!', 'contact@tachlisgeredt.com', [email], fail_silently=False, ) return redirect ("/register/success") else: form = RegisterForm(request.POST) return render (request, 'register.html', {'form':form}) I'ver tried making cookies a million different ways but its really confusing. They all seem to need me to make a variable called 'response', do 'response.set_cookie' or whatever the command is, and then do 'return response'. … -
React-Django: How to send different functional components (React) to Django Views?
So I am new to React and I can currently create different functional components when I use npx create-react-app appname but if I want to "package" these files and send them to my Django's view page, what is the best way to do this? I am having some trouble with webpack configuring everything in the methods I've attempted. I am trying to create a web app. Thank you. -
DJANGO not returning context in my html template
why this context not rendering in my html template: return render(request, 'index.html',{'message_name':name}) This context will print user name after successful submit my contact form. here is my code: views.py @csrf_exempt def home_view(request,*args,**kwargs): name = None if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] save_details = Contact(name=name,email=email,subject=subject,message=message) save_details.save() return HttpResponseRedirect("http://127.0.0.1:8000/") return render(request, 'index.html',{'message_name':name}) else: print("not submitted") else: contact_form = ContactForm() return render(request, 'index.html',{'form':contact_form}) app urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.home_view, name="home"), ] root urls.py from django.contrib import admin from django.urls import path,include from pages import urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] index.html <!--===== CONTACT =====--> <section class="contact section" id="contact"> <h2 class="section-title">Contact</h2> {% if message_name %} <div class="centerTest"> <h1> Thanks {{ message_name }} for your message. We will get back to you very soon</h1> </div> {% else %} <div class="contact__container bd-grid"> <form action="#contact" method = "POST" class="contact__form"> {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endfor %} <label>Name:</label> {{ form.errors.name }} <input type="text" placeholder="Name" name="name" class="contact__input" {% if form.is_bound %}value="{{ form.name.value }} {% endif %}"> <label>Email:</label> {{ form.errors.email }} <input type="mail" … -
ModelForm in Django not showing
I'm trying to display a basic form in django but does not render the form once I run the server, I would appreciate if you could help me with these, here my code. models.py STATUS_OPTIONS =( ('OP', 'OPEN'), ('CL', 'CLOSED') ) class Employee(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=200) status = models.CharField(max_length=50, choices=STATUS_OPTIONS) password = models.CharField(max_length=100) def __str__(self): return self.first_name forms.py from django import forms from .models import Employee class EmployeeForm(forms.Form): class Meta: model = Employee fields = "__all__" urls.py from django.urls import include, path from . import views urlpatterns = [ path('', views.create_employee), ] view.py from .forms import EmployeeForm # Create your views here. def create_employee(request): form = EmployeeForm() return render(request, 'employee/create_employee.html', {'form':form}) create_employee.html <h1>Formu</h1> <form action="" method='POST'> {{form.as_p}} <input type="submit"> </form> When I run the program the only thing rendered is the tag, any idea?