Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i upload files in one django filefield as a list of files?
I have created a webpage where a candidate can apply for jobs. There, they can list different previous experiences. I am handling all experience details by concatenating them in my models and splitting them while fetching. how should I handle files in such a case? My Applicant model has the FileField called company_doc. Can it also somehow take multiple files so that I can retrieve them via some indexing? is that possible? -
How to Save Multiple Objects At Once in Django
I created a checkbox in each row of the table. After selecting multiple check boxes, click the Add Teacher button to add the currently logged in user name (request.user.first_name) to the 'teacher' field of the checked row. I succeeded in getting the id to the page with the table using ajax, but it keeps failing to add the field value of obejct(teacher field) at once. view.py needs to be edited, does anyone know how to fix it? [urls.py] path('/study/add_teacher/', views.add_teacher, name='add_teacher'), path('/study/student/', views.student), ----> page with table [views.py] def add_teacher(request): if request.method == 'POST': ids = request.POST.getlist('chkArray') for id in ids: student = Student.objects.get(pk=id) student.teacher = request.user.first_name student.save() return HttpResponseRedirect(f'/study/student/') ----> page with table [stduent.js] $(function () { ('button.addteacher').on('click',function () { $checkbox = $('.Checked'); var chkArray = []; var updateTeacher = confirm("업데이트하시겠습니까?"); chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ type:'post', url: '/study/add_teacher/', headers: {"X-CSRFTOKEN": "{{ csrf_token }}"}, data:{ "chkArray" : chkArray.toString(), "csrfmiddlewaretoken": "{{ csrf_token }}", }, success:function(data){ console.log(chkArray); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }); }); }); -
Couldnt host Django web to PythonAnywhere
I uploaded my django web to pythonanywhere but everytime when I run the website it will showed Error running WSGI application, ModuleNotFoundError: No module named 'AlertTraceWebsite'. I think I set directory wrongly on the pythonanywhere but doesn't know which steps Im doing it wrong. Any help would be appreciate. thank you. I have a URL like this (project can be found here): I configure my pythonanywhere url like this: My pythonanywhere wsgi: import os import sys path = os.path.expanduser('~/kabiboy/atportal') if path not in sys.path: sys.path. insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'AlertTraceWebsite.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler (get_wsgi_application()) Errors: 2021-10-09 07:27:34,383: Error running WSGI application 2021-10-09 07:27:34,384: ModuleNotFoundError: No module named 'AlertTraceWebsite' 2021-10-09 07:27:34,384: File "/var/www/kabiboy_pythonanywhere_com_wsgi.py", line 10, in <module> 2021-10-09 07:27:34,384: application = StaticFilesHandler (get_wsgi_application()) 2021-10-09 07:27:34,384: 2021-10-09 07:27:34,385: File "/home/kabiboy/.virtualenvs/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-10-09 07:27:34,385: django.setup(set_prefix=False) 2021-10-09 07:27:34,385: 2021-10-09 07:27:34,385: File "/home/kabiboy/.virtualenvs/venv/lib/python3.9/site-packages/django/__init__.py", line 19, in setup 2021-10-09 07:27:34,385: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-10-09 07:27:34,385: 2021-10-09 07:27:34,385: File "/home/kabiboy/.virtualenvs/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ 2021-10-09 07:27:34,385: self._setup(name) 2021-10-09 07:27:34,385: 2021-10-09 07:27:34,385: File "/home/kabiboy/.virtualenvs/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup 2021-10-09 07:27:34,386: self._wrapped = Settings(settings_module) 2021-10-09 07:27:34,386: 2021-10-09 07:27:34,386: File "/home/kabiboy/.virtualenvs/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ 2021-10-09 07:27:34,386: mod = importlib.import_module(self.SETTINGS_MODULE) … -
django send_email not sending to host domain email addresses
My Django (hosted through a cPanel Python App) is not sending out emails to addresses belonging to the same domain as the site. The same send_email() function works fine in sending out messages to any other domain. I use Google Workspace for managing emails, and all MX records are set up via cPanel as normal – and emails otherwise work fine via Gmail. Any ideas? -
Django collectstatic does not use the path specified by STATIC_ROOT
In settings.py, I set the STATIC_ROOT as below: STATIC_URL = '/static/' MEDIA_URL = '/files/' STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_ROOT = BASE_DIR / 'uploads' when running the command: python3 manage.py collectstatic it works perfectly in my local development environment, it created a folder staticfiles, then collected all the files as expected, but when deploying the code on digitalOcean, it gives the error that says: ...... for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/home/kevin/myproject/static' I set the path with BASE_DIR / 'staticfiles', why it points to the BASE_DIR / 'static' the path and folder: BASE_DIR / 'static' was use by STATICFILES_DIRS = [ BASE_DIR / 'static' ] got so confused, debug it for a couple of days, it works in my local machine but not in production. any help is appreciated, thank you in advance. -
Can I integrate kivy GUI with django web framework?
I have an app built with kivy GUI library. I want to build a login system for that using django web framework. Can I integrate my kivy GUI with django web framework? -
getting 500 Internal Server Error when hosting website on cyberpanel
I am hosting django application on Cyberpanel. I have created website in cyberpanel and setup my django project. also changed vHost configuration. but in LIST WEBSITES getting this error No Screenshot Available 500 Internal server Error here is image I cant figure out how do I get rid of it -
Showing ads between posts django ? Trying to show ads after specific number of posts
I want to implement this thing, Like facebook showing ads when we are scrolling posts, after 4th or 5th post we see some ads, how can I do that please can someone tell me? If any video link is available please share Between two post like this I am shwoing all the post by for loop, if any nested for loops available please share how can I loop two different model in single loop , showing 1st item of one model after 5th item of another model loop Thank you 💗 **I am not using google ad sense, you can imagine its like I will create my own model , maybe same post model where is_ads=True be a field like that. This is my post model- class Post(models.Model): postuuid = models.UUIDField(default=uuid.uuid4,unique=True,editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150,blank=False) text = models.TextField(null=True,blank=False) image = models.ImageField(upload_to='post_images/',null=True,blank=True,default="") created_at = models.DateTimeField(auto_now_add=True, null=True) likes = models.ManyToManyField(User, blank=True, related_name="post_like") tag= models.CharField(max_length=150,blank=True) post_url=models.URLField(max_length=150,blank=True) video = models.FileField(upload_to='post_videos/',null=True,blank=True,default="") # community = models.ForeignKey(communities,on_delete=models.CASCADE) def __str__(self): return self.title -
Django: how to add fields to a form in html and save it?
I have a form with different fields and one TextInput field named 'directions'. User can add additional direction-fields with a button (just cloning existing one with javascript). But when i try to save it to the database only the last one is saved. If i print request.POST there's a list named 'directions': ['first direction', 'second' , 'and so on...'], so the data is there but it somehow gets truncated after validation. I also tried replacing the field with custom MultiValueField starting with one CharField and adding additional with javascript like this: <input type="text" name="directions_0" required="" id="id_directions_0"> <input type="text" name="directions_1" required="" id="id_directions_1"> but the result is the same models.py: class Recipe(models.Model): title = models.CharField(max_length=255) directions = models.CharField(max_length=512) class Ingredient(models.Model): name = models.CharField(max_length=127) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') forms.py: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = '__all__' class IngredientForm(forms.ModelForm): class Meta: model = Ingredient exclude = ('recipe', ) IngredientFormSet = forms.inlineformset_factory(Recipe, Ingredient, form=IngredientForm) views.py: class RecipeCreateView(CreateView): form_class = RecipeForm template_name = 'recipes/recipe_new.html' success_url = reverse_lazy('recipe_list') def get_context_data(self, **kwargs): context = super(RecipeCreateView, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = IngredientFormSet(self.request.POST) else: context['formset'] = IngredientFormSet() return context def form_valid(self, form): context = self.get_context_data() ingredient_formset = context['formset'] if ingredient_formset.is_valid(): self.object = form.save() ingredient_formset.instance = self.object … -
How do i create a tracking url in django?
Below I have wriiten a url used in iframe from amazon. <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" src="//ws-in.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=IN&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=inderpsingh-21&amp;language=en_IN&amp;marketplace=amazon&amp;region=IN&amp;placement=B08HQL67D6&amp;asins=B08HQL67D6&amp;linkId=49af08c6e03b6db926b23064dffbf266&amp;show_border=true&amp;link_opens_in_new_window=true" frameborder="0"> </iframe> As you can see the below iframe is being used by amazon to track user actions and grant them rewards on the basis of analytical approach. I am being able to create an iframe element with the actual link of the page, but I am finding it difficult to how to create a tracking link so that in further user , the iframes can be useful for user tracking and actions. Not trying to go in depth of tracking events but to understand the actions or procedures needed for tracking. Also I am not using any kind of 3rd-party options for tracking. Any kind of help would be appreciated. -
view sets throwing pagenotfound! found Django DRF
Getting page not found error, trying DRF, I am trying these viewsets but so far error as mentioned thanks in advance! urlpatterns = [ path('',include(router.urls)), path('organisation_list/',OrganisationList.as_view()), ] Routes router = DefaultRouter() router.register(r'list_organisation',OrganisationViewSet) class OrganisationViewSet(ViewSet): permission_classes = [] authentication_classes = [] queryset = Organisation.objects.all() @action(detail=False, methods=['get']) def list_organisations(self,request,*args,**kwargs): print('working') data = self.queryset serializer = OrganisationSerializer(data,many=True) return Response(serializer.data,status=200) error "GET /list_organisation/ HTTP/1.1" 404 3548 -
Django views.py add multiple files
I have a model.py in which I would like to upload multiple files. In my models I have main class and another which I'm trying to use to upload multiple file as suggested. Problem is, I get the following error in my class in views.py 'Exception Value: Unknown field(s) (file) specified for Post' and I can't get it to upload multiple files. model.py class Post(models.Model): title = models.CharField(max_length=40, verbose_name="Naslov predmeta") # a lot more field here but not important file_1 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 1", validators=[validate_file_size]) file_2 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 2", validators=[validate_file_size]) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) class File(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) file = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteke", validators=[validate_file_size]) views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content_don', 'subject', 'rn_number', 'file_1', 'file_2'] def form_valid(self, form): form.instance.author = self.request.user #here I have a lot of code to process data which is writen in the fields response = super(PostCreateView,self).form_valid(form) ################################################################# ##### this code below I'm trying to use to upload multiple files obj = form.save(commit=False) if self.request.FILES: for f in self.request.FILES.getlist('file'): obj = self.model.objects.create(file=f) return response I also tried using forms, but I can't get my scripts/querys and simmilar to work then. Is there a … -
how can i get my project to show under my repo using git when deploying?(django)
:~/portfolio$ ls README.md venvxz My Django project isn't showing up under my repo in the terminal when i want to deploy with AWS! Ive tried "git push origin master", git remote add origin. i think last time i had it working, i pushed my project under a certain branch on GitHub. I have tried git merge, git checkout, my project on GitHub is currently under git master. If i try git branch, it shows 'main' I cannot deploy my website because of this. `:~/portfolio$ git branch main` -
Complex queryset with django content type model
I have a set of models that contain content that is created and contributed by users. Model User: class User(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=150, blank=True) is_active = models.BooleanField(default=True) Model Tip: class Tip(models.Model): title = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) Model Example: class Example(models.Model): headline = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) Model Struggle: class Struggle(models.Model): headline = models.CharField(max_length=30, blank=True) content = models.CharField(max_length=150, blank=True) and model UserContribution class UserContribution(models.Model): id = models.AutoField(primary_key=True) contributed_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="User that contributed the object", on_delete=models.CASCADE ) contributed_at = models.DateTimeField(auto_now_add=True) object_id = models.PositiveIntegerField( help_text="Primary key of the model", ) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) I want to be able to select a set of users and list the contribution objects they have contributed (created or updated). For example, [ { "user_id": 1, "first_name": "A", "last_name": "B", "tips": [ { "id": 1, "title": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "title": "eabc", "content": "abcd", "contibuted_at": "2021-08-09" } ], "examples": [ { "id": 1, "headline": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "headline": "eabc", "content": "abcd", "contibuted_at": "2021-08-09" } ], "struggles": [ { "id": 1, "headline": "abc", "content": "bcd", "contibuted_at": "2021-08-10" }, { "id": 2, "headline": "eabc", "content": … -
python - Cancel an already executing task with Celery
I need to cancel a task created by celery. I came across this article - Cancel an already executing task with Celery? Since I am calling the task inside my django view, I am also trying to cancel it inside my django view, which looks something like: import myproj.tasks as tasks task = tasks.mytask.delay(...) #I don't have the luxery to do task.revoke() taskid = task.task_id tasks.app.control.revoke(taskid, terminate=True, signal="SIGKILL") I check my worker... and it doesn't give me any indication to think that the worker has stopped working on the task, and it still the same amount of time to actually complete the task as it does to kill it (250 seconds)........ and then the "killed task" disrespectfully returns 250 seconds after its completed. Something else maybe worth mentioning is that the task file imports a class that I've made... so in the task file I have my task defined with the task decorator above the definition, then literally it returns: return myclass.myclass(**kwargs) A potential work around I've considered is copying and pasting my class file into my tasks so that I can set a flag inside blocks of the code to check to see if it needs to be aborted … -
How to debug an Django application running in AWS EC2
I deployed a django app on AWS Elastic Beanstalk and did run it. Some endpoints works well but something said <h1>Server Error (500)</h1> The endpoints with taking errors works well in my local env but took above error when I run it on AWS. So I gonna debug why it takes error... Please help me! Noticed: I have the ssh access. And I checked the /var/log/ directory but I did not find the logging error of application. -
how to authenticate a user using django rest framework
I am trying to authenticate a user using django rest framework and authenticate import below but for some reason i keep getting null as a result when i check the front end with reactJS, i am referring to the variable logged_in_used below: from django.contrib.auth import authenticate ... if request.method == "POST": username = request.data.get('username') password = request.data.get('password') get_user = User.objects.get(username=username) logged_in_used = authenticate(username=get_user.username, password=get_user.check_password(password)) ... # data with token dictionnary ... result = (data_with_token, logged_in_used, status.HTTP_200_OK) Is there something that i am doing wrong here? -
NGROK With Python and Raspberry Pi
I am sorry to return with more ngrok/django issues, but this seems super inconsistent. I am trying to send a string from my django site hosted on heroku to a forwarded socket on my raspberry pi. Testing with both the website and netcat SERVER:PORT(redacted obviously) I am getting TTL(total connections through) but nothing is happening on my python file. I am not sure why this is happening but if anybody sees anything obvious in my code or img then the help would be great! https://imgur.com/a/OZzsDyT Pi script PORT = REDACTED SERVER = '0.0.0.0' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" my_queue = queue.Queue() print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == '!DISCONNECT!': connected = False print("disconnect") break else: my_queue.put(msg) print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) conn.close() def start(): server.listen() print(f"[LISTENING] Server Is Listening On {SERVER}") while True: conn, addr = server.accept() thread = threading.Thread(target=handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[Starting] Server") threading.Thread(target=start).start() msg = my_queue.get() print(msg) Django View: HEADER = 64 PORT = REDACTED SERVER = 'REDACTED' ADDR = (SERVER, PORT) FORMAT … -
how can i display all products by user and edit them ? on django
how can i display all products and edit them ? im working on e-commerce project and i want every user add his own products by himself Blockquote Blockquote Blockquote views.py def ProductsFunction(request): Prodcuts = Product.objects.filter(user=request.user) form = ProductEditForm(instance=Product) if request.method == 'POST': form = ProductEditForm(request.POST,request.FILES,instance=Product) if form.is_valid(): form.save() return redirect('accounts/products') context = { 'product':form } return render(request, 'usrstore/products.html',context) models.py class Product(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) ProductName = models.CharField(max_length=100,default=None) ProductDescription = models.TextField(max_length=5000,default=None,null=True,blank=True) ProductPrice = models.DecimalField(max_digits=5,decimal_places=2) ProductCost = models.DecimalField(max_digits=5,decimal_places=2) ProductCreated = models.DateTimeField() Active = models.BooleanField(default=True) CategoryProduct = models.ForeignKey(Category,on_delete=models.CASCADE,default=None) def __str__(self): return self.ProductName @receiver(post_save, sender=User) def createProduct(sender,instance,created,**kwargs): if created: Product.objects.create( user=instance ) Html Code <form action="POST"> {% csrf_token %} {% for p in product %} <div class="product"> <div class="product-img mx-auto"> <img src="{{p.PoductImage.url}}" alt=""> </div> <div class="productName"> {{p.ProductName}} {{p.ProductDescription}} {{p.ProductPrice}} <button type="submit">edit</button> </div> </div> </form> {% endfor %} The Problem -
heroku [remote rejected] main -> main (pre-received hook declined)
I tried to push my code from github and heroku said it couldn't get decide on the build and gave me this error. I set the build to python (since my app is made in Django) but it still gives me the same error when I try to run it again. Now it says remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1f09558f6b29e630eb55bc936402a9265518d67b remote: ! remote: ! We have detected that you have triggered a build from source code with version 1f09558f6b29e630eb55bc936402a9265518d67b remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version The link provided says the article is a work in progress and it doesn't talk about my error at all. I don't understand what they mean about a different branch since the first time I tried I used the same app, same folders, same … -
Django AttributeError: Importing form class
I'm building a tool which has it's logic written in a separate file tools.py. I created a form which is suppose to pass user input to the variable in my tools.py file. I tried importing the forms class into my tools.py and assigned them to my variables but it has been showing this error AttributeError: type object 'ToolsForm' has no attribute 'sender_input' meanwhile these are my forms.py and tools.py file: Forms.py: from django import forms class ToolsForm(forms.Form): sender_input = forms.EmailField(required=True, widget=forms.TextInput(attrs= {'placeholder': 'Enter your mail account here:'})) Tools.py: from tools.forms import ToolsForm formDetails = ToolsForm sender_input = formDetails.sender_input -
Creating a button that can be used to forward a blog post between users in Django
I am creating a blog post in Django but find it difficult to create a forward button where posts and comments on them can be forwarded from one user to another user. -
Selecting all script tags in HTML using Scrapy in Django
I want to get all script tags from a url but there is an issue I'm facing. Let's say url is: https://somewebsite.com/ How my parse function looks like in my spider class (which is very basic one): def parse(self, response, **kwargs): """ Parses the response. """ script_elements = response.css("script") # There are lots of script tags but most of them are missing. # Let's say, in website, there are 25 script tags. # The code above will return 3 or 4 of them. parsed_result = list() for script_element in script_elements: script = script_element.extract() # other code blocks return parsed_result But when I run scrapy with shell like this: scrapy shell https://somewebsite.com/ And when I select the script tags in shell: response.css("script").extract() I got exactly what I want. Every script tags in HTML is there. Why is there such a difference? I'm running Scrapy with Django web application (I don't know If this makes any difference.) -
DJango ORM double join with Sum
I searched for a similar case on SO and Google with no luck. SHORT EXPLANATION I have transactions that belong to an account, and an account belongs to an account aggrupation. I want to get a list of accounts aggrupations, with their accounts, and I want to know the total balance of each account (an account balance is calculated by adding all its transactions amount). LONG EXPLANATION I have the following models (I include mixins for the sake of completeness): class UniqueNameMixin(models.Model): class Meta: abstract = True name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) def __str__(self): return self.name class PercentageMixin(UniqueNameMixin): class Meta: abstract = True _validators = [MinValueValidator(0), MaxValueValidator(100)] current_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) ideal_percentage = models.DecimalField(max_digits=5, decimal_places=2, validators=_validators, null=True, blank=True) class AccountsAggrupation(PercentageMixin): pass class Account(PercentageMixin): aggrupation = models.ForeignKey(AccountsAggrupation, models.PROTECT) class Transaction(models.Model): date = models.DateField() concept = models.ForeignKey(Concept, models.PROTECT, blank=True, null=True) amount = models.DecimalField(max_digits=10, decimal_places=2) account = models.ForeignKey(Account, models.PROTECT) detail = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{} - {} - {} - {}'.format(self.date, self.concept, self.amount, self.account) I want to be able to do this in Django ORM: select ca.*, ca2.*, sum(ct.amount) from core_accountsaggrupation ca join core_account ca2 on ca2.aggrupation_id = ca.id join core_transaction ct on ct.account_id = ca2.id group … -
Django Model Custom Field Problems
I've been trying to get this done for days but still can't see where the error is. At the moment I'm using the generic CreateView in views.py for form processing. The particular text field in question is supposed to take a string in the format of "HH:mm" or ":mm" (or 0), convert it to minutes and store in the DB as an integer. For some reason the form.errors still says this must be an integer. Obviously initially it is a string, but should be an integer by the time it gets to saving. Custom Model Field in models.py class FlightTimeFieldInt(models.IntegerField): description = "a field to input flying time" def get_db_prep_value(self, value, *args, **kwargs): if value is None: return None return value def to_python(self, value): if value is None or isinstance(value, int): return value if str(value.split(":")[0]) == '': split = value.split(":")[1] value = int(split) print(value) return int(value) else: h, m = value.split(":") value = (int(h) * 60) + int(m) return value def from_db_value(self, value, expression, connection, context): return self.to_python(value) def formfield(self, **kwargs): defaults = {'form_class': None} defaults.update(kwargs) return super(FlightTimeFieldInt, self).formfield(**defaults) There could be a better way but not sure how to go about it. Thanks for your help!