Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetch country based on the IP Address using python django
Is there any snippet or an example that can help me fetching country from the IP address? First I need to fetch the user's IP and then based on that I need to fetch the country. Below is the snippet that I am trying and have started with. from geoip import geolite2 match = geolite2.lookup('17.0.0.1') I am trying with installing geoip package but it throws me below error. a bytes-like object is required, not 'str' Just FYI that I am using python 3.6.3 -
Django reverse lazy add html anchor?
Im trying to add a html anchor to a django reverse lazy. as such return reverse_lazy("app_settings:index", kwargs={'#branch_device'}) however I am receiving the error: _reverse_with_prefix() argument after ** must be a mapping, not set is adding a anchor this way possible? Thanks -
Wrong path for ImageField in Django
I have a model with a ImageField and a function to change the upload path class Images(models.Model): def upload_path(self, filename): return os.path.join(settings.TOOLS_IMAGE_UPLOADS, self.get_artworkID(), filename) image = models.ImageField(upload_to=upload_path) artworkID = models.IntegerField(null=True, blank=True) def __str__(self): if self.title == "" or not self.title: return str(self.image) return self.title def get_artworkID(self): if self.artworkID: return str(self.artworkID) return 'temp' The value of TOOLS_IMAGE_UPLOADS is PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(PROJECT_DIR) MEDIA_NAME_FOLDER = 'media' MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_NAME_FOLDER) TOOLS_IMAGE_UPLOADS = os.path.join(MEDIA_ROOT, 'uploads', 'images') The problem is that the URL returned when visualizing an Image object via Django admin or rest api is wrong Path returned: http://localhost:8000/media/webapp/artrights/media/uploads/images/temp/file.png Real path of the file: http://localhost:8000/media/uploads/images/temp/file.png I'm doing something wrong or I just need to make a custom function to return the right path? -
Django Custom Decorator - Attribute Error
Wrote my own decorator, that get the available reports for a user, and check if the view is within those available reports. Here's my decorator: from functools import wraps from django.http import HttpResponseForbidden def can_access(a=None): def _can_access(view_func): def access(request, *args, **kwargs): if not request.user.get_reports().filter(codename=a).exists(): return HttpResponseForbidden() return view_func(request, *args, *kwargs) return wraps(view_func)(access) return _can_access Gives me this error: 'function' object has no attribute 'status_code' views.py import json from datetime import datetime, timedelta, date from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest from reporting.enums import ReportFrequency from base.helpers import get_begin_of_day, get_end_of_day from billing.helpers import get_fake_usage_by_type, update_license_usage_data from billing.helpers import get_fake_usage_of_ports, get_fake_usage_by_type, update_license_usage_data, \ get_usage_by_type, get_fake_minutes_use_by_type from reporting.enums import ReportFrequency from .forms import UsageByTypeForm, LAST_MONTH from reporting.decorators import can_access @login_required @can_access def view_update_license_usage_data(request): update_license_usage_data() return HttpResponse() @login_required @can_access def billing_home(request): return render( request, 'billing_list.html', {'section': 'billing_index',} ) @login_required @can_access def usage_by_type(request): user = request.user client = user.client form = UsageByTypeForm( data=request.GET or None, user=request.user, initial={ 'frequency': ReportFrequency.MONTHLY, 'begin': (datetime.now()-timedelta(days=365)).date(), 'end': datetime.now().date() } ) return render( request, 'usage_by_type_of_source.html', {'form': form} ) @login_required @can_access def fake_usage_by_type_json(request): form = UsageByTypeForm( data=request.GET, user=request.user, initial = { 'begin': datetime.now()-timedelta(days=365), 'end': datetime.now() } ) form.is_valid() data = get_fake_usage_by_type( request=request, data=form.cleaned_data, ) return … -
How to filter items in query set without using {% for %} in django
I want to check of some field is exists in a query set that has many rows as result, here are the files views.py def home(request): all_dress = Item.objects.filter(dress_active=True).order_by('-created_at') page = request.GET.get('page', 1) paginator = Paginator(all_dress, 12) try: dresss = paginator.page(page) except PageNotAnInteger: dresss = paginator.page(1) except EmptyPage: dresss = paginator.page(paginator.num_pages) context = { 'dresss': dresss, } return render(request, 'fostania_web_app/home.html', context) the context_processors.py where i get my user_Favs query def include_user_favs(request, user_favs=None): if request.user.is_anonymous: pass else: user_favs = Favorite.objects.filter(user=request.user) context = { 'user_favs': user_favs, } return (context) And here is my HTML code : {% if user.is_authenticated %} {% if user_favs %} {% for item in user_favs %} {% if item.item == dress %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star-yes.png' %}" title="مسح من الفساتين المفضلة"></a> {% else %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a> {% endif %} {% endfor %} {% else %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a> {% endif %} {% endif %} I simply get a multiple result, as it uses the for loop to check on every item and if it found more that … -
HTML event for setting value in input
I am searching for the way to trigger some JavaScript when input field is populated by code. my field looks like this: <input class="form-control" type="string" name="total" id="total" {% if object.total != None %} value="{{ object.total }}"{% endif %} oninput="onChange()" required> In this case, if I type anything inside this field the method is triggered, but if I populate context object with content, this method is not called. (so the object.total is not empty, and the value is set: value=object.total) How do I triggered method when value is populated like value=object.total -
urls error in django 1.11.x upgrade to 2.0
I am migrating my project from django 1.11.x to 2.0. I have everything going well till I got to urls. I happen to have an import like this from cashondelivery.dashboard.app import application as cod_app and i have my url pattern as url(r'^dashboard/cod/', include(cod_app.urls)), but I got the following error in my terminal url(r'^dashboard/cod/', include(cod_app.urls)), File ".../dev/lib/python3.6/site-packages/django/urls/conf.py", line 27, in include 'provide the namespace argument to include() instead.' % len(arg) django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. I would really appreciate a fix. -
how to make role_hierarchy and access_control in django
I am new in django, I have problem that how to make role_hierarchy and access_control in django.. means how to implement admin can view all the pages of all the users and simple logged in user can only view its own pages can not view other user pages.. -
How can I migrate to Django-MYSQL
Work Environment: 1. Django 1.11 2. Python 3.6 3. MySQL Community Server- 5.7.21 I've been using django-jsonfield for my Django models. import jsonfield from django.db import models class MySampleModel(models.Model): name = models.CharField(max_length=123) json_data = jsonfield.JSONField(default={}) As we knew, this particular field doesn't support JSON lookups and aggregation because it created as a LongText in MYSQL backend. So, I decided to use Django-MYSQL, which support JSONField too, hence I changed my models.py as, import jsonfield from django.db import models from django_mysql.models import JSONField as MYSQLJSONField class MySampleModel(models.Model): name = models.CharField(max_length=123) json_data = jsonfield.JSONField(default={}) new_jsonfield = MYSQLJSONField(default=dict) then I ran makemigrations command and it succesfully excecuted and generated migration file.But, when try to run migrate, it throws the error, as django.db.utils.OperationalError: (1101, "BLOB, TEXT, GEOMETRY or JSON column 'new_jsonfield' can't have a default value") Traceback: Running migrations: Rendering model states... DONE Applying spider.0055_run_new_jsonfield...Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 217, in execute res = self._query(query) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", … -
Django test model with fake user
I have a django model I want to test. The model includes a 'user' field. Is there a way of creating a temporary user for the purposes of testing? tests.py from django.test import TestCase from .models import Task from django.utils import timezone from .forms import Taskform # models test class TaskTest(TestCase): def create_task(self, title="Title", description="A description"): return Task.objects.create(title=title, pub_date=timezone.datetime.now(), completed=False, description=description, user='user') def test_task_creation(self): w = self.create_task() self.assertTrue(isinstance(t, Task)) self.assertEqual(t.__unicode__(), t.title) -
from testing in sqlite to postgres primary key starts in a different pk
I am running into a problem when passing from development to production. On the test, sqlite starts the pk in 1 , postgres starts it in 9 (I don't get why , running Propuesta.objects.count() I get 10, so there shoudn't be nothing else before ). This makes my test fail, cause is expecting 1 in the url as pk, how can I fix this behavior ? I have the following test: class PropuestaDetailViewTest(TestCase): @classmethod def setUpTestData(cls): cls.concejo_1 = Alcance.objects.create(nombre_pais="España", nombre_provincia="Asturias", nombre_concejo="Castrillon") cls.categoria = Categoria.objects.create(titulo="ambiente", descripcion="test") number_of_proponsals = 10 for proponsal_num in range(number_of_proponsals): cls.propuesta = Propuesta.objects.create(titulo="titulo_" + proponsal_num.__str__(), descripcion="des_" + proponsal_num.__str__(), creador_de_la_propuesta=User.objects.first(), localizacion=cls.concejo_1) cls.propuesta.categorias.add(cls.categoria) def test_context(self): resp = self.client.get(reverse('participation:detail-view', kwargs={'propuesta_id': 1, 'slug': 'titulo_0'})) self.assertEqual(resp.status_code, 200) self.assertTrue(resp.context['propuesta'].titulo == 'titulo_0') self.assertTrue(resp.context['que_ha_votado'] == 0) self.assertTrue(resp.context['is_user_authenticated'] == 'false') And -
Change Django Admin LogEntry Action Flag
i currently have the LogEntry setup in the Django Admin, everything is working as expected, but i am just am struggling to understand how i can change the Action Flag from say for example '2' to the keyword instead which is 'Change'. This is mainly for a more friendlier user interface as some users wont understand what the Action Flags actually mean. I have had a look in the Repository and see that the action_flag is a PositiveSmallIntegerField you can view the LogEntry Model Here. https://github.com/django/django/blob/master/django/contrib/admin/models.py Flag Choices ADDITION = 1 CHANGE = 2 DELETION = 3 ACTION_FLAG_CHOICES = ( (ADDITION, _('Addition')), (CHANGE, _('Change')), (DELETION, _('Deletion')), ) The action_flag Field in django. action_flag = models.PositiveSmallIntegerField(_('action flag'), choices=ACTION_FLAG_CHOICES) So basically i would like to know if this possible. Here is a screenshot of what it currently shows. I would like those to be Addition,Change or Deletion instead. -
Django: Populate a sqlite3 database with a Pandas Dataframe
Setting: I want to populate the standard sqlite3 db with a Pandas Data frame containing mostly text fields. Those text fields are then indexed and made searchable with elastic search. I have seen several other posts on this, but either they are poorly documented (e.g. lacking models.py or they are using a postgres framework). Code: models.py from django.db import models from .search import transcription_index class transcription(models.Model): identifyer = models.TextField(max_length=20, default='') title = models.CharField(max_length=200, default='') speaker = models.CharField(max_length=50, default='') description = models.TextField(max_length=1000, default='') trans = models.TextField(max_length=30000, default='') # Method for indexing the model def indexing(self): obj = transcription_index( identifyer=self.identifyer, speaker=self.speaker, title=self.title, description=self.description, trans=self.trans ) obj.save() return obj.to_dict(include_meta=True) management/commands/populate.py from django.core.management import BaseCommand from elasticsearchapp.models import transcription from elasticsearchapp.data_get import entry_make class Command(BaseCommand): # Show this when the user types help help = "Load data from dataframe to db" # A command must define handle() def handle(self, *args, **options): # Process data with Pandas dbentry = entry_make() for entry in dbentry.itertuples(): dbentry = transcription.objects.create( identifyer=dbentry.identifyer, speaker=dbentry.speaker, title=dbentry.title, description=dbentry.description, trans=dbentry.trans) entry_make() simply returns a pandas data frame with the cols ['identifyer', 'trans', 'title', 'description', 'speaker'] Problem: When running python3 manage.py populate I get the following error: ValueError: The truth value of a Series … -
'str' object is not callable when i try to use DeleteView in Django
here are my files urls.py the URL paths I created for the delete process path('dress/<int:pk>/delete', views.DressDelete.as_view(), name="dress_delete"), path('dress/delete/confirm', views.dress_delete_confirm, name="dress_delete_confirm"), views.py where i created the view for delete and view that is going to appear after deleting is completed to inform the user from django.urls import reverse_lazy from django.views.generic import DeleteView class DressDelete (DeleteView): model = Item success_url = reverse_lazy('dress_delete_confirm') @login_required def dress_delete_confirm(request): return render(request, 'fostania_web_app/dress_delete_confirm.html') the models.py where is the table I'm trying to delete from : class Item(models.Model): # custom validators alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') # fields dress_name = models.ForeignKey(Name, on_delete='DO_NOTHING', blank=False, verbose_name='نوع الفستان',) dress_rate = models.ForeignKey(Rate, on_delete='DO_NOTHING', blank=False, verbose_name='تصنيف الفستان',) dress_size = models.ForeignKey(Size, on_delete='DO_NOTHING', verbose_name='مقاس الفستان', blank=False) dress_color = models.CharField(max_length=50, verbose_name='لون الفستان', blank=False) dress_image1 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, verbose_name='الصورة الأساسية للفستان', help_text='لا يمكنك تركها فارغة',blank=False) dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافية ', blank=False) dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, verbose_name='صورة إضافة ', blank=False) dress_action = models.ForeignKey(Action, on_delete='DO_NOTHING', verbose_name='الفستان معروض لل ', help_text='للبيع او للإيجار ', blank=False) dress_price = models.IntegerField(default=1, verbose_name='السعر', blank=False) dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='رقم الهاتف ', blank=False) created_by = models.CharField(max_length=250,) created_username = models.CharField(max_length=250, default='unknown') created_at = models.DateTimeField(auto_now=True) dress_active = models.BooleanField(default=False) dress_special = models.BooleanField(default=False) dress_town = models.ForeignKey(Town, on_delete='DO_NOTHING', verbose_name='المحافظة', blank=False) and here is the both … -
Match string with database in django/python
A user will come on website and fill the registration form. Registration form has a question displayed below Which subjects you want to study? Answer by user - I want to study Environmental Studies. sentence="I want to study Environmental Studies" I have 2 database displayed below. Now the answer by the user should match with the one database table with maximum accuracy , The database table matching with maximum accuracy should get selected . I am not able to match with accuracy. Class_A id subject 1 Environmental Studies 2 Physical education Class_B Id subject 1 Social Science 2 Computer Management 3 Hindi views.py def submission(request): obj = Registration.objects.latest('id') obj1 = Registration.objects.filter(name__contains=obj1) for a in obj1: sentence= a.subject word = sentence.split() class_a=class_A.objects.all() class_b=class_B.objects.all() if Class_a.filter(subject__in=word).exists(): return render(request,'data/submission.html',{'Class':'Your Are in Class A'}) elif Class_b.filter(subject__in=word).exists(): return render(request, 'data/submission.html', {'Class': 'You are in Class B'}) The system is working fine with one word subject added in a database Table Like Hindi , English ("I want to study Hindi."). But when 2 words or 3 words Subject is added in a database table like Physical education or Environmental Studies. Then the system doesnt work . Like if the user Fills the registration form by writing … -
boolean value in Django unit test cases
I am writing unit test cases , but my code get fail when boolean value comes to the light. Here is code of test.py class UsersApiTests(APITestCase): self.factory = APIRequestFactory() self.data_dict = {"is_true":True} request = self.factory.post(self.url,data=self.data_dict) force_authenticate(request, user=self.user) response = self.view(request) In views.py def method1(request,is_true): if is_true == True: some code return This code is working fine when i access it using python manage.py runserver but when it comes to testing environment it gets fail. python manage.py test In method1 the value of is_true is "True" a string value instead of boolean value. I also tried with 0 and 1 but it also becomes string and method1 checks the following code if is_true == True >> if "1"== True or >> if "True" == True In this case both of the condition fails how can fix this from test.py file?? Here i have some solution but not 1. Modify method1 make condition like if is_true in ["TRUE","1","True"] make dumps of data json.dumps("is_true":True) and load it in view.py but both the solution are not feasible. because both changes in view.py and both needs large number of changes in my views.py Is there any way to manage this thing from test.py?? Thanks in … -
Is there any possibility to run "django stand-alone executable file using Pyinstaller" in Nginx Server?
Build a web application in Django. Converted this application as an executable file using Pyinstaller. But want to launch this app in Nginx. Is there any possibility? -
Login forms stop working when switching to production
I'm using Wagtail 2.1, Django 1.11.13, django-auth-ldap 1.6.1 and gunicorn 19.8.1 (Nginx as a proxy server). I have created two different ways to login, an AJAX view: def loginajax(request): # Identation is okay, can't seem to paste it properly if request.method == 'POST': login_form = AuthenticationForm(data=request.POST) response_data = {} if login_form.is_valid(): response_data['result'] = '1' response_data['message'] = 'You"re logged in' user = authenticate(username=login_form.cleaned_data['username'], password=login_form.cleaned_data['password']) login(request, user) else: response_data['result'] = '0' response_data['message'] = login_form.errors return JsonResponse(response_data) -A regular, pretty standard Django login form. {% block content %} <div class="login-form" style="width: 90%; margin: 0 auto;"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{% if next %}{{ next }}{% endif %}" /> </form> </div> {% endblock %} I am using … -
Display Django ForeignKey as Textarea in CreateView
By default, Django will display a ForeignKey field as a dropdown menu with all of the valid ForeignKeys available for selection. Instead, I want to display a TextArea and have users enter in a value on their own. How is this done? Adjusting the widget in forms.py is not enough, as Django will still not recognize TextArea input as a valid Object. -
ImportError: cannot import name 'SimpleCookie' error
I tried to runserver with the manage.py but I get this error. I am a newbie in django framework. I am following tutsplus tutorial for news aggregator. bash -cl "/Users/Spandan/PycharmProjects/newsproject/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py runserver /usr/local/lib/python3.6/site-packages/django" Traceback (most recent call last): File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/__init__.py", line 16, in setup from django.urls import set_script_prefix File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/__init__.py", line 1, in <module> from .base import ( File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/base.py", line 8, in <module> from .exceptions import NoReverseMatch, Resolver404 File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/urls/exceptions.py", line 1, in <module> from django.http import Http404 File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/http/__init__.py", line 1, in <module> from django.http.cookie import SimpleCookie, parse_cookie File "/Users/Spandan/PycharmProjects/newsproject/venv/lib/python3.6/site-packages/django/http/cookie.py", line 2, in <module> from http import cookies File "/usr/local/lib/python3.6/site-packages/django/http/__init__.py", line 1, in <module> from django.http.cookie import SimpleCookie, parse_cookie ImportError: cannot import name 'SimpleCookie' -
I am building REST API which stores name, salary and expenses of person,how to post data of multiple people at the same time like an array?
This is my serializers.py file from rest_framework import serializers from .models import Bucketlist class BucketlistSerializer(serializers.ModelSerializer): class Meta: model = Bucketlist fields = ('id','name', 'date_created', 'salary','Expenditure') read_only_fields = ('date_created',) -
django current page to pdf
I am trying to create a "convert to pdf" button for a current page (service detail, which is a dynamic page) I tried to work with ReportLab (as Django documentation suggests, but I just can't make it work, and ReportLab documentation is not saying a word about such possibilities) for now I can create a pdf file out of this view: views.py @login_required def service_detail(request, pk): service = get_object_or_404(Service, pk=pk) return render(request, 'detail.html', {'service':service, 'pk':pk}) @login_required def render_to_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='service/pdf') response['Content-Disposition'] = 'filename="netdevops service.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. p.drawString("Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response urls.py url(r'^service/(?P<pk>\d+)/$', views.service_detail, name='service_detail'), #Services details url(r'^render_to_pdf/', views.render_to_pdf, name='render_to_pdf'), The template of the service detail includes dynamic elements, like: Your location: {{ service.user_location }} <br><br> Anyone knows what can I do, or what other technology I can use to create such PDF? I am mostly working with Python, Django, HTML and CSS -
django builtin form manipulation
I am using builtin django form functionality to generate form for my web app. The dropdown list populates as shown below: In the dropdown I want to get rid of the by default option of "---------". How can I do this? -
Wrong encoding when retrieving get argument
I have a an url encoded with URL encoding, namely : /filebrowser/?cd=bank/fran%E7ais/essais The problem is that if I retrieve the argument through : path = request.GET.get('relative_h', None) I get : /filebrowser/?cd=bank/fran�ais/essais instead of: /filebrowser/?cd=bank/français/essais or : /filebrowser/?cd=bank/fran%E7ais/essais Yet, %E7 does correspond to 'ç', as you can see there. And since the %E7 is decoded with the replacement character, I can't even use urllib.parse.unquote to get my 'ç' back... Is there a way to get the raw argument or the correctly decoded string? -
Is there a simple way to change the location of django imagefield files?
I'm trying to change the upload_to path for one of my model fields which is an imagefield. the current location is 'dir1' and I want to change it to 'dir2'. Is there any simple way to move the current uploaded files as well? I think we can move the files manually and then change the file attribute of that field. But is there an easier way to achieve this?