Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to call a field of a django model from the id?
I cant find the error in this code the code call a model id from select and store it in a variable , after i need to recupere two champs of models and store like a char in array <script> $(document).ready(function() { $("#resoudre").click(function(){ var strVehicules = $('#vehicule_sel')[0].value.innerText; var vehicules = strVehicules.split(" "); var idDemandes = $('#pt_collecte')[0].value; p = PointCollecte.objects.get(id=idDemandes); var strDemandes = (p.Latitude,p.Longitude); var demandes = strDemandes.split(" "); }); }); </script> -
NoReverseMatch at /admin/ Reverse for 'logout' with no arguments not found. 1 pattern(s) tried: ['$admin/logout\\/$']
my code for MainProjects.urls is from django.conf.urls import url from django.contrib import admin from django.conf.urls import include admin.autodiscover() urlpatterns = [ url(r'^$',include('register_complaint.urls')), url(r'^register/',include('register_complaint.urls')), url(r'^admin/$', admin.site.urls), ] I have tried removing '$' from 'admin' still the same error occurs. Request URL: http://localhost:8000/admin/ Django Version: 2.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'logout' with no arguments not found. 1 pattern(s) tried: ['$admin/logout\/$'] -
Django render template in template using AJAX
My site currently renders forms on their own page. I'm trying to get them to render inside a sidebar div tag now on my main page. However, I can't figure out how to shape the JavaScript and/or View so I get the HTML of the form template back and inserted into the div tag. HTML (tag on the main page which I want to inject the form template into): <div id="sidebar"> </div> JavaScript $(function() { $("#new-trend").click(function(event){ alert("User wants to add new trend"); //this works $.ajax({ type: "GET", url:"/new_trend/", success: function(data) { $('#sidebar').html(data), openNav() } }) }); }); VIEW def new_indicator(request): # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = IndicatorForm(request.POST) # check whether it's valid: if form.is_valid(): indicator = form.save(commit=False) indicator.author = request.user indicator.modified_date = timezone.now() indicator.save() return redirect('dashboard') else: form = IndicatorForm() return render(request, 'mysite/sidebar_trend.html', {'form': form}) -
Relation does not exist in django admin site after migrations
I'm getting a "relation does not exist error" when attempting to access a model page on my django admin site. Accessing the user model from the admin site works normally. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/web_app/work/ Django Version: 2.0.4 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'web_app.apps.WebsiteConfig', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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 "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (relation "web_app_work" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "web_app_work" ^ ) was the direct cause of the following exception: File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\contrib\admin\options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\utils\decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\utils\decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\contrib\admin\options.py" in changelist_view 1570. cl = self.get_changelist_instance(request) File "C:\Users\danie\Envs\Prolitfic\lib\site-packages\django\contrib\admin\options.py" in get_changelist_instance 705. … -
Can't generate autodoc using Sphinx in my Django project
I'm addind documentation to my Django project (github link, the project is open source) using sphinx, but I'm getting a lot of bugs when a try to generate autodoc of python files. I'm including a models.py file with docstrings but, when a run make html I'm getting different bugs. I have made some changes and the bug is changing, but I'm not sure if I am fixing them or only generating a new bug. If a remove the inclusion of the models.py file, all run perfectly. In other words, the bug is only generated when I include the following lines in a .rst file: .. automodule:: account.models :members: Let me show you what have I done. My first bug was the following, when I run the make html command: WARNING: autodoc: failed to import module u'account.models'; the following exception was raised: No module named account.models I have added the following lines to the sphinx confg.py file: import os import sys sys.path.insert(0, os.path.abspath('../../')) I have created a folder called docs to include all files generated by the sphinx-quickstart command, for this reason, the value of the abspath is ../../. Ok, now, when I run the make html command, I got the … -
How to customize the default <option> in a selector
I have created the following form: class ProductFilter(forms.Form): price = forms.IntegerField(label='Price', widget=forms.Select(choices=PRICE_CHOICES), required=False) category = forms.ModelChoiceField(queryset=Category.objects.all(), required=False) language = forms.ModelChoiceField(queryset=ProductLanguage.objects.all(), required=False) The default in both category and language is displayed as "------------". I know i can set "initial=...", but i would like the default option to be something that is not part of the queryset. Is it possibe to insert an option somehow? I dont want to create a language or a category called "all". -
How do I make a list for a drop down menu in django?
The title may be a bit obscure. I am trying to produce a drop-down menu in django based on the following code: class MyForm(forms.Form): person_list = PersonYear.objects.all().values('person__pk', 'person__TLA') person = forms.CharField(label='Säljare',widget = forms.Select(choices=person_list)) I was trying this, because my understanding is that I need a list of the form person_list = [(1 , 'Abc'), (2, 'CDe'),...] but my person_list has the form <QuerySet [{'person_pk : '1', 'person_TLA : 'Abc'}, {'person_pk : '2', 'person_TLA : 'CDe'}].......> So it does not work. How should I be doing this. I want to get a drop-down menu with the TLA:s from which I then can identify the pk. -
Validate new users passwords in Django admin interface
There is one interesting moment in Django documentation: By default, validators are used in the forms to reset or change passwords and in the createsuperuser and changepassword management commands. Validators aren’t applied at the model level, for example in User.objects.create_user() and create_superuser(), because we assume that developers, not users, interact with Django at that level and also because model validation doesn’t automatically run as part of creating models. But in my Django app i am using only Django Admin interface with admin.ModelAdmin. When i am trying to create new user i can broke all the validators from AUTH_PASSWORD_VALIDATORS. How can i validate passwords on creating new users in Django admin interface using validators AUTH_PASSWORD_VALIDATORS? -
django, getting objects from database to the template in viewable form
I'm new to Django, and the question is how to how to pass variables from the database to the template in a form where they are visible. The information in the database and model was created by using pandas to take the CSV file and to create the model. After a little searching around I was able to add a primary key to data base and when using /admin I am able to see that the db is populated with information from the CVS file. Now the problem seems to be that an object is being passed to the template rather than a string that would be visible. In the views I have def newsinspector(request): df=Df.objects.all() return render(request,'boards/the_file.html',{'df':df}) In the template I have <h1>Title: {{ df.Name }}</h1> <p><strong>My info:</strong> {% for d in df.all %}{{d}}{% if not forloop.last %}, {% endif %}{% endfor %}</p> The model generated by the inspectdb looks like class Df(models.Model): index = models.IntegerField(primary_key=True, blank=True, null=False) user_rank = models.IntegerField(db_column='User_Rank', blank=True, null=True) # Field name made lowercase. name = models.TextField(db_column='Newspaper_Name', blank=True, null=True) # Field name made lowercase. # some other similar fields mostly TextFields class Meta: managed = False db_table = 'df' The issue is that I seem … -
Django Rest Framework ViewSet loses pagination, SearFilter and OrderingFilter when overriding list() method
I have to override default list() method of a DRF ViewSet but, when I do so, all filtering, ordering and pagination stop working. This is the code of the ViewSet: class ZoneViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.Zone.objects.all() serializer_class = serializers.ZoneSerializer filter_backends = (SearchFilter, OrderingFilter,) search_fields = ('city', 'name') def list(self, serializer, pk=None): if pk: queryset = models.Zone.objects.filter(city=pk) else: queryset = models.Zone.objects.all() serializer = serializers.ZoneSerializer(queryset, many=True, context={'request':self.request}) return Response(serializer.data) How can I override list() method without losing this functionality? -
How to create hierarchy of models?
How can I make hierarchy in django? I want to create a tree of Persons. I understand that I should add parent field to Person model. What do I need to change in model and view? Also I want to use tree-view to represent hierarchy. class Person(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name def add_person(request): if(request.method == 'POST'): name = request.POST['name'] person = Person(name=name) person.save() return redirect('/persons') else: return render(request, 'add_person.html') -
How to make a Django App to Track People's Weight
I am doing an application in Django to upload peoples Weight and allowing them to Track their evolution daily. I have the following model, form , view and url : Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) heigth = models.IntegerField('Altura', blank=True, null=True) weigth = models.DecimalField('Peso', max_digits=5, decimal_places=2, blank=True, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() messages.success(request, _('Your profile was successfully updated!')) return redirect(settings.LOGIN_REDIRECT_URL) else: messages.error(request, _('Please correct the error below.')) else: profile_form = ProfileForm(instance=request.user.profile) return render(request, 'catalog/profile.html', { 'profile_form': profile_form }) Forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [ "heigth", "weigth", def __init__(self, *args, **kargs): super(ProfileForm, self).__init__(*args, **kargs) urls.py urlpatterns = [ url(r'^profiles/update/$', views.update_profile, name='update_profile'),] I want to monitor the updates in value of WEIGHT field in my model per user, and generate a chart with the date and last saved value of the day per user. Like a WEIGHT TRACKER. Does anyone have any idea how to do it? -
ModelForm with Many-to-Many relationship: how to automatically create new entries if needed?
I have two models with a ManyToMany relationship: class Topping(models.Model): name = models.CharField(max_length=200) class Pizza(models.Model): name = models.CharField(max_length=200) toppings = models.ManyToManyField(Topping, blank=True) I have this form to update a pizza: class PizzaUpdateForm(forms.ModelForm): class Meta: model = Pizza fields=('name', 'toppings') widgets={'toppings': Select2TagWidget} The Select2TagWidget is imported from django_select2. I would like to use it to allow dynamic pizza topping creation (sounds cool, doesn't it?). This form is used through this view: def update_pizza(request, pk): pizza = Pizza.objects.get(pk=pk) if request.method == 'POST': form = PizzaUpdateForm(request.POST, instance=pizza) if form.is_valid(): form.save() else: form = PizzaUpdateForm(instance=pizza) return render(request, 'pizza/pizza_form.html', {'form': form, 'pizza': pizza}) Right now, it works for pre-registered toppings but I would like to allow my users to define new toppings via this same form, which is why I'm using select2 in the first place. Unfortunately, the form doesn't validate if I do so right now, which is to be expected. If I try to add an illegal_topping, here's what happens: "illegal_topping" is not a valid value. I think that I need to iterate over form['toppings'].value() in the if request.method == 'POST' block before calling form.is_valid() in order to create the new toppings, using get_or_create or something similar. However, if I do that, the … -
Django Migrations does not apply changes in models
Whenever I add/remove/modify anything in models.py and the following commands the project does not make those changes to the database models. python manage.py makemigrations OR python manage.py makemigrations OR Python manage.py migrate All the above command throws the same error as below: " return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column " Tried deleting the migrate folder (without deleting , running fake migrations , running zero migrations but nothing helped. Please advise. -
python - best way to compare objects property by specific other property
I'm using python 3.5.3 I have the following State class: class State(BaseModel): title = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=100, blank=True, null=True) machine = models.ForeignKey(machine, related_name='states') data = JSONField(blank=True, null=True) I'm trying to get all states that point to specific two machines and verify that the 'data' property is the same where the 'name' is the same. This is how I done it: new_machine_states = State.objects.filter(machine_id=new_created_ma_id) for new_state in new_machine_states: existing_machine_state = State.objects.filter(machine_id=existing_ma.id, name=new_state.name) self.assertEqual(new_state.data, existing_machine_state[0].data) But I guess there's a better cleaner way to do that. Any idea? -
DJANGO - Assign permissions from Admin Panel to an user only for some objects from Model
DJANGO In ADMIN PANEL using my superuser account I want to give permissions at users to view/change/delete to some objects , not all of them from a Model.By default in ADMIN PANEL you can give permissions for entire Model and not for some objects from it(Model). I will give you an example: class Professor(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) lastname = models.CharField(max_length=25,null=True,blank=False) firstname = models.CharField(max_length=25,null=True,blank=False) email = models.EmailField(max_length=40,null=True,blank=False) class Course(models.Model): name = models.CharField(max_length=50,null=True,blank=False) professor = models.ForeignKey(Professor,on_delete=models.CASCADE) content = models.TextField(blank=True,null=True,help_text='') For example I will create 3 courses: X,Y,Z The professor teaches Y and Z. In ADMIN PANEL,after I will create an user for this professor,I will give him STAFF STATUS and I want to give him also permissions only for 2 objects from Model Course (Y and Z) not for all. How can I do that? In the final I want to be easy to give permission from ADMIN PANEL not to entire Model but to some objects from it. Thank you so much. -
My text editor generating extra braces, how to get rid of it
I need to setup a text editor for better posting capability into my project (Django 2.0) and I'm using quilljs for it. This is working but some error is attached along with the post. Code here <form action="" method="post"> {% csrf_token %} <input name="description" type="hidden"> <div id="editor-container"> </div> <input class="ui button" type="submit" value="Post" /> </form> Javascript var quill = new Quill("#editor-container", { modules: { toolbar: [ ['bold', 'italic'], ['link', 'blockquote', 'code-block', 'image'], [{ list: 'ordered' }, { list: 'bullet' }] ] }, placeholder: 'Compose an epic...', theme: 'snow' }); var form = document.querySelector('form'); form.onsubmit = function() { // Populate hidden form on submit var about = document.querySelector('input[name=description]'); about.value = JSON.stringify(quill.getContents()); console.log("Submitted", $(form).serialize(), $(form).serializeArray()); }; after post, the result is like that {"ops":[{"insert":"A robot who has developed sentience, and is the only robot of his kind shown to be still functioning on Earth.\n"}]} How to get rid of this extra braces. TIA -
Django REST Framework: create related model from POSTed data
Using the following models: class Ticket(models.Model): [some irrelevant fields] class TicketComment(models.Model): text = models.TextField() creator = models.CharField(max_length=255) ticket = models.ForeignKey(Ticket, models.CASCADE, related_name='comments') I created the following serializers: class TicketSerializer(serializers.ModelSerializer): [irrelevant] class TicketCommentSerializer(serializers.ModelSerializer): class Meta: model = TicketComment fields = '__all__' def create(self, validated_data): return TicketComment.objects.create(**validated_data) A view: class TicketCommentView(APIView): lookup_url_kwarg = 'ticket_id' def post(self, request, ticket_id): data = request.data data['creator'] = 'joe' try: data['ticket'] = Ticket.objects.get(pk=ticket_id) except Ticket.DoesNotExist: raise NotFound('Ticket {} does not exist.'.format(ticket_id)) serializer = TicketCommentSerializer(data=data) serializer.is_valid(raise_exception=True) comment = serializer.save() return Response(comment, status=HTTP_201_CREATED) And URL pattern: urlpatterns = [ path('ticket/<int:ticket_id>/comment', TicketCommentView.as_view()), ] However, when trying to POST the data {"text": "test"}, it fails with: "ticket": ["Incorrect type. Expected pk value, received Ticket."] If I change the view to pass the ticket_id integer instead of the ticket instance, it complains about duplicate keys: django.db.utils.IntegrityError: duplicate key value violates unique constraint "ticketcomment_pkey" DETAIL: Key (id)=(41993) already exists. How can I create a resource and attach it to an existing related object? -
Populating django-taggit field with custom command
I have a custom command to populate Django objects with JSON data that is working mostly the way I want, but I'm having a problem with django-taggit fields. After parsing all of my data and outputting it in JSON, the genres look like this in my JSON objects: "genres": "latin pop, pop, singer-songwriter", django-taggit takes a comma-separated list of tags, which is what this is. But when I run the below custom command, nothing is put in the genres = TaggableManager() field from my model. import json import dateparser from django.db import IntegrityError from django.core.management.base import BaseCommand, CommandError from concerts.models import Concert, Venue class Command(BaseCommand): help = "Load JSON concert data" def add_arguments(self, parser): parser.add_argument('concert_file', type=str) def handle(self, *args, **options): with open(options['concert_file']) as f: data = json.load(f) for concert in data: try: venue = Venue.objects.get(name=concert['venue']) except Venue.DoesNotExist: print "Can't find venue! " + concert['venue'] pass del concert['venue'] try: Concert.objects.create(venue=venue, **concert) except IntegrityError: print concert['slug'] + ": This concert already exists!" pass # if the slug unique contrainst fails, just pass this concert How can I get the genres field to populate the way I want? -
generate token for non-user models in django rest
I have a non user model which is related to another model by ForeignKey. I want to make that non user model directly connected to other model without choosing on form i.e. by directly like user by token. Can token be generated for such purpose or there are any other options? Plz help in detail. -
Django Inline Admin: Changing Model that Through Model Links To
So in the Django admin, I have 3 models: Gallery GalleryMedia (the through model that links Gallery and Media in a many-to-many relation) Media I have set up the Gallery admin page so that there is an inline admin representing GalleryMedia. However, I need to be able to modify the Media table from the Gallery admin with this inline admin, not just the GalleryMedia table. Specifically, each piece of Media has an alt tag that I want to be able to modify from the Gallery that contains the Media. This alt tag should be a property of the Media, not the relationship between the Gallery and the Media. How do I accomplish this? Currently, I have resorted to the hack of creating methods for the GalleryMedia model that display inputs in the inline admin, and then I have used javascript to bind a submit event of the Gallery form to pass the data about these to a view that changes them. As we are adding more fields that should be editable in this way, I want to get away from this if possible. -
Django: Loop over list of objects and save in model with ForeignKey
I'm trying to use the pycryptodome implementation of Shamir's Secret Sharing. When splitting the shares the output is a list object with tuples of this form: <class 'list'>: [(1, b'\x84\x16H\x92\xaaJ\xf7\x84_\xf9\x02\x03\x86\xff\xb7Z'), (2, b'\x86p\xbe5\xbfP\xe4\x00m\x16\xd3\t\xb3\xc8\xfa\x1f'), (3, b'xR\xecWLY\x15||\xb3\x9c\x0f\xa0\xda>\xa1'), (4, b'\x82\xbdS{\x95d\xc3\x08\x08\xc9q\x1d\xd9\xa6`\x95'), (5, b'|\x9f\x01\x19fm2t\x19l>\x1b\xca\xb4\xa4+')] After hexlify in a for loop the object is much more readable : for idx, share in shares: print ("index #%d: %s" % (idx, hexlify(share))) index #1: b'84164892aa4af7845ff9020386ffb75a' index #2: b'8670be35bf50e4006d16d309b3c8fa1f' index #3: b'7852ec574c59157c7cb39c0fa0da3ea1' index #4: b'82bd537b9564c30808c9711dd9a66095' I have this model: class MyModel(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) some_other_id = models.ForeignKey(OtherModel, on_delete=models.CASCADE, null=True) encrypted_share = models.CharField(max_length=200, blank=True) I want somehow to filter MyModel for a specific some_other_id and then for each user_id entry save a single share from the list object enrypted with the user's public_key taken from the user_model. Here's how I create the shares in my views.py: number_of_users = MyModel.objects.filter(some_other_id=self.object.pk).count() minimum_shares = (number_of_users*7)//10 shares = Shamir.split(minimum_shares, number_of_users, key) -
How can i save a Panda dataframe to a django model?
I am trying to read a csv file using panda and parse it and then upload the results in my django database. Well, for now i am converting each dataframe to a list and then iterating over the list to save it in the DB. But my solution is inefficient when the list is really big for each column. How can i make it better ? fileinfo = pd.read_csv(csv_file,sep=',',names=['Series_reference','Period', 'Data_value','STATUS', 'UNITS','Subject','Group','Series_title_1','Series_title_2','Series_title_3','Series_tile_4','Series_tile_5'],skiprows=1) #serie = fileinfo[fileinfo['Series_reference']] s = fileinfo['Series_reference'].values.tolist() p = fileinfo['Period'].values.tolist() d = fileinfo['Data_value'].values.tolist() st =fileinfo['STATUS'].values.tolist() u= fileinfo['UNITS'].values.tolist() sub = fileinfo['Subject'].values.tolist() gr = fileinfo['Group'].values.tolist() stt= fileinfo['Series_title_1'].values.tolist() while count<len(s): b = Testdata(Series_reference=s[count], Period=p[count], Data_value=d[count], STATUS=st[count], UNITS= u[count],Subject=sub[count],Group=gr[count],Series_title_1=stt[count]) b.save() count=count+1 -
Django - Access pre-existing data in mySQL database
What I'm trying to do is this: I have a csv file containing some public transport data. I want to use this in my Django app, so I imported the csv to my mySQL database. Then, I created a Django model for the table (I also compared my model against the output of python manage.py inspectdb to make sure it was correct. Then I ran python manage.py makemigrations and finally python manage.py migrate. From what I understand (and I am new to Django, so sorry if I've missed something obvious), the table in my database should now be accessible to Django. It's not working though. I've tried using the Django shell (python manage.py shell) and returning the table contents with Stops.objects.all(), which returns an empty set. Similarly, I was able to make a HttpResponse with the value of Stops.objects.all() and, though it didn't give an error, no data was returned. I've confirmed that I'm accessing the correct database in settings.py, and that the data is in fact there via mysql terminal. I've been trying to fix this for ages, but haven't found any solutions. I think there's probably some small step I've missed out, that hopefully someone here will know. … -
Unicode characters in JSON data messing up loading JSON data
I'm happy to provide more code, but in an attempt to keep this to the point, I'll keep it brief to start. I have JSON data I pull from a web scraper. It includes occasional unicode values, which are no big deal in most instances. Here's the problem: "venue": "St. John\u2019s Episcopal Church", One of my JSON objects contains this. Venue is a foreign key for a Concert object, and it's looked up like this in my custom command: venue = Venue.objects.get(name=concert['venue']) The problem is that because the JSON renders the apostrophe as \u2019 and my venue is just named with the apostrophe character, the lookup fails. When I print this data in my Python parser, it renders the apostrophe, so a simple concert['venue'] = concert['venue'].replace("\u2019", "'") does not work. What can I do?