Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-framework-datatables with Apache shows 414 URI too long error
Pre-requisites OS - Centos 7 Python 3.6.4 Django 3.0 (or 3.1.1) Django Rest framework 3.11.1 django-rest-framework-datatables 0.5.0 Apache 2.4 ORACLE 19.1 I have a simple Rest API - which fetches all data from a table in Oracle database. This Django Framework is hosted on Apache webserver. This data is fed into a datatable using the django-rest-framework-datatables. When I fetch data from the API using djangorest framework it works well. When I fetch data using the template with ?format=datatables as the query parameter the URL is changed and it becomes a very long URL since my table consists of 50-60 columns. Thus throws a 414 error. Did anybody else face this error ? It works well with the django's inherent webserver but when used using Django fails. -
Trying to display file name of selected image in a Django project
I have a part in the site I'm working on where a user can upload an image. I'm using a ModelForm to upload the image, but I have to modify the form itself in order to add the styling from the CSS framework I'm using (Bulma). When I display the form from the template as {{ form.as_p }}, it actually has the behavior I want: it shows an upload file button and when you've selected the file (before hitting the submit button) it shows the name of that file so the user can see that the picture has actually been selected. I've tried looking this problem up online several times with no luck, and I've tried looking at the inspector in the browser to see the html code that is generated by Django using the {{ form.as_p }} option, but that looks to be the same as doing it this way. This is the template code I have for this form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="field"> {{ pic_form.non_field_errors }} <label class="label" for="{{ pic_form.image.id_for_label }}">Upload an image</label> <div class="file has-name is-small"> {{ pic_form.image.errors }} <label class="file-label"> {{ pic_form.image }} <span class="file-cta"> <span class="file-icon"> {% fa5_icon 'upload' 'fas' %} … -
Get count of Django queryset by today's date
I have a Django project with a model that looks like this: class sellerprod(models.Model): prod = models.CharField(max_length=15) title = models.CharField(max_length=255, default=None, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateField(db_index=True, default=datetime.date.today, null=True, blank=True) company = models.ForeignKey(company, db_index=True, on_delete=models.SET_NULL, null=True) In my views I import datetime and define NOW = date.datetime.now(). I want to get the count of all the records in the table that have today's date. I have tried this (and some other similar variations): sellercount = sellerprod.objects.filter(date=NOW.date()).count() The table in my PostgreSQL database has a total of 62 records and only 28 have today's date, but this query gives me the total count of 62. I have a different view, which actually retrieves the data rather than a count, and it correctly gets 24 records (there are four less matching records with a company_id of 2) with this: products = sellerprod.objects.filter(date=NOW.date(), company__companyid=2) I presume that I am doing something wrong that causes me to get a count of all my records rather than just those with today's date. Can someone point me in the right direction? Thanks-- Al -
Forbidden (CSRF token missing or incorrect.) Django
I have included {% csrf_token %} in my HTML form(which includes textboxes and some checkboxes) in Django still I get Forbidden (CSRF token missing or incorrect.) error because of processData:false in AJAX. If I try removing processData:false from AJAX the form only keeps loading without any result. In browser console I get the following error:Uncaught TypeError: Illegal invocation . How do I fix this? -
How to use yolov5 model in django
I want to use the yolov5 model in django, but I got trouble. What I want to make is if user upload an image to django server, object detection made by with the yolov5 model, and then the result displayed on the web. The process itself is simple. But I am not sure how to attach yolov5 api and django. As those of you who have used yolo know, yolo basically runs apis based on commands. !python train.py --img 512 --batch 16 --epochs 100 --data ~~ # for training !python detect.py --weights'/content/yolov5/runs/~~ # for detection Is there any way to run this in a Django view? I tried python functions such as execfile() and os.system() that execute commands in an interpreter way within Python script, but it didn't work properly. (I think the paths between Django and Yolo were twisted.) In fact, if possible, it is best to load yolo api as a module like Keras and run it like a function, rather than the command method. But I can't find a way to use yolov5 like a module or something like that. How can I solve this problem? Please give me some advice. -
Aggregate, Sum and Round altogether
So far I have tried return self.aggregate(round(Sum("cart__total"),2), Avg("cart__total")) return self.aggregate(Sum(round("cart__total")),Avg("cart__total")) return (self.aggregate( (round(Sum("cart__total"),2)), (round(Avg("cart__total"),2)))) recent_data = '{:0.2f}'.format(recent_data) recent_data = format(recent_data, '.2f') When I do <p>Recent Total: ${{ this_week.recent_data.cart__total__sum }}</p> I get Recent Total: ${'cart__total__sum': Decimal('146238.770000000'), 'cart__total__avg': Decimal('16248.7522222222')} I want to round the decimals to two places. -
amazon s3 boto3 django secure photo urls
I'm concerned with security, the django app I have allows photos to be displayed after the user has authenticated with Twitter, or locally. I let uploaded files be stored in Amazon s3 using boto3, but can navigate to the url externally when i type it into the browser. I display like this in the template: <img class="" src="{{ MEDIA_URL }}{{item.file}}" style="width:100%; height: auto;"> and the template renders it with the amazon s3 url when the user request the page. I'm a little concerned about this as this url can be retyped by anyone, or information shared without a user credential, even if the file name is hashed and difficult to find. It is possible to create a signed url, but is possible to create signed urls for media objects in the template of a django context? As the media url is constant, and the filename is constant, how would I do this? Any help appreciated. -
Django Class-based Views - ListView if User Is Authenticated, FormView if User is Not, Same URL
When a visitor is logged out and visits my homepage, I want them to see a registration form. When the user logs in, they will be redirected back to the homepage, but it will show a listview-like view. Is the best way to achieve this to subclass both ListView and FormView and override each method necessary to get the behavior I want? Or is there a better way? Checking if the user is authenticated in each method doesn't seem like the Django way to do this. Hoping there's a smart design pattern approach for doing this that I don't know about. class HomepageView(ListView, FormView): def get_template_names(self): if self.request.user.is_authenticated: return ['homepage/loggedin_index.html'] else: return ['homepage/loggedout_index.html'] def get_context_data(self, **kwargs): if self.request.user.is_authenticated: ... else: ... def ... and so on My must-have requirement is that the URL for both logged-in and logged-out users must resolve to the root URL since it's a homepage. from django.urls import path from .views import HomepageView app_name = 'homepage' urlpatterns = [ path('', HomepageView.as_view(), name='index'), ] -
DJango Error - [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
I am using the DJango framework. I created a project in school using Pycharm and I wanted to create another project. However, when trying to run my server, all of the sudden I start to get the following error in my command prompt: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Johnny\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, … -
Pass for loop button value to modal bootstrap django
I've been looking around for this problem and while there are many threads, most use javascrip, ajax, or other stuff that I don't know... I have a list called movies that contain lists of movies and all their information. I'm using this to display all movies in a table. {% for movie in movies %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> <a type="button" data-toggle="modal" data-target="#myModal"> {{movie.0}} <!-- The movie name--> </a> </td> <td>{{movie.3}}</td>. <!-- The movie rating--> <td><a href="">Add</a></td> </tr> {% endfor %} And a trimmed version of my modal looks like: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalTitle" <div class="modal-body"> {{movies.0}} </div> </div> Obviously, no matter which movie I click i will only get the description of the first movie because of {{movies.0}}. Im wondering how can I pass the correct index to the modal so I can do maybe something like {{movies.pk}} where pk would be the index corresponding to the movie I pressed? -
DJANGO - Computing every item unitprice and quantity
what i want is to compute every item product not the total average, how do i compute every product unitprice multipy by its quantity? I just want to get the total amount of every item, but how do i do that? what should I use? aggregate or annotate? I use aggregate for getting the total amount of all product total = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id') ).aggregate( total=Sum( F('unitprice') * F('quantity'), output_field=FloatField(), ) )['total'] print('aggregate', total) and this is my logic on how to get the the total amount of per product total_amount_of_product = CustomerPurchaseOrderDetail.objects.filter( id__in=cart.values_list('id')).annotate(total_per_item=Sum(F('unitprice') * F('quantity'), output_field=FloatField(),)) item_totals = [item.total_per_item for item in total_amount_of_product] this is the result in my html this is how i print to the html <td class="cart__cell--total"><span class="cart__item-total">₱ {{item_totals}}</span></td> -
how to automatically generate schema for django graphql
I am working on this project: https://github.com/mirumee/saleor This project uses graphql and I am wondering how to generate schema in this folder: https://github.com/mirumee/saleor/tree/master/saleor/graphql Is there a way to automatically generate schema? Thanks -
Django Side Bar Text Wont Appear
so I am trying to Add Another Side Bar Text On my Website Called "Create" But It Only Shows The "Home" I created Not The Views At All IMAGE still learning how to make website but learning little by little not sure why I am having this problem sidenav1 is my Create Text And Sidenav is my Home Page Text <html> <head> <style type="text/css"> .sidenav { height:15%; width:1600; position: fixed; z-index:1; top:0; left:0; background-color:#2C3E50; overflow-x: :hidden; padding-top:20px; } .sidenav a { padding:6px 8px 16px 676px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } .sidenav1 a { padding:6px 6px 16px 696px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } .sidenav a:hover{ color:#f1f1f1; } .main{ margin-left:60px; padding: 0px 10px; } .sidenav1 a { padding:6px 8px 16px 676px; text-decoration: none; font-size:25px; color: #2ECC71; display:block; } </style> <title>{% block title %} Habibs Website {% endblock %}</title> </head> </body> <div class="sidenav"> <a herf="/home">Home</a> </div> <div class="sidenav1"> <a herf="/create">Create</a> </div> <div class="sidenav2"> <a herf="/2">View</a> </div> <div id= "content", name="content", class="main"> {% block content %} {% endblock %} </body> </html> -
whenever i try to use "conda" command i get this error, i don't exactly know what it is. can anyone help me?
C:\Users\jaspr>conda create --name myDjangoEnv django Traceback (most recent call last): File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\common\configuration.py", line 30, in from cytoolz.dicttoolz import merge ModuleNotFoundError: No module named 'cytoolz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\jaspr\AppData\Local\Programs\Python\Python38-32\Scripts\conda-script.py", line 11, in load_entry_point('conda==4.2.7', 'console_scripts', 'conda')() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 490, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2862, in load_entry_point return ep.load() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2462, in load return self.resolve() File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources_init_.py", line 2468, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\cli_init_.py", line 8, in from .main import main # NOQA File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\cli\main.py", line 46, in from ..base.context import context File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\base\context.py", line 18, in from ..common.configuration import (Configuration, MapParameter, PrimitiveParameter, File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda\common\configuration.py", line 35, in from .._vendor.toolz.functoolz import excepts File "c:\users\jaspr\appdata\local\programs\python\python38-32\lib\site-packages\conda_vendor\toolz\functoolz.py", line 467 f.name for f in reversed((self.first,) + self.funcs), ^ SyntaxError: Generator expression must be parenthesized C:\Users\jaspr> -
Turn Rasberry Pi into Apache server and use mod_wsgi
I am trying to turn my Pi into an Apache server to host a Django built site. I already have Apache installed and running with no problem. I am trying to install mod_wsgi as per Django's documentation. I have installed mod_wsgi but I cannot compile it due to it not finding the aspx component. You can point directly to it by using the command ./configure --with-apxs=path/to/apxs \ --with-python=/path/to/python when configuring mod_wsgi. See here When I configure it there is an error saying it cannot find aspx. The same when I try to compile. To discover if apxs is built you can use the apache2 -l command and sure enough it seems to be running. Even though apxs seems to be compiled I cannot find it to build mod_wsgi. From what I have been reading apache2-dev should be installed to use apxs. It doesn't seem to make any sense to me though as I can find the compiled aspx running. If I do install apache2-dev will that affect apache2? Will apache2-dev take over for apache2? apxs page https://manpages.ubuntu.com/manpages/trusty/man1/apxs.1.html#options -
How to add the PayPal Smart Payment Buttons to my form
Helloo, I am finding difficultly in proceeding with adding the PayPal smart payment buttons in my forms. In my project, there are forms to choose the required payment method through selecting Radio Button Stripe or Paypal. I don't know how to arrange it so that the logos of credit cards and PP used in this website to be shown in the check out page: https://developer.paypal.com/demo/checkout/#/pattern/radio This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) here is the checkout template: <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username I need help to integrate the PayPal payment in my checkout page -
How can I check the reverse relations?
My models: class OrderItem(models.Model): name = models.TextField(max_length=100, blank=True) pack = models.ForeignKey(Pack, on_delete=models.PROTECT, blank=True, null=True) class Pack(models.Model): name = models.TextField(max_length=100, blank=True) How can I check the reverse relations? I want to get all Pack-s that are not in OrderItem-s (in pack field). I solve it like this, but I think it`s a terrible way: orderItems = OrderItem.objects.all() packItems = Pack.objects.all() for packItem in packItems: for orderItem in orderItems: if orderItem.pack == packItem: print('Yeah, you found one of them') PS Terrible, because "Pack" have more than 5k lines -
Execute R scripts through Django hosted on AWS (Elastic Beanstalk)
I am currently building a project that uses Django Web Framework (hosted on AWSEB) but also needs to execute some R scripts. I have tried using subprocess.call(["Rscript", "R_django_test.R"]) but I get the following error "No such file or directory: 'Rscript': 'Rscript'". The code above works locally, but not on the project hosted on AWS. Any help would be greatly appreciated. -
How to send a email for user to sign up in django
I have been trying to search on google and stack overflow but can not seem to find what i'm looking for. In my django web app i would like users to signup with email invite only. I don't want just anyone to sign up. How would I go about doing this. Any help would greatly be appericated. -
Template in Flask vs Django
This is my code: {% for x in range(0,3) %} {% if x == 0 %} {% set YCode = "STAGE01" %} {% set stStage = "First Stage" %} {% elif x == 1 %} {% set YCode = "STAGE02" %} {% set stStage = "Second Stage" %} {% elif x == 2 %} {% set YCode = "STAGE03" %} {% set stStage = "Third Stage" %} {% endif %} <h3>{{ stStage }}</h3> {% for Product in dsStages %} {% if Product.3 == YCode %} <p>{{ Product.4 }}</p> {% endif %} {% endfor %} <br> {% endfor %} This works in a Flask (Jinja2) Template, but it doesn't work in a Django template ... How should it be done in Django? Thanks. -
not able to use cache in django python
i want to cache in django so I am using low level API caching but even after adding it shows none >>> from django.core.cache import cache >>> cache.set('my_key', 'hello, world!') >>> cache.get('my_key') >>> print(cache.get('my_key')) None >>> in my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } even when i use cache.add('my_key', 'hello, world!', 30) it return false -
TemplateSyntaxError at /classes/aerobics/ Invalid block tag on line 6: 'set', expected 'endblock'. Did you forget to register or load this tag?
I'm trying to render a page using a for loop to show video objects over 3 columns on the page until there are no more videos to display Why am I getting this error? What tag do I register/load for this to work? what is wrong with this line ({% set count = 0 %}) on line 6? I believe I have the {% endblock %} in the correct spot(last line). Should there be another one? views.py @login_required def classes_aerobics(request): obj = Video.objects.filter(category='Aerobics') return render(request, 'clubex/aerobics.html', {'obj': obj }) aerobics.html {% extends "ClubEx/base.html" %} {% load embed_video_tags %} {% block content %} {% set count = 0 %} {% for i in obj.all %} {% if count == 0 %} <div class="row"> {% endif %} <div class="col-md-4"> <div class="thumbnail"> <div class="caption"> {% video i.video 'tiny' %} <p>{{ i.content }}</p> <div class="rw-ui-container"></div> </div> </div> </div> {% set count = count + 1 %} {% if count == 3 %} </div> {% set count = 0; %} {% endif %} {% endfor %} {% endblock%} Traceback error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/classes/aerobics/ Django Version: 2.2.5 Python Version: 3.8.2 Installed Applications: ['ClubEx.apps.ClubexConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'embed_video'] … -
how do i redirect to user profiles upon signup with django
I am trying to redirect users to their profiles once they sign up. i can't figure out how the url should be, should be written the same way it is in the urls.py or modified? i read some articles and they talked of using a reverse lazy argument, i am not sure that would work. my current profile url uses a slug field that contains the last name and surname. views.py def addpatient(request): form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.first_name = form.cleaned_data.get('first_name') user.profile.last_name = form.cleaned_data.get('last_name') user.is_active = True user.save() user.profile.id=pk username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') messages.success(request, 'Account was created for ' + username) user = authenticate(username=username, password=password) login(request, user) return redirect('profile/<str:slug>/<int:pk>') else: form = SignUpForm() return render(request, 'core/signup.html', {'form': form}) models.py class Profile(models.Model): username = models.CharField(max_length=50, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) last_name = models.CharField(max_length=100, blank=True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) slug = models.SlugField(max_length=200,null=True) def save(self, *args, **kwargs): self.slug = slugify(f"{self.last_name}-{self.first_name}") super(Profile, self).save(*args, **kwargs) urls.py urlpatterns = [ path('profile/', profile, name='profile'), path('profile/<str:slug>/<int:pk>', profile, name='profilepk') -
Django form inheritance with Crispy Forms
I am trying to handle a form in Django in a more DRY way. I am using Django Crispy Forms to lay out and render the forms. I have a model: class Txn(models.Model): transaction_date = models.DateField() reference = models.CharField(max_length=12) arrived = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) used = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) sent= models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) adjust = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) For each of the 4 number fields (arrived, used, sent, adjust), I have a form that exposes just one of those fields. (BTW, this is based on a model that was inherited from another project - I know there are better ways to structure this, but I have to use this structure). So, I created 4 forms that look very similar: class TxnUseForm(forms.ModelForm): class Meta: model = Txn fields = ('transaction_date', 'reference', 'used') def __init__(self, *args, **kwargs): super(TxnUseForm, self).__init__(*args, **kwargs) # Layout definition for the form self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column(Field('reference', autocomplete="off", autofocus="autofocus"), css_class='form-group col-sm-4 mb-0 pb-0'), Column(Field('transaction_date'), css_class='form-group col-sm-4 mb-0 pb-0'), Column(Field('used', step='1'), css_class='form-group col-sm-4 mb-0 pb-0') ) ) # Validation for amount used - must be a positive number def clean_used(self): data = self.cleaned_data['used'] if data is None or data … -
Django - override model's default value in ModelForm
I'm trying to figure out how to override the (showing of the) default value that is provided on a model field. It seems using the 'placeholder' attribute does not work. I have an optional field that I want to present in a form, but if a user does not enter something then the default value should be stored in the database. However, I also don't want to present that default value to the user in the form. Assume: class SomeModel(models.Model): title = models.CharField(max_length=128, default="some default value here") and class NewSomeModel(forms.ModelForm): class Meta: model = SomeModel fields = ['title'] widgets = { "title": forms.TextInput(attrs={"placeholder": "My placeholder text"}) Upon rendering the form the text in the field always represents the model's default value, so "some default value here". How can I get the actual placeholder attribute to work?