Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Why is the “default value” in view not working?
my index view should query some data with the default "date of the day"value. For a test, I entered a string as a default value. : "2019-08-01" My url : urlpatterns = [ path('<str:date_index>', views.index, name='index'), ] My view: def get_reunions_by_date(date_r): return Reunion.objects.filter(datetime_start__startswith=date_r) \ .order_by('numero', 'hippodrome__nom') def index(request, date_index="2019-08-01"): year, month, day = map(int, date_index.split('-')) date_du_jour = date(year, month, day) return render(request, 'myapp/index.html', { 'reunions': get_reunions_by_date(date_du_jour), 'date_du_jour': date_du_jour }) Now, If I enter this url : myapp/2019-01-01, it's working, the index template is rendered, but if I enter this url: myapp/ nothing is rendered. Why is it not takking the default value date_index="2019-08-01" in the view ? I don't understand. -
how can I fetch data from database in django with parameter in url?
** URl : ** path('products_filter/', views.products_filter, name='products_filter'), ** VIEW :** def products_filter(request): product = request.GET.get('product') selling = request.GET.get('selling') products = Product.objects.filter(selling='best_seller') return render(request, 'product/products.html', {'products':products}) ** TEMPLATE : ** <a href="/product/products_filter?product={{'carpet'|urlencode}}&selling={{'best_seller'|urlencode}}"> -
Django ManyToManyField not showing in admin
As this questions says, i am having trouble displaying a ManyToManyField in the django admin page. The m2m field that i'm having trouble displaying is comics in the Gig model. Here is the code for my project: #models.py file class Host(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='host') name = models.CharField("Venue Name", max_length=200) slug = models.SlugField(allow_unicode=True, blank=True, null=True) description = models.TextField("Brief Venue Description - [50 Characters Max]", max_length=50, blank=True) profile_pic = models.ImageField("Profile Picture", upload_to='host/profile_pics',blank=True) class Gig(models.Model): host = models.ForeignKey(Host, on_delete=models.CASCADE, blank=True, related_name='host_gigs') title = models.CharField("Gig Title",max_length=50, null=True) date_time = models.DateTimeField("Date/Time of Gig", null=True, blank=True) description = models.TextField("Describe this gig", max_length=150, blank=True) instructions = models.CharField('Instructions for accepted comics', max_length=200, blank=True, null=True) comics = models.ManyToManyField("comic.Comic", through='comic.ComicGig',related_name='gig_comics', default=" ") #in separate app #models.py class Comic(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='comic') dob = models.DateField("Date of Birth", null=True, blank=True) mobile = PhoneNumberField(null=True, blank=True) slug = models.SlugField(allow_unicode=True, blank=True, null=True) class ComicGig(models.Model): thegig = models.ForeignKey('host.Gig', on_delete=models.CASCADE, default="", related_name='comic_gig') comic = models.ForeignKey(Comic, on_delete=models.CASCADE, default="") approved_comic = models.BooleanField(default=False, null=True) def approve(self): self.approved_comic = True self.save() Here is my Host admin.py file: class AuthorAdmin(admin.ModelAdmin): list_display = ('host', 'title',) filter_horizontal = ('comics',) def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "comics": kwargs["queryset"] = Gig.objects.filter(comic_gig__approved_comic=True) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Host) admin.site.register(Gig, AuthorAdmin) Here is a … -
Showing database files in new window with django
Okay so, i am trying to show all the entries in my FileField Database and assign a html button to each entry. when the button is pressed, a new window will open and show the pdf file that is stored in the database. models.py class UploadedFile(models.Model): the_file = models.FileField() def __str__(self): return self.the_file.name[:50] Views.py def show_file(response,pk): file_name=UploadedFile.objects.get(pk=pk) pdf = open( 'chartsapp/%s' % str(file_name), 'rb') response = FileResponse(pdf) return response class Showing_File(ListView): model = UploadedFile template_name = 'index.html' context_object_name = 'the_uploaded_files_list' URLs.py path('show_file/<pk>', views.show_file), index.html {% for file in the_uploaded_files_list %} <p> {{ file.the_file.name }} </p> <input type="button" value="Show Report" onclick="window.open('show_file/{{file.pk}}')"> {% endfor %} Settings.py MEDIA_URL = '/chartsapp/' MEDIA_ROOT=os.path.join(BASE_DIR, "chartsapp") What happens is my index.html loads, however i do not see the database entries names or corresponding buttons shown on the page. I think maybe that the Media_Url and Media_root paths might be messing me up. I have read the documentation and played around with the paths but no joy. please see picture below of the layout of the project, just incase it is the media roots that are messing it up. Correct me if i am wrong but when i upload a to FileField in django admin. the file itself … -
Partial matching search of files in Django
Im doing the cs50 web course and working in Django. I need to select md files based on the keyword that the user searches. If the query does not match the name of an the files, the user should instead be taken to a search results page that displays a list of all files that have the query as a substring. For example, if the search query were Py, then Python should appear in the search results assuming such file exists. Problem is im not sure how. Also we arent using sql. Here is util.py, code given by course that we are told we dont need to touch: import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. … -
Django: NoReverseMatch not a valid view function or pattern name
I have a django project with a structure like this: my_project |_ UserSignUp |_ urls.py |_ views.py |_ Mainpage |_ urls.py |_ views.py |_ my_project |_ urls.py |_ settings.py My problem is as follows: I can access mysite.com/index and mysite.com/login just fine. But if I try to open mysite.com/signup I encounter a 500 Internal Server Error, more precisely an Error is thrown: NoReverseMatch at /signup/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Off cause I already googled the error but did not encounter anything particular helpfull. The descriptions I found explained errors, in wich an url of an app had been tried to access, then failing because the namespace of the app was not provided in the url tag. In my case I am inside an app and want to access an url of the project root. Afaik it should be automatically resolved and even if not, I don't know how to tell django to please look into the root urls. Is django not checking the root urls really cause of the problem or is there another thing I set up wrong? How can I fix this? My root urls.py: from django.contrib … -
Django forms creates table rows by itself
I'm using django with forms. And on every one of them django add <tr> & <td> before the different inputs. Example: forms.py class LoginForm(forms.Form): username = forms.CharField(label='username', max_length=50) password = forms.CharField(label='password', widget=forms.PasswordInput, max_length=100) views.py: class Login(View): def get(self, request): form = LoginForm() return render(request, 'login.html', {'form': form}) In the html file i simply import the form via {{ form | linebreaks }} But now the given html code looks like this: <form method="post" action="/"> <input type="hidden" name="csrfmiddlewaretoken" value="*csrftoken*"> <p><tr><th><label for="id_username">username:</label></th><td><input type="text" name="username" maxlength="50" required id="id_username"></td></tr><br><tr><th><label for="id_password">password:</label></th><td><input type="password" name="password" maxlength="100" required id="id_password"></td></tr></p> <br> <button class="button" type="submit">Login</button> </form> But why does django do this? Can't it simply just use the input tags? -
Couldn't open audio blob recorded through react-mic in python
I am trying to record audio through react-mic and send the audio through django rest framework for further processing. So far everything worked fine but I am having a problem that I am unable to that file in python. I have tried wavio , wave ,playsound, winsound and speech_recognition. None of them were able to open the file or even play it but the file runs perfectly fine when I try to open with any media player. I have also tried other audio formats like mp3 and webm but none of this helps. I don't have any idea what to do now -
TypeError at /admin/customer/customerregistration/add/ __str__ returned non-string (type User)
I have created a model CustomerRegistration and add fields in it and I make relation with User models and register it in admin.py file. when I go to the Django default admin panel and register the customer it gives an error.'''TypeError at /admin/customer/customerregistration/add/ str returned non-string (type User)'''. I don't know what is getting wrong. here is my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone # Create Your Models Here. class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): if not username: raise ValueError('Users must have an username address') now = timezone.now() username = self.model.normalize_username(username) user = self.model( username=username, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username=None, password=None, **extra_fields): return self._create_user( username, password, False, False, **extra_fields) def create_superuser(self, username, password, **extra_fields): user = self._create_user(username, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254,unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_service = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) id_user_type = models.OneToOneField('Role', null=True, on_delete=models.CASCADE, related_name='usertype') last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects … -
How to write regex properly in re_path django 3
The problem with my code is that I keep getting a "page not found (404) error, the path 'post/...' does not match" when I try to click on a hyperlink on my posts page. I made 3 posts. Could it be the regex? Because I'm currently not good at regex. How can I match the views.py to the correct path in urlpatterns? My urls.py is: from django.contrib import admin from django.urls import path, re_path from blog import views as blog_views urlpatterns = [ path('post/', blog_views.post), re_path(r'^post(.*)/$', blog_views.post), path('about/'. blog_views.about), path('', blog_views.index), path('admin/', admin.site.urls) ] My views.py is: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Post def index(request): posts = Post.objects.all() return render(request,'index.html', {'posts': posts}) def post(request, slug): print(slug) return render ('post.html',{'post': get_object_or_404(Post, slug=slug)}) def about(request): return render(request, 'about.html', {}) -
Django from is not being past into html template
As in the question title "{{form}}" from is not being loaded into html template I checked by previous projects I have almost the same code, differences are required fields, naming etc. mechanic is the same. In those projects registration function works perfectly here it's not even throwing an error just don't display anything. No wonder what might be wrong in here. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Profile class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text="Required field") class Meta: model = Profile fields = ["email", "username", "password", "password2", "calories_plan", "diet_type"] views.py def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") new_account = authenticate(email=email, password=password) login(request, new_account) else: context["registration_form"] = form else: form = RegistrationForm() context["registration_form"] = form return render(request, "Account/registration.html", context) html template {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class=border-bottom mb-4>Join today {{ form }} </legend> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already have an account? <a href="#" class="ml-2"> Log In </a> </small> </div> </div> {% endblock %} And how it looks … -
In GUNICORN, is it possible to set different timeout by entrypoint?
In GUNICORN, is it possible to set different timeout by entrypoint? I have a default value of 45s for all entrypoints in Django, but one entrypoint in specific needs a timeout of +/- 10 min. Can I change gunicorn setting to solve that, instead of put all entrypoints with 10 mins? Thanks -
Djnago post "like" functionality issue
I built posts "like" functionality in posts list page (where posts of a single user are displayed). Using examples form the book "Django by examples", I did ajax like button bellow every post. But it works incorrectly. In that example like button was made for single post page, and I tried to fit it for posts list page (many post in one page). When push the like button in the database everything is fine - I got plus one like for particular post. But in the front end stange things happen - likes number for all the posts is changing, as if all the posts are connected. And when I do Like and unlike, numbers of likes for all the post are changing to some big values. I think that happens becouse in this case Ajax uses the same class selector (instead of id) for all posts. I'm still not so good at Django and Ajax and can't find a way to make this work correctly. A spent long time of triying to fix this and in googling with no result. Any help appriciated. Bellow is the code. The post's model with the likes fields: class Posts(models.Model): author = models.ForeignKey(CustomUser, … -
can't send post request from reactJs using Axios to Django restframework
I'm new to ReactJs and am trying to do post request to my Django backend server, Get request works great as expected. But post returns an error (403) Forbidden ,, here is my code : axios.post('my_url', { headers: { 'Authorization': 'my_auth_string' }, body: { 'type':'in', 'amount':'123' } }).then(res =>{ console.log(res) }) NOTE The endpoint accepts post request, as it works as expected when I send the request using flutter. -
Using PayPal Standard with Subscriptions gives error
Im have used Django-PayPal for one time payment and its work good. Now i want to convert it into Subscription that will automatically resubscribe the package on same day of next month or next year. In this image i have showed the code of one time payment In the Django-Paypal documentation they showed the way to do subscription , This image contains documentation Using PayPal Standard with Subscriptions¶ i have write the code same as the said in documentation But when i click on subscribe button as shown in this image ,paypal says "Things don't appear to be working at the moment. Please try again later." when i click on subscribe button it redirects to this link "https://www.sandbox.paypal.com/cgi-bin/webscr" , while when doing one time payment it redirects to this link "https://www.sandbox.paypal.com/webapps/hermes?token=8F359638A8728725A&useraction=commit&mfid=159438098_a982*3bb48 " Can anybody please tell me the way to solve it , or how i can do monthly and yearly subscription with Using PayPal Standard with Subscriptions Thanks in advance :) -
{% if object in cart.products.all %} always show false in Django
{{ object }}[![image has output of object:iphone, cart:10 ,cart.products.all:thw querset][1]][1] {{ cart }} {{ cart.products.all }} {% if object in cart.products.all %} IN cart {% else %} NOT cart {% endif %} {% if object in cart.products.all %} always show false else statement always prints iphone in queryset< iphone > shows false cant figure out y -
Suggestion to Make Order Model to get Order
I have Order list variable in local storge which I can send to python **The Order variable in Cart **: **Cart in localstorage ** {pdt7: Array(6), pdt5: Array(6)} pdt5: (6) ["1", "Overcoat (Gray)", 17.7, "product-3.jpg", null, 80] pdt7: (6) ["1", "Boys Shoulder Bag (Yellow )", 15.99, "man-1.jpg", null, 50] __proto__: Object **It have price quantity discount size ** all a order have THe QUESTION is that how can I create or design a Order model IN DEJANGO For Example : def Placse_order(request): if request.method == 'POST': first_neme = reuqest.POST['name'] last_neme = reuqest.POST['name'] country = reuqest.POST['name'] street1 = reuqest.POST['name'] street2 = reuqest.POST['name'] postcode = reuqest.POST['name'] City_or_town = reuqest.POST['name'] email = reuqest.POST['name'] phone = reuqest.POST['name'] return HttpResponse('Empity') -
Error while switching the database from sqllite to postgre django
I changed the values of the DATABASE variable in the file settings.py to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': "5432" } } but now after i run python manage.py migrate i'm getting the error django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist can someone tell what this error means and how to fix it -
Django admin one2one list_editable in proxy model
Нужно каким то образом через прокси модель достать поле is_big через связь one2one и вставить в list_editable в admin.py. Я использую django 3 Вот мой models.py: class Author(models.Model): first_name = models.CharField() last_name = models.CharField() class Book(models.Model): author = models.OneToOneField(Author, on_delete=models.CASCADE) is_big = models.BooleanField() class NiceAuthor(Author): class Meta: proxy = True И вставить в list_editable Вот мой admin.py: class BookInline(admin.StackedInline): model = Book class NiceAuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] list_display = ( 'is_big', ) list_editable = ( # Нужно сюда засунуть is_big ) list_filter = ( 'book__is_big', ) def big(self, obj): return obj.book.is_big big.admin_order_field = 'book__is_big' big.short_description = 'Book is big?' big.boolean = True admin.site.register(NiceAuthor, NiceAuthorAdmin) -
Why isn't the command python manage.py runserver working?
So, yesterday when I was coding everything was fine but now whenever I run the command - python manage.py runserver This error showed up - Traceback (most recent call last): File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\LENOVO\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'editdojo_project.settings' During handling of the above exception, another exception occurred: 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 "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\db\utils.py", line 225, in close_all for alias in self: File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\db\utils.py", line 219, in __iter__ return iter(self.databases) File "C:\Users\LENOVO\anaconda3\lib\site-packages\django\utils\functional.py", line 48, … -
How to redirect the user to the detailview page after form submission in Django
I have a model: class Site(models.Model): url = models.URLField(max_length=250, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.url class Meta: ordering = ('url',) I have a detail page for model. The url is the following: http://127.0.0.1:8000/sites/10/ Now I need to make a form. Where the user will add new site. And after adding the new site, I want to redirect him to this detail page url with his site id. Here is the urls.py path: from django.urls import path from django.http import HttpResponse from .views import RobotView, SiteView, add_site app_name = 'checks' urlpatterns = [ path('robots/<int:pk>/', RobotView.as_view(), name='robots'), path('sites/<int:pk>/', SiteView.as_view(), name='sites'), path('add/', add_site, name='add_site'), ] and here is the view: def add_site(request): if request.method == 'POST': form = AddSiteForm(request.POST) if form.is_valid(): form.save() return redirect('checks:sites', url.pk) else: form = AddSiteForm() return render(request, 'home.html', { 'form': form }) But this doesn't work. Can someone help me with this problem? -
Get the id of a model object which is FK of another model object django
I have a model named WarehouseProduct, which has a field warehouse_id which is FK of Warehouse model, and i need to get that warehouse_id, so that it would return the id of that FK Warehouse. I tried using: def __int__(self): return self.id which returns WareHouse object (6), and another way: def __str__(self): return str(self.id) which returns id, but the type is Warehouse so i can't convert it to int for further usage. -
My updateView creates a new post instead of updating the old post
My updateView creates a new post instead of updating the old post. i want to update my post but when i go to update form it creates a totally new post views.py def edit_task(request, post_id): post = Post.objects.get(id=post_id) form = TaskForm(instance=post) if request.method == 'POST': print(request.POST) form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('task') context = {'form': form} return render(request, 'List/add_task.html', context) -
How To Keep Django Logic To The Back-End
I have a number of connected models: class User(models.Model): individual_units = models.ManyToManyField(BaseUnit) unit_packages = models.ManyToManyField(UnitPackage) class BaseUnit(models.Model): class UnitPackage(models.Model): individual_units = models.ManyToManyField(BaseUnit) class UnitFiles(models.Model): base_unit = models.ForeignKey(BaseUnit) lesson_number = models.CharField() class UserUnitData(models.Model): user = models.ForeignKey(User) unit = models.ForeignKey(BaseUnit) package = models.ForeignKey(UnitPackage) class UserLessonData(models.Model): user_unit_data = models.ForeignKey(UserUnitData) lesson_number = models.CharField() class UserUploadedFile(models.Model): user_lesson_data = models.ForeignKey(UserLessonData) I need to print data from a single user on a page. Data from different models is spread over the page, not grouped together. For example: Loop over each UnitPackage Within each UnitPackage print each BaseUnit Within each BaseUnit print each related UnitFiles Then print each UserUploadedFile After this has been done loop through every second BaseUnit Print each BaseUnits UserLessonData etc.. Sure I can gather all those models in my view, but as data from each is printed throughout the document, I can't see how it's possible to perform the logic within my view. I have massive, nested loops within my template: {% for unit_data in user.unit_data.all %} {% if unit_data.unit_id == unit.id and unit_data.package_id == package.id %} {% for extra_data in unit_data.user_lesson_data.all %} {% if extra_data.lesson_number|add:0 == iteration|add:1 %} {% if extra_data.completed == True %} <td><input type='checkbox' disabled="disabled" name='completed' checked></td> {% else %} <td><input … -
Inconsistent behavoiur of save(commit=False) for a ModelForm in Django 2.2
I have a ModelForm that selects one field and excludes the rest, one of which is a ForeignKey that I need to populate manually before saving the form. I'm in the process of fixing a bug that one of my views has and I'm making use of the request.session object to store information so that the GET and POST method funcions will be in synced by the session in locating the model at hand instead of separately iterating though the database to pin-point what model object the submitted data should be saved for. I'm making use of the form_object.save(commit=False) funcionality in other places of the same view and it works as I need but for some reason there is a section of the view where it just doesn't populate the extra field before calling the eventual save() method and I get an IntegrityError for that column in the database, even if it is not null=False in my model declaration right now (and I think it'd rather should be..). So here's my ModelForm: class PesoFormApertura(ModelForm): peso_apertura = forms.DecimalField(min_value=0,required=True) class Meta: model = Peso fields = ('peso_apertura',) here's the Model itself: class Peso(models.Model): prodotto = models.ForeignKey(ProdottoPesato,on_delete=models.CASCADE) peso_apertura = models.DecimalField(max_digits=8,decimal_places=2, blank=False, null=True) peso_calcolato …