Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Filter by custom field
I have Serializer which defines a custom column, in the serializers.py which I am trying to filter a query on. The itemsoutstanding column example below, I am trying to filter it from my view but it returns "is not defined" class OverView(serializers.ModelSerializer): itemsoutstanding = serializers.SerializerMethodField() class Meta: model = Order fields = ['id','total_price', 'created_at','itemsoutstanding'] def get_itemsoutstanding(self, obj): count= Items.objects.filter(order=obj.id).count() return count In my view I am trying to filter on the serializer column, but it says it's not defined queryset = Order.objects.all() serializer_class = OverView queryset = Order.objects.filter(shop=shop) queryset = queryset.filter(itemsoutstanding> 0) Is there any way to filter based on the serializer columns? -
How can I prepare dell intel i5 7th gen laptop to host django website using Ubuntu OS?
Operating System : Ubuntu 20.04 LTS I have a domain name DNS (from Godaddy). I just want to use my laptop as a server for my Django website. If Yes then Plz suggest me server and other requirements like Gunicorn. I have go through many tutorials. -
Unknown field(s) () specified for Offer
I'm quite new to django and currently have a problem, which I trouble to solve I'm getting Unknown field(s) () specified for Offer views.py from django.views.generic.edit import CreateView from django.urls import reverse_lazy from .models import Buyer, Seller, Offer class OfferCreate(CreateView): model = Offer fields = ['category', 'car_brand', 'car_model', 'type', 'year_of_production', 'color', 'car_mileage', 'description', 'car_equipment', 'fuel_type', 'doors_number', 'seats_number', 'engine_capacity', 'seller', 'photos', '',] success_url = reverse_lazy("/") model Offer class Offer(models.Model): car_brand = models.CharField(max_length=64) car_model = models.CharField(max_length=64) category = models.IntegerField(choices=CATEGORY) type = models.IntegerField(choices=TYPE) year_of_production = models.SmallIntegerField() color = models.CharField(max_length=64) car_mileage = models.IntegerField() description = models.TextField() car_equipment = forms.MultipleChoiceField(choices=EQUIP) fuel_type = models.IntegerField(choices=FUEL_TYPE) doors_number = models.IntegerField(choices=DOORS_NUMBER) seats_number = models.IntegerField(choices=SEATS_NUMBER) engine_capacity = models.IntegerField() seller = models.ForeignKey(Seller, on_delete=models.CASCADE) photos = models.ImageField(upload_to='offers') any idea what is causing a problem? -
why the {% if post.is_liked %} doesn't work in home.html
I have passed the context of is_liked to from the PostListView to the home template, but why the if post.is_liked the statement doesn't work? I have an like_post function that when the user liked the post, the is_liked will equal to true and text will turn from not liked to liked. But why the if statements did not work(only showed not liked) in the template with no error messages? Or I have tried to change the if statements to {% post.user.is_liked %} and {% user.is_liked %}. But it still didn't work, what is the problem? thanks models.py class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes', blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py def home(request): context = { 'posts': Post.objects.all(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 is_liked = False def get_context_data(self, *, object_list=None, **kwargs): context = super(PostListView, self).get_context_data() posts = context['posts'] for post in posts: … -
Write a custom decorator to check if session is active in Django
Is this possible to write a decorator to check if a specific request session exists? Like user id. If not redirect to another page. Similar to login_required decorator. @session_active('user_id') def HomeView(request): return HttpResponse('') -
django type error,object of type 'ModelBase' has no len()
my views.py: def songs(request): object_list=song_thumb.objects.all() paginator = Paginator(song_thumb, 3) page = request.GET.get('page', 1) try: artists = paginator.page(page) except PageNotAnInteger: artists = paginator.page(1) except EmptyPage: artists = paginator.page(paginator.num_pages) return render(request, 'home.html', {'page':page,'artists':artists}) my pagination.html and home.html <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div> #home.html <div class="container"> {% include "pagination.html" with page=page_obj %} </div> I am getting a typerror.It shows that object of type 'ModelBase' has no len Tracebacks: Traceback Switch to copy-and-paste view C:\Python38\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Python38\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Python38\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars E:\coding\fyp\music\home\views.py in songs artists = paginator.page(page) … ▶ Local vars C:\Python38\lib\site-packages\django\core\paginator.py in page number = self.validate_number(number) … ▶ Local vars C:\Python38\lib\site-packages\django\core\paginator.py in validate_number if number > self.num_pages: … ▶ Local vars C:\Python38\lib\site-packages\django\utils\functional.py in get res = instance.dict[self.name] = self.func(instance) … ▶ Local vars C:\Python38\lib\site-packages\django\core\paginator.py in num_pages if self.count == 0 and not self.allow_empty_first_page: … ▶ Local vars C:\Python38\lib\site-packages\django\utils\functional.py in get res = instance.dict[self.name] … -
how to add static to my scripts in django
i have a datetimepicker created, but i have a little problem adding static to it my base.html,if i do i wont get what i want its just rendering a normal html,i want it to be in a way in which once clicked it shows the date and time as stated in my js, here is what i have tried base.html <script src="{% static 'js/bootstrap-datepicker.js' %}" type="c9dfb692cab9a2d000c13798-text/javascript"></script> <script src="{% static 'js/jquery.timepicker.min.js' %}" type="c9dfb692cab9a2d000c13798-text/javascript"></script> -
Django 3.0 tutorial - mysite/URL not working
I have completed all seven steps of the Writing your first Django app tutorial for 3.0. Everything works great, except the base site URL for 'mysite' at http://127.0.0.1:8000/. At the beginning of the tutorial, it worked, but it stopped working as I progressed/at the end. http://127.0.0.1:8000/admin/ works fine. Can anyone tell me what I'm doing wrong? Based on how the tutorial is structured, i.e. "add this and that and this and that," etc., that I overwrote something. Here is the error I'm receiving in my browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the error I'm receiving in Terminal: Not Found: / [20/Jun/2020 11:01:22] "GET / HTTP/1.1" 404 2027 Here is my polls/urls.py file: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Here is my … -
Django Allowed Hosts
I want only my front.domain.com to access the django API so i updated my settings.py . When i deployed i can access the django API via curl and postman so i'm confused here is there anything i'm missing ! settings.py DEBUG = False # deployment if DEBUG: FRONT_OFFICE_URL = 'http://127.0.0.1:4200/' ALLOWED_HOSTS = ['*'] # development CORS_ORIGIN_ALLOW_ALL = True # development else: FRONT_OFFICE_URL = 'https://front.domaine.com' ALLOWED_HOSTS = [FRONT_OFFICE_URL ] # deployment CORS_ORIGIN_WHITELIST = [FRONT_OFFICE_URL] CSRF_TRUSTED_ORIGINS = [FRONT_OFFICE_URL ] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] -
Django ModelForm not submitting
The views are rendering the correct values to the template and there are no errors when I try to submit the form. Instead when I try to submit the form nothing happens. Let me know if you guys need more pictures or information, and thanks for helping me out! -
Serve React with Django Server
I am following this tutorial in order to serve React through Django server, but I only get a blank page when I access http://localhost:8000/admin, and I get the following errors on Django local server console: [20/Jun/2020 17:05:08] "GET /admin HTTP/1.1" 200 2217 [20/Jun/2020 17:05:08] "GET /static/css/main.5f361e03.chunk.css HTTP/1.1" 404 1821 [20/Jun/2020 17:05:08] "GET /static/js/main.853c8ab9.chunk.js HTTP/1.1" 404 1815 [20/Jun/2020 17:05:08] "GET /static/js/2.6d20342a.chunk.js HTTP/1.1" 404 1806 [20/Jun/2020 17:05:08] "GET /static/js/2.6d20342a.chunk.js HTTP/1.1" 404 1806 [20/Jun/2020 17:05:08] "GET /static/js/main.853c8ab9.chunk.js HTTP/1.1" 404 1815 I made all, and only, the changes stated in the tutorial. Thanks for your help. -
The same validation for multiple views in django rest framework
I have created a number of API endpoints for accepting POST requests using DjangoRestFramework. For 5/6 of them, I need to have 1 key in the body present providing some data so for each view I have if (key not in request.data): return Response('please provide key', status=400) How can I remove this duplication across all views? -
Pulling Values From List Python
I am working in Django and I am saving the below variable as a list: manifestData = form.cleaned_data so if I print this it returns: [{'ProductCode': <Product: APPLES-1>, 'UnitQty': u'11', 'Price': u'11.00', 'Amount': u'121', 'DescriptionOfGoods': u'Washington Extra Fancy', 'Type': u'Cases', u'id': None, u'DELETE': False}, {'ProductCode': <Product: ORANGES-1>, 'UnitQty': u'1', 'Price': u'12.00', 'Amount': u'12', 'DescriptionOfGoods': u'SUNKIST ORANGES', 'Type': u'Cases', u'id': None, u'DELETE': False}] I need to pull the ProductCode values out of this and save them to variables. Really I need the values APPLES-1 and ORANGES-1 pulled from the list. What would my best approach be for this? Thanks! -
Access Denied Django : (1045, "Access denied for user 'darth_vader'@'151.33.241.48' (using password: YES)")
I am using django 3.0 and using MySQL database for my web application. My settings.py code is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'thirdihrms', 'USERNAME': 'admin', 'PASSWORD': 'xxxxxxxx', 'HOST': 'database-1.xxxxxxxxx.us-east-1.rds.amazonaws.com', 'PORT': '3306', } } And instead of connecting to the admin@151.33.241.48 it's getting connected to the darth_vader username. The darth_vader name is my ubantu machine (Local development environment) home user name. I see "darth_vader@Rushikesh-HP:~$ " when i open my terminal. The error message: Traceback (most recent call last): File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'darth_vader'@'157.33.241.48' (using password: YES)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/darth_vader/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv … -
Django Save Object "Receipts"
I'm building a Django web application, part of it involves an online ordering system for food. I want to make a "receipt" object to save transactions. My concern, however, is this - let's say I have an object Receipt that relates to Orders which relate to Items, if the items get edited or change over time, it will make the receipts look different down the line. Is there a way to save these at the moment of a transaction? I am implementing a "soft deletion" to my models to avoid deletion issues however I don't think this would protect against edits. -
Building wheel error mysqliclient pythonnet..FAIL
I'm trying to install requirement.txt file and it seems like there's some issue with build wheel of couple packages which I can't figure out. This is the error I'm getting Building wheels for collected packages: mysqlclient, ndg-httpsclient, newspaper, nltk, oauthlib, pycountry, pycryptodomex, PyDispatcher, pyjwkest, pyodbc, pyserial, python-instagram, python-Levenshtein, python-openid, pythonnet, PyYAML, randomcolor, redis, requests-file, simplejson, ssh-import-id, supervisor, Twisted, Unidecode, winpython, zope.interface, django-pure-pagination, stem Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/rehman/projects/wdpjsenv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-m500R2/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-m500R2/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-m7ljPY cwd: /tmp/pip-install-m500R2/mysqlclient/ Complete output (39 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat … -
Django: How to optimize and reduce repetitive code the django way?
I am new to development and to Django, still learning OOP but I wanted to learn better with some examples from the code that I created. I have created a function in my view file. The function is getting very long and probably I will have to make it longer. I think the if statement could be written as a function but not sure where to start. What would be a way to reduce the code making it easier to maintain. Here is the code: def processView(request, pk): process = ProcessInfo.objects.get(id=pk) #bottlenecks = get_object_or_404(ProcessBottlenecks, process_info_id=process.id) try: details = ProcessDetails.objects.get(process_info_id=process.id) except ProcessDetails.DoesNotExist: details = None try: score = ProcessScoring.objects.get(process_score_id=pk) except ProcessScoring.DoesNotExist: score = None try: assumptions = ProcessAssumptions.objects.get(process_rel_process=process.id) except ProcessAssumptions.DoesNotExist: assumptions = None color_bottleneck = None color_quality = None color_datacomplexity = None color_technology = None color_transformation = None color_driversforchange = None color_technology = None #B if score.tot_score_bottlenecks_scoring in range(0, 200): color_bottleneck = 'badge-primary' if score.tot_score_bottlenecks_scoring in range(100, 500): color_bottleneck = 'badge-danger' if score.tot_score_bottlenecks_scoring in range(500, 1000): color_bottleneck = 'badge-warning' if score.tot_score_bottlenecks_scoring >= 1000: color_bottleneck = 'badge-success' #P if score.tot_score_dataquality in range(0, 200): color_quality = 'badge-primary' elif score.tot_score_dataquality in range(200, 500): color_quality = 'badge-danger' elif score.tot_score_dataquality in range(500, 100): color_quality = 'badge-warning' … -
Django query with existing format
I have model like below class Books(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.CharField(null=True, blank=True) How to query that will return author1 - Book 1 - Book 2 - Book 3 author2 - Book4 - Book5 -
ModelFormMixin + DateDetailView
I have a DateDetailViewPage with a comment form. The GET requests works fine, but I have problems with POST. Below the view: class PostDateDetailView(ModelFormMixin, DateDetailView): template_name = 'blog/post_detail.html' queryset = Post.published.all() date_field = "publish" month_format='%m' form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self) obj = self.get_object() post_tags_pks = obj.tags.all().values_list('pk', flat=True) related_posts = self.queryset.filter(tags__in=post_tags_pks).exclude(pk=obj.pk) related_posts = related_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:3] context["related_posts"] = related_posts comments = obj.comments.filter(active=True) context["comments"] = comments context['post_id'] = obj.pk context['form'] = self.form_class return context def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) The error I'm receiving is 'PostDateDetailView' object has no attribute 'object'. This error comes when get_context_data() is called and tries: if self.object: Honestly, I can't figure out the reason of this error. I mean, why get_context_data works for GET and not for POST. Thanks in advance!! -
Beginner questions about Wagtail (in comparison with Django)
I'm a beginner learning Wagtail, and a lot of things are un-clear to me, and unfortunately not found sufficient explanation in Wagtail documentation. Please help and give me some answers, and I feel I'm on the edge of giving up on Wagtail and switching back to Django. Here are a few noob questions I have, How to handle POST request? I've watched a few tutorials at LearnWagtail.com, it seems in Wagtail, development is all about creating models, no need to set urls.py or views.py. And we could create Routable pages to respond to custom url-patterns. Question: but how to respond to POST request if without defining a view? I don't see any example of Routable page handling POST request. Is the home app the only entry to a Wagtail website? From what I see, home app is a default one created by Wagtail when a project is created. And the home.HomePage is the default page when I open the website on 127.0.0.1:8000. Question: so I cannot remove this home app? How to set urls.py or should we set them? For example, a typicall urls.py settings are as follows. And my understanding is the wagtail_urls will point to home.HomePage by default. … -
How to create two different user authentication table in django for two different type of users?
#Models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # User Model For registration --------------------------------------------------------------------------- class StudentUserManager(BaseUserManager): def create_user(self, name,email,gender, password,picture=None, ): """ Creates and saves a User with the given email and password. """ if not gender: raise ValueError('User must have a gender') if not email: raise ValueError('Users must have an email address') user = self.model( name = name, email=self.normalize_email(email), gender = gender, picture = picture ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, email, gender, password,picture=None,): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( name = name, email=self.normalize_email(email), gender = gender, picture = picture, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class StudentUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) GENDER_CHOICE = ( ('Male','Male'), ('Female','Female'), ('Other','Other') ) name = models.CharField(max_length=100, default='Open Blog Forum User') gender = models.CharField(max_length=10,null=True, blank=False, choices = GENDER_CHOICE) picture = models.ImageField(upload_to='Student Pictures', blank = True, null=True) creationTime = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = StudentUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','gender'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: … -
Invalid HOST Header from router IP
I keep getting an Invalid HOST Header error which I am trying to find the cause of. It reads as such: Report at /GponForm/diag_Form Invalid HTTP_HOST header: '192.168.0.1:443'. You may need to add '192.168.0.1' to ALLOWED_HOSTS I do not know what /GponForm/diag_Form is but from the looks of it, it may be a vulnerability attacked by malware. I also am wondering why the IP is from a router 192.168.0.1 as well as why it is coming through SLL :443 Should I consider putting a HoneyPot and blocking this IP address? Before I do, why does the IP look like a local router? The full Request URL in the report looks like this: Request URL: https://192.168.0.1:443/GponForm/diag_Form?style/ I am getting this error at least ~10x/day now so I would like to stop it. -
Submit button in a form is not working in django
In my django template when I render whole form at once, submit button works and forms get submitted or error shows up if there's any. this is actually deafult form in django. no styling or no customization has ben done: employee_add_form.html: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="" method="post" id="employee_add_form"> {% csrf_token %} {% bootstrap_form form %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} <div class=""> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> {% endblock %} but when I render like this, when I call form's fields manually one by one and apply some customized design to form like this: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="{% url 'employee:employee-add' %}" method="POST" id="employee_add_form"> {% csrf_token %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} {{ form.non_field_errors }} <div class="container"> <label for=""><b>Personal Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> {{ form.first_name.errors }} <label for="">First Name</label> {{ form.first_name}} </div> <div class="col"> {{ form.last_name.errors }} <label for="">Last … -
Combining django templates with content editable for non-technical users
We use django to generate HTML pages using templates which include javascript. Our website only consists out of a limited number of pages (creating new pages isn't a common use case) and we have people editing the content without python (and html) knowledge. Is there a way to have a simple user interface where non-technical editors can (in the best case) use a WYSIWYG editor to change the content (mainly text) of a template and a developer can build the page with html, css and javascript around it? The problem we see with full CMS system like Wagtail and Django-CMS is that they don't give us the same flexibility to build the pages and don't offer the needed functionality to make our platform configurable (When setting up the system, a user can configure their specific instance of the system as many use cases have the same structure and only need specific configurations). -
form_invalid method not displaying fields in error
I have a CBV CreateView and a django form that behaves correctly when you entered data that is valid. However, when the form has fields in error (duplicate phone number or more than one primary contact phone), then is re-displayed by form_invalid method, but the fields that were previously populated are now displayed blank. The customUser field in the Phone model which is the foreign key to the user CustomUser(AbstractUser) model appears to be blank when I print the request.post data. This is my model: class Phone(models.Model): COUNTRIES = ( (55, _('Brazil')), (1, _('United States of America')), ) PHONETYPES = ( ('1', _('Mobile')), ('2', _('Home')), ('3', _('Work')), ('4', _('Other')), ) status = models.CharField(_("Record Status"), max_length=1, default='A') status_dt = models.DateTimeField(_("Status Date"), default=timezone.now) customUser = models.ForeignKey(CustomUser, verbose_name=_("User"), on_delete=models.CASCADE) phone_name = models.CharField(_("Phone name"), max_length=20, default="PH"+str(random.randint(1,99999))) country = models.IntegerField(_("Country Dialing Code"), choices=COUNTRIES) phone_number = models.CharField(_("Phone Number"), max_length=11) phone_type = models.CharField(_("Phone Type"), max_length=1, default="4", choices=PHONETYPES) verified = models.BooleanField(verbose_name=_('verified'), default=False) primary = models.BooleanField(verbose_name=_('primary'), default=False) at_user = models.CharField(_("Audit Trail (user)"), max_length=255, blank=True) at_ip = models.GenericIPAddressField(_("Audit Trail (IP)"), protocol='both', blank=True, null=True) at_dttm = models.DateTimeField(_("Audit Trail (Date-Time)"), default=timezone.now) at_action = models.CharField(_("Audit Trail (Function performed)"), max_length=255, blank=True) UniqueConstraint(fields=['customUser', 'country', 'phone_number'], name='user_unique_phone_number') class Meta: verbose_name = _("Phone Number") verbose_name_plural = _("Phone …