Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a user instance in a class-based view
I would like to pass the user instance of the current user in a class-based view and feed it in a second step to a model containing the column author. Related to that column I get the following integrity error: NOT NULL constraint failed... From the traceback I can see that my variable loggedUser which I had attributed self.request.user is a SimpleLazyObject. How can I pass my user instance? Thank you! View: class PlotGraphView(LoginRequiredMixin, TemplateView): redirect_field_name = '' login_url = '' template_name = "plot.html" def get_context_data(self, **kwargs): loggedUser = self.request.user context = super(PlotGraphView, self).get_context_data(**kwargs) context['logger'] = Logger.objects.get(name=logger_name) context['plot'] = plots.plotgraph(logger_name, loggedUser) Model: class Data(models.Model): logger = models.ForeignKey('Logger', on_delete=models.CASCADE) date = models.CharField(max_length=20) relative_humidity = models.FloatField(max_length=5) temperature = models.FloatField(max_length=5) author = models.ForeignKey(User, on_delete=models.PROTECT) -
Express multiple one-to-many and one-to-one relationship in Django
I am designing a delivery app. It has User, Address and Store models. I have following requirements: User can have multiple delivery address Store is located at only one location. An address cannot be linked with both user and store. Models looks as follow: class User(AbstractBaseUser): ... class Address(models.Model): ... class Store(models.Model): ... First requirement can be shown as: user = models.ForeignKey(User, on_delete=models.CASCADE) Second requirement can be shown as(in Address model as): store = models.OneToOneField(Store, on_delete=models.CASCADE) Also, second requirement can be shown as(in Store model as): address = models.OneToOneField(Address, on_delete=models.CASCADE) What is the best way to represent the third requirement. And how do I take care of serialization in this case? Thanks. -
view is correct, but django templates aren't rendering
I'm trying to figure my URLs out. My views seems to function in the console, but nothing renders in the templates after the search is completed. My search seems to function regardless of what i have in the user_list function as long as the user is defined with the following: user_list = Employee.objects.all() args = {'users':users} return render(request, 'user_list.html', args) My user_list falls under search and functions correctly with the filter. return render(request, 'user_list.html', args) It's after the filter that I try to render a view called results with: return render(request, 'results.html', args) The navigation is correct and it takes me to the URL and I can view the POST from the previous view in the console and it is correct. However, the template is empty when there is code in results.html In settings INSTALLED_APPS I have my app defined as: 'mysite.search', My application structure is laid out as the following: My project urls.py is setup as: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), ] My application urls.py is setup as: from django.conf.urls import … -
Recommendation for REST API using Python
I will be working on a project that consists of developing some REST API for a web app with MongoDB database using Python (Django framework to be particular ) I have the basic knowledge with Python , so in order to accelerate the learning phase and get things going much faster I need some advice on what should I learn first and if possible some suggestions Please help me :) thank you -
Django CMS on Raspberry Pi 3 Fails
Today I tried to install django CMS for a while on my Raspberry pi but it will not work. I Installed a fresh "RASPBIAN STRETCH LITE" then i entered following commands via an ssh connection: sudo wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py sudo pip install Django==1.10 sudo pip install virtualenv cd /srv sudo mkdir django_cms cd django_cms sudo virtualenv env source env/bin/activate sudo pip install --upgrade pip sudo pip install djangocms-installer sudo mkdir django_site cd django_site/ sudo djangocms -f -p . web_site All this follows this guide And this error get thrown after executing the last command above: Creating the project Please wait while I install dependencies ERROR: cmd : [u'pip', u'install', u'-q', u'django-cms>=3.5,<3.6', u'djangocms-admin-style>=1.2,<1.3', u'django-treebeard>=4.0,<5.0', u'https://github.com/divio/djangocms-text-ckeditor/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-file/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-link/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-style/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-googlemap/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-snippet/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-picture/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-video/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-column/archive/master.zip?1520455195.14', u'easy_thumbnails', u'django-filer>=1.3', u'Django<2.0', u'pytz', u'django-classy-tags>=0.7', u'html5lib>=0.999999,<0.99999999', u'Pillow>=3.0', u'django-sekizai>=0.9', u'six'] :Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-FFzxtb/Pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-CPB18v-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-FFzxtb/Pillow/ The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/usr/local/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/main.py", line 33, in execute verbose=config_data.verbose File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/install/__init__.py", line 95, in requirements output = subprocess.check_output(['pip'] + args, stderr=subprocess.STDOUT) File "/usr/lib/python2.7/subprocess.py", … -
Bad magic number when deploying on Heroku
I am trying to deploy a Django app to Heroku which uses a client to connect to the api of an invoice service. Everything works when running localy, but when deploying on Heroku I get a Bad magic number errror: error at /bexiopy/auth/ Bad magic number Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Exception Type: error Exception Value: Bad magic number Exception Location: /app/.heroku/python/lib/python3.6/dbm/__init__.py in open, line 94 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '/app'] Server time: mer, 7 Mar 2018 19:53:24 +0000 Environment: Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['jet.dashboard', 'jet', 'nested_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django_celery_beat', 'django_celery_results', 'bexiopy.apps.BexiopyConfig', 'database'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/views.py" in get 29. client = Client() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in __init__ 360. self.load_access_token_from_file() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in load_access_token_from_file 611. access_token … -
Django CMS -- Unregister Custom Menu?
Any idea how to unregister customized menus? The docs only show how to add them and I don't see any unregister attribute on menu_pool. I blindly tried menu_pool.clear(), but that didn't work. The prior menus remain discoverable with menu_pool.get_registered_menus() and in logging. -
Django model's clean() method not raising the expected ValidationErrors for individual fields
I have a Django model called CheckIn with (among others) two fields, min_weeks and max_weeks. I would like to build in validation such that min_weeks is always less than or equal to max_weeks. Following https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#django.db.models.Model.clean (in particular, the last example in which the ValidationError is passed a dictionary which maps fields to errors), I tried the following clean() method: from django.db import models from django.core.exceptions import ValidationError class CheckIn(models.Model): min_weeks = models.IntegerField(blank=True, null=True) max_weeks = models.IntegerField(blank=True, null=True) def clean(self): if self.min_weeks > self.max_weeks: raise ValidationError({ 'min_weeks': ValidationError("'min_weeks' should be smaller than 'max_weeks'", code='invalid'), 'max_weeks': ValidationError("'max_weeks' should be greater than 'min_weeks'", code='invalid')}) The model is used in a ModelForm: class CheckInForm(forms.ModelForm): class Meta: model = CheckIn fields = [ 'min_weeks', 'max_weeks', ] The fields are displayed manually in the template. Here is an excerpt: <div class="row"> <div class="input-field col s4"> <div class="js-hide-edit-field-text {% if not check_in_type or form.min_weeks.value %}hide{% endif %}"> {% if check_in_type and not form.min_weeks.value %} <span class='js-max-weeks inherited-field text'>{{ check_in_type.min_weeks }}</span> <a href='#' class='js-hide-edit-field-edit edit-icon right'><i class="material-icons">mode_edit</i></a> <label class="active"> Min Weeks </label> {% endif %} </div> <div class="js-hide-edit-field {% if check_in_type and not form.min_weeks.value %}hide{% endif %}"> {{ form.min_weeks|add_error_class:"invalid"|attr:"data-duration-weeks-mask" }} {{ form.min_weeks.errors }} {{ form.min_weeks|label_with_classes }} </div> </div> … -
How to set subdomains whit ip using nginx
Can subdomains be used with ip on Nginx for testing, like teste.x.x.x.x I did this but does not work. server_name teste.x.x.x.x teste2.x.x.x.x ; Thanks -
Custom validation in a CUSTOM Django admin
I've a custom django admin that extends a default change_form (I do it because a need some logic for uploading images), but I need a way to show the page again if no image was uploaded, and show the errors. Some code to illustrate: class MyModel(models.Model): ... main_photo = models.ForeignKey(Photo) photos = models.ManyToManyField(Photo, related_name='collage') I extend the change_form.html admin template for this model: myapp/templates/admin/mymodel/change_form.html {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> <h2>Upload photos</h2> <h3>Main photo</h3> <input name="main_photo" type="file" /> <h3>Others</h3> <input name="photos" type="file" multiple /> </fieldset> {% endblock inline_field_sets %} Now I overwrite the save_model method from ModelAdmin in the admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): ... exclude = ['main_photo', 'photos'] def save_model(self, request, obj, form, change): photos = request.FILES.getlist('photos') main_photo = request.FILES.get('main_photo', None) if not main_photo: pass # --> I NEED THE WAY TO NOTIFY THE USER THIS IMAGE MUST BE UPLOADED # raise ValidationError("msg") --> It's not an option because this doesnt show the form re-rendered with the error. # some internal bussiness logic here: folder_to_save = '{0}/{1}'.format(self.folder_to_save_img, obj.id) obj.main_photo = Photo.objects.create(folder=folder_to_save, original=main_photo) obj.save() if photos: for photo in photos: obj.photos.add(Photo.objects.create(folder=folder_to_save, original=photo)) -
Django with Docker - Server not starting
I have followed the steps in the official docker tutorial for getting up and running with django: https://docs.docker.com/compose/django/ It works fine until I have to run docker-compose up It doesn't directly give me an error, but it won't run the server either, stopping at this point: (Screenshot of the Docker Quickstart Terminal) I am on Windows and have therefore used docker-toolbox. Thanks for your suggestions! -
Running Wagtail site with Docker
I'm trying to convert an existing Wagtail site to run with Docker. I have created the image and then run the container, but I'm unable to connect in the browser window. Getting 0.0.0.0 didn’t send any data. ERR_EMPTY_RESPONSE. Dockerfile: FROM python:3.6 RUN mkdir /app WORKDIR /app COPY ./ /app RUN pip install --no-cache-dir -r /app/requirements/base.txt RUN mkdir -p -m 700 /app/static RUN mkdir -p -m 700 /app/media ENV DJANGO_SETTINGS_MODULE=mysite.settings.dev DJANGO_DEBUG=on ENV SECRET_KEY=notsosecretkey ENV DATABASE_URL=postgres://none ENV SENDGRID_KEY=sendgridkey EXPOSE 8080 RUN chmod +x /app/entrypoint.sh \ && chmod +x /app/start-app.sh RUN python manage.py collectstatic --noinput ENTRYPOINT ["/app/entrypoint.sh"] CMD ["/app/start-app.sh"] docker-compose.yml: version: '2' services: db: environment: POSTGRES_DB: app_db POSTGRES_USER: app_user POSTGRES_PASSWORD: changeme restart: always image: postgres:9.6 expose: - "5432" ports: - "5432:5432" app: container_name: mysite_dev build: context: . dockerfile: Dockerfile depends_on: - db links: - db:db volumes: - .:/app ports: - "8080:8080" environment: DATABASE_URL: postgres://app_user:changeme@db/app_db command: python manage.py runserver 0.0.0.0:8080 entrypoint.sh: #!/bin/sh set -e exec "$@" start-app.sh: #!/bin/sh python manage.py runserver 0.0.0.0:8080 I run docker run -p 8080:8080 app:latest and it works when I run docker ps showing that it's at 0.0.0.0:8080->8080/tcp, but when I go to 0.0.0.0:8080 in the browser window, I get the error. What am I missing? -
Is there any open-source free codes of a Django Python database app with a CRUD and search functionality? [on hold]
Is there any open-source free codes and tutorials of a Django Python database app with a CRUD and search functionality? Need to develop a bioinformatics-oriented application with an extended search and data view functionality. And I am thinking what technology would be more appropriate: Django Python or YII PHP. Thx. -
Trouble using an Oracle View in Models.py
My group and I are attempting to rewrite our website. We are keeping an Oracle database back-end, and rewriting the front-end with Python Django. No problem connecting to Oracle, or accessing the datatables. Now I'm trying to add an Oracle view to the models.py, and I can't get it to work. I googled this question with many results, so I know it is possible and apparently common, but I can't get it to work. All I've done so far is add the class to models.py. We are using PhCharm as our IDE. When I try to access the data using the Python Console, I can import the class, but when I try to load the QuerySet I get the error "Unable to get repr for " in the result window. Does anyone see something I'm missing from my model? Here is the model: class LawBillRoleActionInfoView(LawBaseClass): combo_id = models.AutoField(primary_key=True) rltp_role_cd = models.CharField(max_length=2, blank=True) bill_dft_no = models.CharField(max_length=6, blank=True) session_id = models.IntegerField(blank=True, null=True) ebrl_appl_seq = models.IntegerField(blank=True, null=True) enty_id_seq = models.IntegerField(blank=True, null=True) lst_nm = models.CharField(max_length=100, blank=True) fst_nm = models.CharField(max_length=40, blank=True) mi = models.CharField(max_length=1, blank=True) entity = models.CharField(max_length=145, blank=True, null=True) prtydist = models.CharField(max_length=11, blank=True, null=True) blac_appl_seq = models.IntegerField(blank=None, null=True) role_descr = models.CharField(max_length=80, blank=True) shr_ttl = … -
Why can't I display my background image in django template?
I have an app by the name 'main' having static folder and template folder. My static folder goes like static/main/background/city.png I am trying to set background image of my html file but it does not load. Can you tell me what is it that I'am doing wrong? <style> body{ background-image:url("{static 'main/background/city.png'}"); } </style> -
Django: Modify model field value when form is submitted
I have a model field for each use that keeps track of their score on my website. Every time a user does some I want to add or subtract from their score. In this particular case, I would like to change the users score when they publish a post on my site. I am able to access the user's score, but not modify it. Here is what I have so far: def createPost(request): user = UserProfile.objects.get(user=request.user) current_score = user.user_score if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): ... user.user_score = current_score - 1 ... else: form = PostForm() return render(request,'feed/userpost_form.html',{'form':form}) I am not getting any errors and publishing the post works fine, just not modifying the user's score. Also, I am using Django 1.11 -
Between Django and WAMP which would be better for using their sql for my Android studio project?
I want to use the database and communicate between both using REST API. -
Rest framework: different serializer for input and output data on post/put operations
Lets say I have these models: class Download(MPTTTimeStampedModel): endpoint = models.ForeignKey(EndPoint, related_name="downloads",) class EndPoint(TimeStampedModel): name = models.CharField(max_length=100, verbose_name=_(u"Nombre")) url = models.CharField(max_length=2000, verbose_name=_(u"Url")) These serializers: class DownloadSerializer(serializers.ModelSerializer): class Meta: model = Download fields = ('id', 'endpoint') def create(self, validated_data): ... def update(self, validated_data): ... class EndPointSerializer(serializers.ModelSerializer): class Meta: model = EndPoint fields = ('id', 'name', 'url') def create(self, validated_data): ... def update(self, validated_data): ... And this generic api view: class DownloadList(generics.ListCreateAPIView): queryset = Download.objects.all() serializer_class = DownloadSerializer This will allow me to create a download by sending a json representation looking like this: { 'id': null, 'endpoint': 19 } And upon creation, the web service will send me back the data with the id from the database. Now, I actually want the web service to send me back not just the endpoint id but a complete representation of the object, Something like this: { 'id': null, 'endpoint': { 'id': 19, 'name': 'my endpoint', 'url': 'http://www.my-endpoint.com/' } } I would manage this with this serializer: class DownloadDetailedSerializer(DownloadSerializer): endpoint = EndPointSerializer(many = False, read_only=False) And now the actual question: how do i tell my generic view to use this last serializer for the returned data while keeping the original DownloadSerializer for the input? -
Django and Postgress Heroku deployment error
I have the following error in Heroku: at=error code=H10 desc="App crashed" method=GET path="/" host=psc-test.herokuapp.com request_id=c16bb8e0-a1e6-4905-ae79-56d105d71ef7 fwd="92.86.38.87" dyno= connect= service= status=503 bytes= protocol=https and I have no idea why -
How to pass an InMemoryUploadedFile as parameter to a celery task with json set as serializer?
I've just changed my celery settings to use json as serializer, I have to change some of my tasks with objects like querysets as parameters. I have one particular task with an InMemoryUploadedFile as parameter that can no longer be used with json as serializer. Do you have any advice since the file has no path please? The only thing I can think of would be to temporarily save the file, then pass the path as parameter, then reopen the file, and finally delete it. Thanks guys! -
Django debug toolbar 404
I am trying to get django-debug-toolbar working. I have followed the installation steps and I get the sidebar including stats (e.g. SQL 1 query in 2.75ms, Static Files 19 Files used, 30 receivers of 12 signals) which seem to be legitimate and indicate that its working. However, when I click for more info on a given tab, I get a 404 in browser, and this sort of thing in the console: "GET /__debug__/render_panel/?store_id=ac74875cfe864b2dab4c6d17c1d1ed5d&panel_id=RequestPanel HTTP/1.1" 404 1791" Other pages on site do work. I have tried various configurations in urls.py. Here is what I currently have: from __future__ import absolute_import, unicode_literals from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: url(r'', include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your site, rather than the … -
Django: Extent with snippets or better solution
I have the following template: {% extends "account/base.html" %} {% load i18n %} {% load account %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Password Reset" %}{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1>Reset your password</h1> {% if user.is_authenticated %} {% include "account/snippets/already_logged_in.html" %} {% endif %} <p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}</p> <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Reset My Password</button> </form> <p><em>{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</em></p> </div> </div> </div> {% endblock %} account/base.html contains this here: {% extends "base.html" %} base.html then contains tags etc. I am currently struggling with finding the best solution while considering DRY. In my template I have written: <div class="container"> <div class="row justify-content-center"> <div class="col-8"> [more text] </div> </div> </div> I have several of these templates and in each of them I am currently writing the same ... I am now wondering is the right solution to include these opening / closing div-tags in two files and then … -
Pre-populate HTML form table from database using Django
I have a class-based view (IndexView at views.py) that shows a table with all the data stored in the database. This view is rendered in index.html using a def get_queryset(self) to obtain all the data. No issues yet. The difficult part for me is trying to do it using a form, to be able to modify and save the amount column. I have no issues with the POST part, where I use AJAX to save the new values. Where I'm having issues is getting the initial values from the database to populate a Django Form (forms.py) I tried using initial argument in the definition of the form fields (at forms.py), even overriding __init__ at the form definition, but I don't know how to get "one value". I mean, the closer I've been in my tests was populating a MultipleChoiceField with: forms.ModelMultipleChoiceField(queryset=Item.objects.order_by('code__name')) (achieving a multiple choice field of Item object (1), Item object (2), etc.) But how do you populate a single IntegerField or CharField with the content of the database to show a form-based table field in the template? I'm trying first with a single item (to try to understand how to reference one item/value to populate them using the … -
Unable to import view .. Python Django
i donot why app registery error is showing when i try run the url.py in music folder i see this error also view not getting imported when i try running the website urls, i get this above errors, i tried searching for solution in this website.. couldn't get the proper ans please help to resolve this soon team. -
Python // coming from SQL server table with /
I have a field in my SQL server table that is a varchar that is coming into my model defined as field= models.CharField(db_column = 'tablename', max_length = 30) When I look at the POST coming through my field is displayed as AAA//AAA#### when it's stored in the database as AAA/AAA####. Later in my view I try to call the field, but it's attempting to divide giving the following error: ValueError: invalid literal for int() with base 10: 'AAA\\AAA####' How can I get this field to display as AAA/AAA#### in my post? owner = request.POST.get('usercheck')