Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-storages save images webp as octet-stream
when I try to save pillow images using django-storages to store in S3, webp images save them as octet-stream. You should also save images in JPG. I leave below my configuration of django-storages AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'public, max-age=2592000', } AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='WEBP', optimize=False, ) So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='JPEG', optimize=False, ) Thanks! -
Django different types of user
I want to build a simple website with Django, and so far I have made a sign-up form that everyone can sign up and publish some announcement. For next stage I want to make the user can only view the announcement by default, I also want to have another type of user can view and create an announcement. How should I build my user model and sign up forms? Should I use things like permission or AbstractUser? the current sign up forms.py I am using is like from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" and the views about the announcement is like #show all announcement class AnnouncementListView(ListView): ... #show a specific announcement class PostDetailView(DetailView): ... #create a announcement class CreatePostView(LoginRequiredMixin,CreateView): ... Thanks! -
How to redirect when loading a FormView?
Using the class based view FormView I want to redirect to a different page if a user is already activated. So I've tried overriding the get_form_kwargs function: class UserActivateView(AnonymousRequiredMixin, FormView): ... def get_form_kwargs(self): .... if profile.activated: # User is already activated an can log in messages.info( self.request, 'You are already activated. ' 'Login or click forgot password if you have forgotten' ) redirect(to=reverse_lazy('auth_login')) .... return kwargs Using this method the message is added but the redirect is never done. Am I doing this redirect at the correct place, I've been using ccbv as a reference -
Django migration issue: dynamic_forms missing migration as a dependency
One of my migrations specify a particular dynamic_forms migration as a dependency: dependencies = [ ('dynamic_forms', '0004_auto_20170110_1645'), # other deps ] But that file doesn't exist in the migrations directory under the lib's instalation path. The migrations for the version of dynamic_forms I am using, 0.3.3, are: 0001_initial 0002_auto_20140124_1844 0003_auto_20140916_1433 Since the dependency migration doesn't exist, when running migrate, showmigrations, or any other migration-related task, I am logically getting the following error: django.db.migrations.graph.NodeNotFoundError: Migration some_app.0001_initial dependencies reference nonexistent parent node (u'dynamic_forms', u'0004_auto_20170110_164 5') I tried updating the package to its most recent version, 0.5.3, but it didn't help either because it doesn't have that migration file. I tried faking the migrations for dynamic_forms just to see if it helped somehow: py manage.py migrate dynamic_forms --fake But it didn't even go through because the same missing dependency error occurred. I am not sure how to deal with this and although about I did find some information about missing migrations in the dynamic_forms package I couldn't learn how to solve the issue. -
django-import-export : getting post_export to update models
Please how do i updated exported Company model below using post_export signal. I don't want to export items not exported before. So the best thing is using signals. However, if i print the model in the signal at the end of the code below, I get a type class e.g <class 'app.models.Company'> I know am doing something wrong by saving a model but can't find my way arround. Maybe I'm not understanding the documentation of django-import-export library which is found here. #models.py class Company(models.Model): class Meta: verbose_name_plural = "Companies" company_name = models.CharField(max_length=254, blank=True) website = models.URLField(max_length=254, unique=True) address = models.CharField(max_length=254, blank=True, null=True) imported = models.BooleanField(default=False) exported = models.BooleanField(default=False) user = models.ForeignKey(User) def __str__(self): if self.company_name: return self.company_name return self.domain #admin.py from django.dispatch import receiver from import_export.signals import post_import, post_export class CompanyResource(resources.ModelResource): class Meta: model = Company fields = ('website', 'user', 'country', 'source', 'industry') @admin.register(Company) class CompanyAmin(ImportExportModelAdmin): resource_class = CompanyResource list_display = ('domain', 'website', 'exported', 'added_on') list_filter = ('user', 'country', 'imported', 'exported', 'added_on') import receiver from import_export.signals import post_import, post_export @receiver(post_export, dispatch_uid='ss1') def _post_export(model, **kwargs): print(model) model.exported = True model.save() # This line when included raises Error: "save() missing 1 required positional argument: 'self'" so code breaks here -
How to use model's default value in the serializer?
I have a serializer defined by model's fields in the following way: class MyModel(models.Model): f1 = models.CharField(max_length=10, default='abc') class Serializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['f1'] Bit, running: Serializer({}).data Return an empty object. So how can I use the default value declared in the model? I know I can repeat the field in serializer, like that: class Serializer(serializers.Serializer): f1 = serializers.CharField(default='abc') Serializer({}).data This will return the expected {'f1' : 'abc'}, but I do not want to repeat myself. -
error while using makemigration in django
i am working on a development server running python3.6 and django 1.11 with virtualenv when I use "python manage.py makemigrations" i get this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/base.py", line 17, in <module> from django.db.migrations.exceptions import MigrationSchemaMissing File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named 'django.db.migrations.migration' please help me -
Django annotate Avg on model field
I have these models: class Agency(models.Model): pass class User(models.Model): agency = models.ForeignKey(Agency) class Feedback(models.Model): rating = models.DecimalField() user = models.ForeignKey(User) and I want to annotate a queryset with the average of all ratings. I expected this to work: Feedback.objects.annotate(avg_rating=Avg('rating')).values('rating', 'avg_rating') but it just outputs this: <QuerySet [{'rating': 0.8, 'avg_rating': 0.8}, {'rating': 0.2, 'avg_rating': 0.2}, {'rating': 0.6, 'avg_rating': 0.6}, {'rating': 1.0, 'avg_rating': 1.0}, {'rating': 0.4, 'avg_rating': 0.4}]> As you can see the average should be 3.0. Where am I going wrong? For a bit of clarity, I'm trying to do something like this: agencies = Agency.objects.annotate( avg_rating=Coalesce(Subquery( Feedback.objects.filter(user__agency_id=OuterRef('pk')) .values('rating') .annotate(avg_rating=Avg('rating', output_field=DecimalField())) .values('avg_rating') ), 0) ) where the average rating is per agency. Any ideas? -
Django 1.11 EmailMultiAlternatives: ValueError: need more than 1 value to unpack
Iam trying to send an email using EmailMultiAlternative. Using Django 1.11, Python 3.4. However I am getting ValueError. Am using the SMTP backend.This is the code: subject = "Hi {} !".format(user.username) sender = settings.DEFAULT_FROM_EMAIL recipients = [user.email, ] html_content = render_to_string('email/hello.html', {'url': url, 'first_name': user.first_name, 'last_name': user.last_name, 'static': HOST + settings.STATIC_URL,}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, sender, recipients) msg.attach_alternative(html_content, "text/html") msg.send(). However I am get the following error: ValueError: need more than 1 value to unpack Complete traceback here: Traceback (most recent call last): File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/edit.py", line 183, in post return self.form_valid(form) File "/home/george/george/project/new_beco/applications/accounts/views.py", line 87, in form_valid msg.send() File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 123, in _send from_email = sanitize_address(email_message.from_email, encoding) File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 136, in sanitize_address nm, addr = addr ValueError: need more than 1 value to unpack -
Makemigrations error : django.db.utils.OperationalError: no such table
when I makemigrations i get the following error: django.db.utils.OperationalError: no such table: django_site Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\campaign\models.py", line 5, in <module> from sinUser.models import sinUser, sinUserCategories File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\sinUser\models.py", line 4, in <module> from functionUtility.sendEmails import sendEmailFunctionIsError File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\functionUtility\sendEmails.py", line 12, in <module> HOSTNAME = Site.objects.get_current().domain File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 63, in get_current return self._get_site_by_id(site_id) File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 35, in _get_site_by_id site = self.get(pk=site_id) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get num = len(clone) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__ self._fetch_all() File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql raise original_exception django.db.utils.OperationalError: no such table: django_site I am newbies python programming some one can help me thank you -
Image size change by URL Request like Instagram style
I noticed that Avatar in Instagram (sorry I cant post links): thumbnail (150 x 150) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s150x150/e15/11821182_168255950173048_11130460_n.jpg low_resolution (320 x 320) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s320x320/e15/11821182_168255950173048_11130460_n.jpg standard resolution (640 x 640) scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s640x640/sh0.08/e35/11821182_168255950173048_11130460_n.jpg When we change the dimenstion in URL (s640x640 -> s128x128), the dimension of image change automatically. What is it and How can I handle this in Python Django? Is there any package to do this? Thank you! -
Custom inclusion templatetag with djangoCMS render_model
I have created a website with djangoCMS and make heavy use of apphooks, cms plugins, wizards, etc. We have a simple app with just one model holding the core data that should be displayed on the homepage. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from cms.models.fields import PlaceholderField from djangocms_text_ckeditor.fields import HTMLField class Programme(models.Model): name = models.CharField(max_length=60, unique=True) slug = models.SlugField() icon = models.CharField(max_length=50, unique=True) introduction = HTMLField() overview = PlaceholderField( 'programme_overview', related_name='programmes_overview' ) def __str__(self): return self.name def get_absolute_url(self): return reverse( 'programmes:programme-detail', kwargs={'slug': self.slug} ) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Programme, self).save(*args, **kwargs) I decided to create a custom inclusion templatetag for this purpose. templatetags/programmes_tags from django import template from ..models import Programme register = template.Library() @register.inclusion_tag('programmes/programme_list.html') def programme_list(): programmes = Programme.objects.all() return {'programmes': programmes} In the template I use render_model from the cms_tags, because the editors should be able to edit the contents in the frontend. Here is the template: templates/programmes/programme_list.html {% load cms_tags %} {% for programme in programmes %} <div class="col-lg-2 col-md-4 col-sm-6 col-xs-12 text-center flex-item"> <div class="service-box"> <i class="fa fa-4x {{ programme.icon }} wow bounceIn text-primary" style="visibility:visible;"></i> <h3> <a href="{% url 'programmes:programme-detail' programme.slug %}"> … -
Django Form Fields won't show in my template
The form field won't show up in the browser. There is only the submit button showing up. views.py code: def vote(request, pk): # check if request is post if request.method == 'POST': # create a form and populate it with data from request form = forms.Vote(request.POST) if form.is_valid(): fact = Fact.objects.get(pk=pk) fact.votes += int(form.cleaned_data['vote']) fact.save() return HttpResponseRedirect(reverse( 'facts:detail', args=(pk,) )) else: form = forms.Vote() return render(request, 'facts/fact_detail.html', {'form': form}) template(fact_detail.html) code: <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> Form class(forms.py) code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect()) -
Django test deleteview for model with overwritten 'delete' method.
I am writting tests for a django application that contains multiple deleteviews. I test all deleteviews with variations of the following code: #Object exists to begin with response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 200) #Object Can be deleted can be posted response = self.client.post(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 302) #Object is actually deleted response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 404) #Query returns an empty result self.assertFalse( Role.objects.filter(pk=self.role.pk).exists()) All of this is working fine, however, in on of my models I've overwritten the default 'delete' method. Basically everytime I delete a 'TenantPurchase' object I want to check for the existence of a linked 'PurchaseRequest' object and delete it as well. I wrote the following code to do so: def delete(self, *args, **kwargs): try: purchase_user = self.user purchase_arrangement_period = self.item #Import here to avoid circular import from arrangement.models import ArrangementBuyRequest linked_buy_request = ArrangementBuyRequest.objects.filter( user=purchase_user, arrangement_period=purchase_arrangement_period) \ .order_by('request_date').last() linked_buy_request.delete() except (ArrangementBuyRequest.DoesNotExist, AttributeError) as e: pass super(TenantPurchase, self).delete(*args, **kwargs) When I test manually on our development server, I behaves as it should. Linked buy Requests are deleted and no errors are thrown. However, all my Unittests for this model fail. It passes the first three tests (assert 200, assert 302, assert 404) But a direct … -
Django loop through list
How do you loop trough a list in django templates with a for loop? my problem is with trying to fetch list.0 list.1 list.2 But when running the code i don't get anything {% for i in range %} {% for key, value in list.i.items %} {{ key }} {{ value }} {% endfor %} {% endfor %} where i should be list.0-2 but it doesn't show anything on screen -
In form view, how to put the template_name on the current page
Everything is in the title, I have a problem with the form error and I think to solve it I have to put the template name on the current page. Thanks =) -
Not able to link the template page of Django
I am trying to make an application using django-allauth; My Django version is 1.11.5. I am trying to display the result on another template: facebook_personality_traits.html Here is the code: settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = 'facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True } } ACCOUNT_LOGOUT_ON_GET = True views.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') urls.py url(r'^facebook_personality-traits/&', views.fb_personality_traits, name="fb_personality_traits"), facebook_personality_traits.html <html> <body> Welcome back {{ user.first_name }} {{ user.last_name}} <a href="/">Home</a> </body> </html> But I could able to make it run effectively. I guess there is some issue where I have declared the url for the site. Here is the snapshot of the error: Kindly suggest me the missed part. -
Can I override Django password form layout?
I have overridden the Django login and registration forms by creating the templates registration/login.html, registration/logout.html, registration/registration_closed.html and registration/registration_form.html. However, the password change forms are in the original style. Unlike the existing forms, it doesn't look like django-registration.registration.auth_urls specifies HTML templates for these password forms. So how can I override them to look like my custom templates? -
How to detect related models get saved in django model and save the instance model
I am working on django, and I am in a situation, that I need to run some function, after all the related models of django model get saved in database. Let say I have a model models.py from . import signals class Video(models.Model): """Video model""" title = models.CharField( max_length=255, ) keywords = models.ManyToManyField( KeyWord, verbose_name=_("Keywords") ) When the new instance of video model is created. I need to 1. All the related models get saved first. a. If the related models are empty return empty or None 2. and then Save this video instance. I tried to do it using post_save signals, but couldn't succeded as there is no gurantee that related models get saved first that this video model. from django.db.models.signals import post_save, pre_delete, m2m_changed from django.dispatch import receiver from .models import Video @receiver(m2m_changed, sender=Video) @receiver(post_save, sender=Video) def index_or_update_video(sender, instance, **kwargs): """Update or create an instance to search server.""" # TODO: use logging system # Grab the id print("Id is", instance.id) # Keywords is empty as keyword instance is saved later than this instace. keywords = [keyword.keyword for keyword in instance.keywords.all()] print(keywords) # [] empty no keywords instance.index() @receiver(pre_delete, sender=Video) def delete_video(sender, instance, **kwargs): print("Delete index object") instance.delete() -
Using `subprocess` in a web service
I'm trying to leverage wkhtmltopdf to make a render-on-the-fly endpoint in a Django web app. The only way I'm aware of if to execute the external tool in a subprocess, for e.g.: from subprocess import Popen, PIPE from rendering.service.settings.local import WKHTMLTOPDF_PATH class HtmlToPdfView(APIView): def post(self, request): process = Popen([ WKHTMLTOPDF_PATH, '--disable-smart-shrinking', '-', '-' ], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout, stderr = process.communicate(input=bytes(request.data['html'])) return Response({'pdf': stdout}) But I have a general bad feeling about this. Should I worry about things like SIGFAULT? Am I even doing it right? Should I join() or poll() the process to make sure wkhtmltopdf is done with it's execution? Should I use close_fds=True? -
Is it ok to use app config variable as CharField choices?
Is it correct to use a AppConfig variable in model? myapp/apps.py class MyAppConfig(AppConfig): name = 'my_app' my_list = None def ready(self): self.my_list = ( ('a', 'A'), ('b', 'B'), ('c', 'C'), ) anotherapp/models.py AnotherModel(models.Model): options = models.CharField( max_length=1, choices=apps.get_app_config('my_app').my_list) -
Django redirect having a ValueError
I am having a valueerror on my redirect function below. I checked previous updates which specified that this would occur when the name argument is not specified. I already did but its still not working for some strange reason. The traceback is below ValueError at / dictionary update sequence element #0 has length 0; 2 is required views.py class HomeView(TemplateView): template_name = "home.html" title = 'Your Dashboard' def get_context_data(self, *args, **kwargs): if self.request.user.is_authenticated(): fav_polls = PollFav.objects.filter(fav_user=self.request.user) poll_types = [] for poll in fav_polls: poll_types.append(poll.poll.polltype_id) poll_types = Ptype.objects.filter(pk__in=list(set(poll_types))) context = super(HomeView, self).get_context_data(*args, **kwargs) context["submit_btn_value"] = "Send" context["title"] = self.title context["poll_types"] = poll_types todate = datetime.datetime.now().date() user = self.request.user context["pollsCreated"] = Ptype.objects.filter(c_user=user).count() context["pollsECreated"] = PollItem.objects.filter(user_submit=user).count() try: context["user"] = PUser.objects.get(user_id=self.request.user.id) except: #where the issue is return redirect("PUserCreate") return context urls.py url(r'^puser/add/$', PUserCreate.as_view(), name='PUserCreate'), -
form instance inside loop django
I'm looking to save my form instance and I found Create objects in for loop. How can I achieve similar effect if I have: pk = self.kwargs['pk'] C = {'dog':'Nash', 'cat':'Luffy'} for animal,owner in ngipon.items(): form.instance.owner = owner form.instance.animal = animal form.instance.patient = Clinic.objects.get(pk=pk) -
Running celery task on Ubuntu with supervisor
I have a test Django site using a mod_wsgi daemon process, and have set up a simple Celery task to email a contact form, and have installed supervisor. I know that the Django code is correct. The problem I'm having is that when I submit the form, I am only getting one message - the first one. Subsequent completions of the contact form do not send any message at all. On my server, I have another test site with a configured supervisor task running which uses the Django server (ie it's not using mod_wsgi). Both of my tasks are running fine if I do sudo supervisorctl status Here is my conf file for the task I've described above which is saved at /etc/supervisor/conf.d the user in this instance is called myuser [program:test_project] command=/home/myuser/virtualenvs/test_project_env/bin/celery -A test_project worker --loglevel=INFO --concurrency=10 -n worker2@%%h directory=/home/myuser/djangoprojects/test_project user=myuser numprocs=1 stdout_logfile=/var/log/celery/test_project.out.log stderr_logfile=/var/log/celery/test_project.err.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 My other test site has this set … -
Random Option In Django Drop Down Form
I've been picking my brain trying to figure this out and so now I turn to the community for help. I'm using models to create a form in Django and I want to add a Random option to a few of the drop-down choices. Here is a general idea of what I'm working with: models.py Character(models.Model): name = models.CharField(max_length=255,unique=True) age = models.PositiveIntegerField(default=0) gender = models.CharField(max_length=20,choices=creation_choices.GENDERS) race = models.CharField(max_length=500,choices=creation_choices.RACE) creation_choices.py GENDERS = ( ('male',"Male"), ("female","Female"), ("unknown","Unknown"), ) RACE = ( ('human','Human'), ('elf','Elf'), ('dwarf','Dwarf'), ) What I am trying to do is add a way for users to select Random and it returns one of the other values. I tried a lot of different methods but most returned an error. When I created a function with random.choice() and pushed that through it seemed to work, but for some reason always returned the same value. Any help would be greatly appreciated!