Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON String Added to DB as Unicode
I'm trying to save a JSON request as strings in a database but having some issues: for some reason, my data is being saved to the database as a Unicode string. What I mean by this is that strings are being saved like this in the database: [{u'content': u'Treehouse', u'name': u'opportunity_name'}, {u'content': u'Robert', u'name': u'user_firstname'}, {u'content': u'Warren', u'name': u'client_firstname'}, {u'content': u'Buffett', u'name': u'client_lastname'}, {u'content': u'Form ABC123', u'name': u'my_name'}] When they should be like this (without the u's): [{'content': 'Treehouse', 'name': 'opportunity_name'}, {'content': 'Robert'... Here's my code, in views.py (data in this can also prints as unicode): @csrf_exempt def send_aggregate_list(request): if request.method == 'POST': data = json.loads(request.body) print 'data' # the output from this print statement is the same, with leading 'u's print data serializer = SendAggregateSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(data,status=201) models.py: class SendAggregate(models.Model): created = models.DateTimeField(auto_now_add=True) is_sent = models.BooleanField(default=False) global_merge_vars = models.TextField() subject_merge_vars = models.TextField() to_email = models.CharField(max_length=256, blank=False) to_name = models.CharField(max_length=256, blank=False) template = models.ForeignKey(Template, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.pk) serializers.py: class SendAggregateSerializer(serializers.ModelSerializer): class Meta: model = SendAggregate fields = ('id', 'created', 'is_sent', 'to_email', 'to_name', 'global_merge_vars', 'subject_merge_vars', 'template') If it helps, here is the output from serializer.validated_data: OrderedDict([(u'to_email', u'rob.grzesik@gmail.com'), (u'to_name', u'Recipient Name'), (u'global_merge_vars', u"[{u'content': u'Treehouse', u'name': … -
How do I change & save a ForeignKey value from within it's parents save in Django?
So I have a MenuItem model, that has a foreign key to itself (called parent), and then it also has a ManyToMany relationship called children. The point of this is because I want to be able to filter the list by TOP TIER entries (entries with no parent) of the same type. AS well I need to be able to access each elements children (all the ones that have a parent pointing to it, as well as their own sub children). E.G Assume this tree represents the information I expect to have access to when I filter the list by TOP TIER entries (entries with no parent) of the same type. In this example I receive 3 pages, where one of the pages has 2 children, and one of those children has 2 children of their own. Page 1 Child 1 SubChild 1 SubChild 2 Child 2 Page 2 Page 3 When I try to override the save function so that I can add to the parents children list, and then save... It doesn't seem to work as when I try to print the contents of the children it says MenuItems.MenuItem.None Here's my code... from __future__ import unicode_literals from django.db … -
Django: Get the form name or id from template
If you have multiple forms from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) class SecondNameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) is there a way that, in your template, you can figure out if form in inside context belongs to NameForm or SecondNameForm I have a custom widget that in its html, it uses the id="" identifier (which should be unique in the whole html). I want to assign the id to something like id="{{form.name}}_{{field.val}}" or id="{{form.id}}_{{field.val}}" or where {{form.name}} and {{form.id}} is some value associated with the form instance and not the form's content. -
Using post_save signal with an abstract class
I'm trying to create a BaseDocument with creation and modification dates: from datetime import datetime from mongoengine import DateTimeField, Document, StringField, signals class BaseDocument(Document): created_at = DateTimeField(default=datetime.utcnow) modified_at = DateTimeField() @classmethod def post_save(cls, sender, document, **kwargs): document.modified_at = datetime.utcnow() meta = { 'abstract': True, 'allow_inheritance': True } signals.post_save.connect(BaseDocument.post_save, sender=BaseDocument) class Book(BaseDocument): id = StringField(primary_key=True) When I create a new Book document: >>> b = Book() >>> b.id = '123' >>> b.save() <Book: Book object> The modified_at field is not shown on Mongo: MongoDB shell version v3.4.0-rc2 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.0-rc2 > use test switched to db test > db.book.find() { "_id" : "123", "_cls" : "Book", "created_at" : ISODate("2016-11-08T18:17:20.761Z") } Is my approach wrong? -
Django Allauth redirection after authentication
I have two django projects. One is using drf and has allauth. The other project serves the HTML and is the front-end. Front-end server calls the drf API for every functionality. Front-end project is not connected to the DRF project databse. When user clicks on Facebook, a request goes to allauth URLs on DRF server. But how do I manage the redirection after authentication? Because I have to redirect to the Front-end server and not the server on which allauth is running. -
Django project- JavaScript function not being recognised...?
I am new to Django/ Python, and am currently trying to debug a Django project. In the webpage I am currently viewing, a table is displayed with a number of rows. The cells in each row hold information regarding a particular project. In the first column of the table, every row displays an image of a + sign, which, when clicked, should duplicate the row in which it appears, adding the duplicated row directly below that row. Currently, when I click the + the first time, a new duplicated row appears below the row in which I clicked the +, however, no new rows are added if I click the + again- a new row should be added for every click. In the browser console, every time I click the + (apart from the first time), I see an error message which says: duplicate_item.js:198 Uncaught TypeError: new_row is not a function(…) duplicateItem @ duplicate_item.js:198 dispatch @ jquery-2.2.2.min.js:3 r.handle @ jquery-2.2.2.min.js:3 I understand that this indicates that the code is trying to call a JS function called new_row, which it can't find. The line where the call to new_row is being performed is in: (function($){ $(document).ready(function(){ $(document).on('click','.duplicate', function duplicateItem(e){ $changed_row = … -
django-allauth: Custom signup doesn't save
I am trying to create a custom signup, filling fields of a Profile model that has a OneToOne relation to User. My form is displayed correctly but saving leads to nothing but a page refresh. Using the standard form coming with django-allauth works though. In my forms.py I have a custom form that uses def signup(self) as the original creator has posted here. This function also seems to never get called. settings.py # allauth settings SITE_ID = 1 ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_FORMS = {'signup': 'accounts.forms.SignupForm'} forms.py class SignupForm(forms.ModelForm): email = forms.EmailField(widget=forms.TextInput( attrs={'type': 'email', 'placeholder': _('E-mail address')})) password1 = PasswordField(label=_("Password")) password2 = PasswordField(label=_("Password (again)")) class Meta: model = Profile fields = '__all__' def signup(self, request, user): print "hi" print request.POST print user new_profile = Profile() new_profile.user = user new_profile['field1'] = self.cleaned_data['field1'] new_profile['field2'] = self.cleaned_data['field2'] models.py class Profile(models.Model): user = models.OneToOneField(User) field1 = models.CharField(max_length=255) field2 = models.CharField(max_length=255) -
JSON Added to Database as Unicode
I'm trying to save a JSON request as strings in a database but having some issues: for some reason, my data is being saved to the database as a Unicode string. What I mean by this is that strings are being saved like this in the database: [{u'content': u'Treehouse', u'name': u'opportunity_name'}, {u'content': u'Robert', u'name': u'user_firstname'}, {u'content': u'Warren', u'name': u'client_firstname'}, {u'content': u'Buffett', u'name': u'client_lastname'}, {u'content': u'Form ABC123', u'name': u'my_name'}] When they should be like this (without the u's): [{'content': 'Treehouse', 'name': 'opportunity_name'}, {'content': 'Robert'... Here's my code, in views.py (data in this can also prints as unicode): @csrf_exempt def send_aggregate_list(request): if request.method == 'POST': data = json.loads(request.body) print 'data' print data serializer = SendAggregateSerializer(data=data) models.py: class SendAggregate(models.Model): created = models.DateTimeField(auto_now_add=True) is_sent = models.BooleanField(default=False) global_merge_vars = models.TextField() subject_merge_vars = models.TextField() to_email = models.CharField(max_length=256, blank=False) to_name = models.CharField(max_length=256, blank=False) template = models.ForeignKey(Template, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.pk) serializers.py: class SendAggregateSerializer(serializers.ModelSerializer): class Meta: model = SendAggregate fields = ('id', 'created', 'is_sent', 'to_email', 'to_name', 'global_merge_vars', 'subject_merge_vars', 'template') -
Django app view - how to get an entry from the django database in the url and to obtain more information from the database for the view?
I have a django application 'test_app'. The test_app page - "domain/test_app/" has a link to another page within the app "Genes". This takes me to "domain/test_app/genes/". In this page I have a list of links which comes from my a table in my django database called "gene", which is in test_app/models.py as class Gene. This links to another table called "Variants" via attribute 'gene' as a foreign key. This is all in test_app/models.py: class Gene(models.Model): gene = models.CharField(primary_key=True, max_length=110) transcript = models.CharField(max_length=100) def __str__(self): return self.gene class Variant(models.Model): variant = models.CharField(primary_key=True, max_length=210) gene = models.ForeignKey(Gene, on_delete=models.CASCADE) cds = models.CharField(max_length=150) def __str__(self): return self.variant My test_app/urls.py urlpatterns look like this: urlpatterns = [ url(r'^$', views.test_app, name='test_app'), url(r'^genes/$', views.genes, name='genes'), url(r'^genes/(?P<gene>)', views.variant_info, name='variant_info'), ] and test_app/views.py look like this (link to test_app/templates/test_app/ directory with my templates in): def test_app(request): template = loader.get_template('test_app/index.html') return render(request, 'test_app/index.html') def genes(request): gene_list = Gene.objects.all() context = {'gene_list': gene_list} return render(request, 'test_app/genes.html', context) def variant_info(request, gene): variant_info = Variant.objects.filter(gene=gene) return(request, 'test_app/gene_info.html', {'variant_info': variant_info} I have a list of genes in my gene table in my database. When obtaining these genes using 'gene_list = Gene.objects.all()' this works fine. I then render this list to a template as a … -
populate table in django template using knockout.js
This is the first time I am trying my hands on Knockout javascript. I am very naive to it so excuse me for the question. I have a view which gives a json response. views.py def get(self, request, code, format=None): data = self.get_details(code) paginator = Paginator(data, self.paginate_by) page = request.GET.get('page', 1) context = {} try: data_sent = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. data_sent = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. data_sent = paginator.page(paginator.num_pages) context['data'] = self.get_user(chain_code) context['page_object'] = data_sent.object_list context['code'] = code data = json.dumps(context, cls=DjangoJSONEncoder) return HttpResponse(data) I want to use this response to populate context['data'] in a table in my django template something like this: Id Name Status 1 xyz 1 2 abc 2 datalist.html <script src="{% static "jsscript/datalist.js" %} "></script> <div class = "container"> <div class = "page-header"> <!---all headers data ---> </div> <div class="tab-content"> <table class="table table-bordered listingtable" > <thead> <tr> <th style="width: 10%;">Id</th> <th style="width: 10%;">Name</th> <th style="width: 20%;">Status</th> </tr> </thead> <tbody> <!----script to populate table---> </tbody> </table> I have gone through the official tutorial of knockout.js, but I'm not sure how to access the response … -
error with interpretation of resources in Django REST + Angular2
I'm try to deploy my app on pythonanywhere and stuck with problem. I'm have this error: Resource interpreted as Stylesheet but transferred with MIME type text/html I don't know why it's happening. In localhost all working fine. full stack trace: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/node_modules/bootstrap/dist/css/bootstrap.min.css". rodion.pythonanywhere.com/:12 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/bower_components/alertify.js/themes/alertify.core.css". rodion.pythonanywhere.com/:13 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/bower_components/alertify.js/themes/alertify.bootstrap.css". rodion.pythonanywhere.com/:14 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/styles.css". rodion.pythonanywhere.com/:24 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/libs/fancybox/source/jquery.fancybox.css". rodion.pythonanywhere.com/:28 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/libs/fancybox/source/helpers/jquery.fancybox-buttons.css". rodion.pythonanywhere.com/:32 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/libs/fancybox/source/helpers/jquery.fancybox-thumbs.css". rodion.pythonanywhere.com/:11 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://rodion.pythonanywhere.com/static/bower_components/font-awesome/css/font-awesome.min.css". jquery.min.js:1 Uncaught SyntaxError: Unexpected token < jquery.mousewheel-3.0.6.pack.js:1 Uncaught SyntaxError: Unexpected token < jquery.fancybox.pack.js:1 Uncaught SyntaxError: Unexpected token < jquery.fancybox-buttons.js:1 Uncaught SyntaxError: Unexpected token < jquery.fancybox-media.js:1 Uncaught SyntaxError: Unexpected token < jquery.fancybox-thumbs.js:1 Uncaught SyntaxError: Unexpected token < bootstrap.min.js:1 Uncaught SyntaxError: Unexpected token < alertify.min.js:1 Uncaught SyntaxError: Unexpected token < shim.min.js:1 Uncaught SyntaxError: Unexpected token < zone.js:1 Uncaught SyntaxError: Unexpected token < Reflect.js:1 Uncaught SyntaxError: Unexpected token … -
How Do I Create Special Fields For Users In Django
I'm new to Django and I want to create an app where artistes can post their songs and albums. Now I want artistes to have a different sign-up page from the normal users. I want artistes to be able to add their portraits, genres, and all that. Is there a way to add these fields to the User model? I've seen some questions on this but I don't think I really understood the answers. -
Can not import front end code
My Django project has the following structure: I am displaying questions.html in the browser: <html> <head> </head> <body> Questions: <div id="questionSpace"></div> <script src="../js/frontEnd/src/App.js"/> </body> </html> questions.html is referencing the code from App.js which is: import {React, Component} from 'react'; import logo from './logo.svg'; import ReactDOM from 'react-dom'; import './App.css'; class App extends Component { componentWillMount() { fetch(`http://localhost:8000/api/questions`) .then(result => { this.setState({questions: result.json()}) }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <ul> {this.state.questions.map(question => <li>question.content</li>)} </ul> </div> ); } } ReactDOM.render(<App />, document.getElementById("questionSpace")); For some reason, the javascript code is not included in the html page. Any idea what could cause this? -
Grabbing a file sent from Django on front-end
I am trying to post a file via http-request (something similar to CURL -F request). So what I want to do is best described by the following code: def my_view(request): string_to_return = '<?xml version="1.0" encoding="UTF-8"?>...' file_to_send = ContentFile(string_to_return) response = HttpResponse(file_to_send,'application/xml') response['Content-Length'] = file_to_send.size response['Content-Disposition'] = 'attachment; filename="somefile.xml"' return response $.get('/my_view/', function(response){ var formData = new FormData(); // file = ??? How do I grab the file ??? formData.append("thefile", file); xhr.send(formData); }); Basically, the question here is how do I grab the xml file in the client. Thanks in advance! -
Why can't we import installed pandas package and use in Django applications?
Please help me understand. Pandas package is already installed and can be used in python applications. However the same package can't be used in Django applications. -
Update list item in rendered django template
In my template I have list retrieved from the server: {% for elem in event_list %} <li id="item{{forloop.counter}}"> <a>...</a> <button onclick="fetch({{elem.id}})">...</button> {{ elem.id }} {{ elem.name }} </li> {% endfor %} When I click on the button I call the server to fetch some new information and want to update that specific list item with the newly retrieved information. How could I do that? My javascript is as follows: function fetch(elem_id){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { resp = JSON.parse(xhr.responseText); document.getElementById("item"+elem_id).innerHTML = resp; } }; url = SERVER_URL xhr.open('GET', url, true); xhr.send(); } I made the server return a dictionary which in javascript is then seen as a JSON object, but I can't successfully update the list item. Any help is appreciated -
django drf serializer with a many-to-many model (with extra data) and inverting the represented relationship
NOTE: this isn't really about getting Django's intermediate model for many-to-many relationship with extra fields to work. this is about how to use Django Rest Framework's Serializers.ModelSerializer with an intermediate model. I have these models (and more): class Method(models.Model): name = models.CharField(max_length=50, unique=True) descripton = models.TextField(null=False) class Version(models.Model): version_number = models.CharField(max_length=50) cmd_line_script = models.CharField(max_length=250, null=False) SOP = models.TextField(null=False) FK_method = models.ForeignKey(Method, on_delete=models.CASCADE) class Meta: unique_together = ('version_number', 'FK_method') class Instrument(models.Model): serial_number = models.CharField(max_length=50, unique=True) asset_number = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) checksum_string = models.CharField(max_length=128, null=True) FK_instr_type = models.ForeignKey(InstrType, related_name='installations', on_delete=models.PROTECT) Instr_Version = models.ManyToManyField( Version, through='Instr_Version', related_name = 'Instr_Version', ) class Instr_Version(models.Model): FK_version = models.ForeignKey(Version, on_delete=models.CASCADE) FK_instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) validating_user = models.ForeignKey(UserProfile, on_delete=models.PROTECT) timestamp = models.DateField(auto_now_add=True) class Meta: unique_together = ('FK_version', 'FK_instrument') and they're fine. I'm trying to use the [Django-Rest-Framework serializers][1] to serialize through the Instr_Version table so an api can retrieve a json representation of all the versions (and their FK_method data, via a MethodSerializer) that are listed as valid for that instrument. I have these serializers so far (and a couple more for InstrType, UserProfile, etc) class MethodSerializer(serializers.ModelSerializer): class Meta: model = Method fields = ('id', 'name', 'description', 'version_set') class VersionSerializer(serializers.ModelSerializer): method = MethodSerializer(read_only=True) #Instr_Version = Instr_VersionSerializer(source='Instr_Version_set', … -
Django multiple separate forms in CreateView
How would you deal with the case of having two separate forms and two models but sharing the same CreateView? For example if you have two models that inherit one abstract model, and in the CreateView it include both forms the context. The form the user submits, should create an instance of its associated model. class EventCreateView(generic_view.CreateView): template_name = 'event/create.html' form_class = OneToOneEventForm second_form_class = GroupEventForm def get_context_data(self, **kwargs): context = super(EventCreateView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class() return context ## how would we deal with post() and form_valid() and object creation? -
Token authentication and regular resources
I have a Django backend with an Angular frontend. The backend exposes a REST API, and the frontend uses token authentication. I have a problem when serving ordinary resources, such as files that are created in the server and are supposed to be downloaded by the client. When the browser accesses these resources (through an <img> tag or an <a href=...>), the token is not added to the HTTP headers and the backend doesn't authenticate the user. I can work both with tokens and with cookies, but I hope there's something easier and more straightforward. -
Django runserver and memcached: variable in cache gets lost
In a Django website I use memcached to save a variable in cache. After some minutes, if I refresh the page, the variable is lost. I am in develop mode using runserver. Any ideas? -
Build system for Django project
I have a project with 2 parts: frontend + backend. Backend is written using Django, FrontEnd using AngularJs2. I want to automate building/deploying process. In order to make it simple I wrote Docker files, so the containers are build automatically. Dockerfiles are not related to any environment, they use prebuilt artifacts. In order to switch between environments like integration, staging, production etc I wrote bash files like build_and_deploy_qa.sh, build_and_deploy_prod.sh. But it doesn't look nice. In the future it might get more complicated and I want it to be more structured. What build tools could I use to make my life easier? Current process of build/deploy contains of these steps: Backend Prepare django app. I change some cluster related stuff to particular environment. Mostly it's just copying files and zipping them. Also I would like to run migrate command once in a while. Building Docker container Pushing an image to my repository FrontEnd ng dist Build frontend Docker container Push docker container What build tools could I use to make it easier? I looked at Gradle, but looks like PyCharm doesn't support it(even via plugins). Also I looked at Pybuilder, but cannot understand if it fits me. I wonder how you … -
Is it possible to create django models from csv in the view?
So this might be a weird or super easy question. Is it possible to build a table(model like) from csv files on the go from django views? -
504 Gateway Time-out when logging as superuser
I am building a docker container for a django app using uwsgi + nginx. Everything goes well when I build and run the container. When I visit the website its all fine,however, as soon as I try to log as the admin i get 504 Gateway Time-out. My nginx.conf file looks as follow: upstream django { server unix:///path/to/socket.sock; # for a file socket } server { listen 80 default_server; listen 443 ssl; server_name 192.168.99.100; # substitute your machine's IP address or FQDN charset utf-8; ssl on; ssl_certificate /path/to/certificate.crt; ssl_certificate_key /path/to/key.key; client_max_body_size 75M; # adjust to taste access_log /path/to/lb_access.log; error_log /path/to/lb_error.log; location /static { alias /path/to/static; # your Django project's static files - amend as required } location / { uwsgi_ignore_client_abort on; proxy_read_timeout 300; proxy_connect_timeout 90; uwsgi_pass unix:///path/to/socket.sock; include uwsgi_params; proxy_set_header X-Proxy-Forwarded-Protocol $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect http:// https://; } } My guess is, that the IP changes and as soon as I try to access I get the error. -
Django invalid form when using modelchoicefield
I am new to Django and I have been struggling to get the selected value of the forms.ModelChoiceField in my views. My form (post) is not valid and I noticed that the request.POST returns all the possible values in the ModelChoiceField. How do I get only model the selected by the user? Thank you in advance for any help. Model I have a sensor model as well as a measurements model... class Sensor(models.Model): # This contains information about a sensor, type, location, and other type = models.CharField(max_length=16) ... class Measurement(models.Model): #This contains the measurements of the sensors at a given date sensor = models.ForeignKey('Sensor') date = models.DateField() temperature = models.FloatField() pressure = models.FloatField() ... class Meta: unique_together = ('sensor', 'date') Form ... and a form that allows the user to choose the sensor and date: class MeasurementForm(forms.ModelForm): #the user is allowed to choose any sensor that is related to the measurement table sensor = forms.ModelChoiceField(queryset=Sensor.objects.exclude(measurement=None)) date = forms.DateField(widget=DateInput(attrs={'format':'%Y-%m-%d'}), initial=datetime.today()) So far so good, this gets rendered by the get method and the user is able to select both sensor and date. However, the following view fails at the post, after submitting: Views class MeasurementView(View): form_class = MeasurementForm my_template = "measurement.html" … -
Like in the admin, adding a related model on the fly in a django form
For the classical example of an Author has many Books and each Book belong to an Author; when I am adding a book (say using a CreateBookView), I get a select input with authors populated as options. Now, if the author I need is not already there, like in django admin, I need to be able to create the author on the spot, and upon submission, the id and name of the author should be inserted back to the create book form as selected option. I would also like the solution to be easily reusable on other models. What is the best way to tackle this problem? For example, I consider to override CreateView model, or use a custom widget and add javascript code to do this. What is the approach that would give the most reliable solution in the least amount of effort?