Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Only accessing __str__ when retrieving from database
I am attempting to retrieve information from a database, specifically a set of emails: Views.py: context['allEmails']=emails.objects.all() Models.py: class emails(models.Model): author = models.CharField(max_length=100) recipient = models.CharField(max_length=100) subject = models.CharField(max_length=100,blank=True) body = models.TextField(blank=True, null = True) timestamp = models.DateTimeField() showTo = models.ForeignKey(User,default="1") def __str__(self): return self.subject However, when i get all of the emails, it only gets their subject lines. When I remove str, it gets them as objects. What am I doing wrong here? Thanks! -
Django URL not hitting the view - String Regex
I have a URL like this: url( r'^(?P<type>[\w-]+)/$', views.FindByTypeView.as_view(), ), And a view like: class FindByTypeView(APIView): def get(self, request, type): The URL does not seem to hit the view. Is something wrong with the regex? Been scratching my head over this. What is wrong? Thanks for the help! -
operations on request data in DRF
i am new to django and have looked everywhere but cannot find a concrete answer. so i have a model and a model serializer one of my fields is vote, i want to be able to increment that value if the instance of that model is updated and the field vote has 1 as its value and decremented if its -1 basically i want to run operations or a function on the data that is passed through before storing it to the database class ImageSerializer(serializers.ModelSerializer): image = serializers.CharField() class Meta: model = Image fields = ( 'image', 'winner', 'votes', 'event' ) read_only_fields = ('id',) -
How add select element to Bootstrap’s modal?
In my template, there are two parts. The first part contains the list of choices and the second part is a modal window. I would like to add in my input (modal window) the selected element from my list of choices. Here is my template: {% block content %} <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <select name="name_id" size="1"> {% for i in list_utilisateur %} <option value={{ i.user_id }}>{{ i.username }}</option> {% endfor %} </select> <button class="btn btn-primary" id="btn-confirm" name="fdts" type="submit">CONFIRMATION</button> <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="mi-modal"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">CONFIRMEZ</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" id="modal-btn-no"><span style="font-size: 50px" class="glyphicon glyphicon-remove-circle">Cancel</button> <form class="form-signin" id="login_envoi" method="get" action="."> <!--{% csrf_token %}--> <input type="text" name="fdts" value = "@name_id" > <button class="btn btn-success btn-lg" type="submit"><span style="font-size: 74px" class="glyphicon glyphicon-send"> <BR> SEND </button> </form> </div> </div> </div> </div> <script> var modalConfirm = function(callback){ $("#btn-confirm").on("click", function(){ $("#mi-modal").modal('show'); }); $("#modal-btn-no").on("click", function(){ callback(false); $("#mi-modal").modal('hide'); }); $("#login_envoi").on("click", function(){ callback(true); $("#mi-modal").modal('hide'); }); </script> {% endblock %} -
Working with Django's save_model function
I'm using the example code from Django's site on editing the admin site and I keep getting an error returned when I save it. super(type, obj): obj must be an instance or subtype of type Here's my admin.py file: from django.contrib import admin from .models import Brand, JobType, Job admin.site.register(Brand) admin.site.register(JobType) class JobAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): # obj.user = request.user super().save_model(request, obj, form, change) admin.site.register(Job, JobAdmin) I've hidden the variable change under there and just want this custom save model to work first. It wasn't working well with my model so I wanted to start by getting it working in the most minimal way. -
Marking only a part of string as safe
I want to show user's profile link in comment, i.e u/ali should look like a link to user's profile. but I also don't want to risk marking whole comment as safe because it will make site vulnerable to html injection so my question is this: how to mark safe only a part of a string, instead of marking the whole comment as save? This is the templatetags code: @register.filter(name='mentioned_profiles') def mentioned_profiles(comment): words = comment.split(" ") for word in words: if word[:2]=="u/": u = word[2:] try: user = User.objects.get(username=u) new_word = """<a href="http://127.0.0.1:8000/u/{}"> {}</a>""".format(user.username,user.username) new_word = mark_safe(new_word) comment = comment.replace(word,new_word) except: pass return comment Currently, it shows the whole string, without showing the link. -
Gettings items created by related users
I have model like this: COMPANY_ADMIN = 'company_admin' MANAGER = 'manager' EMPLOYEE = 'employee' ROLE_CHOICES = ( (COMPANY_ADMIN, 'Admin'), (MANAGER, 'Manager'), (EMPLOYEE, 'Employee'), ) class User(models.Model): name = models.CharField(...) role = models.CharField(choices=ROLE_CHOICES, ...) created_by = models.ForeignKey('self', related_name='created_by_user', null=True, blank=True) class Item(models.Model): name = models.CharField(...) user = models.ForeignKey(User) company_admin = User.objects.get(pk=1, name='admin') manager = User.objects.create(created_by=company_admin, name='manager1', role=MANAGER) employee = User.objects.create(created_by=manager, name='employee_12', role=EMPLOYEE) item = Item.objects.create(user=employee, name='test') item1 = Item.objects.create(user=manager, name='test1') I'm log in as company_admin: items = Item.objects.filter(user=request.user) How can I get all items created by logged in user and his sub accounts? -
Wrapper error in Django Zappa deployment
I am trying to deploy my Django application using Zappa. I am using python 3.6 (although, I also have python 2.7 installed on my MacBook; never used it). Everything goes smoothly with the deployment except when I go to the url, I get this error. "{'message': 'An uncaught exception happened while servicing this request. You can investigate this with the zappa tail command.', 'traceback': ['Traceback (most recent call last):\n', ' File \"/var/task/handler.py\", line 452, in handler\n response = Response.from_app(self.wsgi_app, environ)\n', ' File \"/var/task/werkzeug/wrappers.py\", line 903, in from_app\n return cls(*_run_wsgi_app(app, environ, buffered))\n', ' File \"/var/task/werkzeug/wrappers.py\", line 57, in _run_wsgi_app\n return _run_wsgi_app(*args)\n', ' File \"/var/task/werkzeug/test.py\", line 884, in run_wsgi_app\n app_rv = app(environ, start_response)\n', \"TypeError: 'NoneType' object is not callable\n\"]}" When I use the tail command, I get the following error. [1522350439826] 'NoneType' object is not callable [1522350561286] [DEBUG] 2018-03-29T19:09:21.282Z afbf4f1c-3384-11e8-8a03-a1095dcd99f5 Zappa Event: {'time': '2018-03-29T19:09:19Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '753712688736', 'region': 'us-east-1', 'detail': {}, 'version': '0', 'resources': ['arn:aws:events:us-east-1:753712688736:rule/r-suri-production-zappa-keep-warm-handler.keep_warm_callback'], 'id': 'f15a5fd5-aaf9-dfb7-1553-d14bb33d1b2b', 'kwargs': {}} [1522350561286] [DEBUG] 2018-03-29T19:09:21.282Z afbf4f1c-3384-11e8-8a03-a1095dcd99f5 Zappa Event: {} I have tried resetting my virtual env and requirements.txt from the scratch, but no help. This is what my Zappa settings file looks like { "production": { "aws_region": "us-east-1", "django_settings": "r_suri.settings", "profile_name": … -
How cursor selects a database in django
I have a question for cursor in python, if I have more than one database in my settings, I want to open a cursor in a function that will export data for an excel with openpyxl. My question is how my cursor will know which database to connect and how it does it. Thanks in advance DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'default', 'USER': 'postgres', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'test1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test1', 'USER': 'postgres', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': '5433', }, 'test2': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test2', 'USER': 'postgres', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Wagtail multisite setup
My Wagtail project will have two sites: www.mysite.com - the main/marketing site members.mysite.com - the membership site for subscribers In Wagtail, I see how to setup the different sites under Settings -> Sites, but here are the areas where I'm getting stuck: The home page for the membership site has different requirements than the main site. Is it recommended to have the usual "HomePage" Page model for the main site and then a "MembersHomePage" Page model for the membership site? I'm using a StandardPage model (as seen on the Bakery Demo) for the main site for Privacy, About, Terms, etc. Both sites could share these page models, but they need to use different templates when rendered - would I need to use the RoutablePageMixin to accomplish this? Or is it recommended to create a separate "MembersStandardPage" Page model instead? The membership site will have some regular Django models, but how do I specify the Wagtail SiteID they belong to using a Foreign Key relationship? Or, do I need to make use of the Django "Sites" framework? Project layout. This may be more of a general Django question, but I'm not totally sure, so... The sites will have different designs. Rather … -
django test, long running process fails because item in dbase no longer exists
I have a pretty simple django rest API where clients POST some data which gets placed into a dbase. Once the data is written into the dbase, a long-running process is spawned that access another external API. The incoming request is then returned. Once the long-running process returns with results from the external API, it updates the dbase entry with the id that was saved from the initial write. However, when I use the ./manage.py test, this access fails because the item does not exist in the dbase! It works fine in normal server run mode. The id looks as I'd expect it to. But looking at the dbase, there's no entry from the test. Here's a graphic to help visualize. The long-running process is using rq-worker which I start as follows in a different window: ./manage.py rqworker default I'm using the "--keepdb" flag and having the tests use the SAME dbase as the typical run mode (no separate test dbase.) ./manage.py test --keepdb DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabasename', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', 'TEST': { 'NAME' : 'mydatabasename' } } } The data is saved in Step 2 (see graphic) but the … -
Django & Graphene: How to handle bidirectional relationship with polmorphic models?
I have a Django model that looks like this (simplified of course): from django.db import models from polymorphic.models import PolymorphicModel class Tournament(models.Model): slug = models.CharField(max_length=100, unique=True) class Event(PolymorphicModel): tournament = models.ForeignKey(Tournament, related_name='events') slug = models.CharField(max_length=100) class PracticeEvent(Event): pass class MatchEvent(Event): winner = models.CharField(max_length=100, null=True, blank=True, default=None) Tournaments consist of two kinds of events: practice events, and matches. I'd like to expose this model using GraphQL, using Graphene. This is what I have come up with: import graphene from graphene_django import DjangoObjectType from . import models class TournamentType(DjangoObjectType): class Meta: model = models.Tournament exclude_fields = ('id',) class EventType(graphene.Interface): tournament = graphene.Field(TournamentType, required=True) slug = graphene.String(required=True) class PracticeEventType(DjangoObjectType): class Meta: model = models.PracticeEvent interfaces = (EventType,) exclude_fields = ('id',) class MatchEventType(DjangoObjectType): class Meta: model = models.MatchEvent interfaces = (EventType,) exclude_fields = ('id',) extra_types = {PracticeEventType, MatchEventType} class Query(graphene.ObjectType): tournaments = graphene.List(TournamentType) events = graphene.List(EventType) # ... resolvers ... schema = graphene.Schema( query=Query, types=schema_joust.extra_types,) So far, so good; I can query events { ... } directly, and even the tournament is available. However, as there is no DjangoObjectType with model = models.Event, I can't query tournaments { events {...} }... How can I fix this? I can't make EventType a DjangoObjectTpe, and I … -
Django Social Auth--I Can't Reset Password for User That Signed Up Via Facebook
I'm having a really odd issue that I'm having trouble figuring out. On my site, I have an option for a user to register via either a normal signup page or via Facebook social auth --I'm using the Social Auth App for Python/Django. A user can successfully register either way. If a user registers by the normal signup method and enters username and email and password---they are able to successfully trigger a password reset if desired via a password reset page. BUT, if a user signs up via Facebook AUTH, after their user profile is created, if they go to enter their email for a password reset, no EMAIL is generated. Here are my settings in settings.py for the auth apps. AUTH_USER_MODEL = "accounts.User" SOCIAL_AUTH_USER_MODEL = 'accounts.User' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } SOCIAL_AUTH_SLUGIFY_USERNAMES = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) As you can see i'm slugifying the username, so all fields are populated. Here is my User model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."}) username = models.CharField(max_length=40, default='') first_name = models.CharField(max_length=40, default='', blank=True) last_name = models.CharField(max_length=40, … -
django-smart-select not populating secondary dropdown
I trying to use django-smart-select to have a user select a state in the first dropdown and have the secondary dropdown populate with all Metro Statistical Area(CBSAs) within that state. Currently, when I select a state no options populate. However, if I give specify show_all=True in the ChainedForeignKey, it will populate with the options (only a few test options below). My question is why wont the show_all=False update my MSA(CBSA) dropdown to only show chained records? I have inspected the page in chrome when running the development server and no JS errors are present. My code is below. models.py class State(models.Model): id = models.AutoField( state_name = models.CharField( _('State Name'), max_length = 46, blank = True, null = True, ) def __str__(self): return u'%s' % (self.state_name) class CBSA(models.Model): id = models.AutoField( primary_key = True ) cbsa_title = models.CharField( _('CBSA Title'), max_length = 46, blank = True, null = True, ) def __str__(self): return u'%s' % (self.cbsa_name) # CBSA/State Connection Table. CBSA's can span several states class CBSAState(models.Model): id = models.AutoField( primary_key = True ) state = models.ForeignKey( State, verbose_name=_('State'), on_delete=models.CASCADE, null = True, blank = True, ) cbsa = models.ForeignKey( CBSA, verbose_name=_('CBSA'), on_delete=models.CASCADE, null = True, blank = True, ) def … -
How to properly deploy django channels on windows?
I need to design a Django based project with WebSockets on Windows server. It seems like Django Channels is the most elegant and pythonic way to do such thing. However I have issue with finding a proper way to deploy Channels and/or Daphne on Windows. It's suggested to use a process supervisor but all solutions I found so far are on Linux environment. What is the most proper way to deploy Daphne on Windows? Or maybe I should use something else than Daphne to deploy Channels on Windows? -
Django - One query to get M2M objects
Entry model and Reference have M2M relationship class Entry(models.Model): description = models.TextField(blank=True, null=True) references = models.ManyToManyField(Reference, blank=True) class Reference(models.Model): name = models.CharField(max_length=1000, blank=True, null=True) title = models.CharField(max_length=1000, blank=True, null=True) I need to iterate over the entries and get a field from Entry. Also for each entry, I need to iterate over its references, and get data from each reference. Prefetch related is not caching all the reference data. For each entry, I am hitting the db again when I call entry.references.all(), and the performance is terrible (I have 100k entries, and 500k references). How can I get all the data in one database call? qs = Entry.objects.prefetch_related('references').all() for entry in qs: # do something with entry for ref in entry.references.all(): # do something with ref -
When calling delete(), I get 'models aren't loaded yet' error in Django 2.0.3
I have two models defined in an app called coins. models.py from django.db import models class Coin(models.Model): model defintions class CoinData(models.Model): model defintions I have a function which can write data to my Coin model using a for loop (this is inside models.py) models.py for each_item in list: each_item = Coin(name=each_item) This works fine, but each time I write to the model, it's creating an additional instance even if one already exists. While I refine my code, I simply want to delete all instances in Coin.The list is 1500+ so I cannot delete from Admin (which does work, but produces an error if I try to delete all at once). So I run many variations of the delete() function on the objects in Coins: Coin.objects.all().delete() Or for x in Coin.objects.all() x.delete() It's only when I call delete() that I get the error File "C:\Anaconda\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Anaconda\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Anaconda\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Anaconda\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Anaconda\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Cannot hide "Save and add another" button in Django Admin
I would like to hide all the "Save" buttons in Django's Admin's Change Form, for a specific model, when certain conditions are met. Therefore, I override the changeform_view method in the relevant ModelAdmin, like so: def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} obj = collection_management_MammalianLine.objects.get(pk=object_id) if obj: if not (request.user.is_superuser or request.user.groups.filter(name='Lab manager').exists() or request.user == obj.created_by): extra_context['show_save'] = False extra_context['show_save_and_continue'] = False extra_context['show_save_and_add_another'] = False else: pass else: pass return super(MammalianLinePage, self).changeform_view(request, object_id, extra_context=extra_context) With this code, I can successfully hide the "Save" and "Save and continue" buttons, but not the "Save and add another" one. I can see that submit_line.html contains the following three lines {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %} My question is: why can I hide the "Save" and "Save and continue" buttons, but not the "Save and add another" one? Even though the relevant templatetag (show_save_and_continue) is in the template. -
How do i get UserCreationForm data displayed in the django admin and on my template?
I have a django app that extends the user model to include more fields that collect data about a new user, so far i have managed to get the form to work properly and render the fields on a template correctly, on adding i'm also trying to add the new user to a group called agents, which i have somehow achieved to do but on adding the new user to the agents user group i run into a problem on the templates where i want to display all the new user information as stored in the database, the usual django user fields e.g email ,name are accessible but the additional form fields i created are not displayed. below is my code forms.py class MyRegistrationForm(UserCreationForm): COUNTIES = (('Baringo','Baringo'), ('Bomet','Bomet'), ('Bungoma', 'Bungoma'), ) first_name = forms.CharField(required = False) last_name = forms.CharField(required = False) photo = forms.ImageField() email = forms.EmailField(required = True) phone = forms.CharField(max_length=30) company = forms.CharField(max_length=150) county = forms.ChoiceField(choices=COUNTIES) city = forms.CharField(required = True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2') def clean_email(self): # Get the email email = self.cleaned_data.get('email') # Check to see if any users already exist with this email as a username. try: match … -
Creating a dictionary-like website with django
Well, I'm a bit new to programming and I want to work with Django. Believe me I've searched for this questions for so long before asking it but I couldn't find an answer. So here it is. I want to create a dictionary-like website.I want my users to be able to click on a word and see the translation of it in a tooltip. To achieve this I'm trying grab the clicked item and seach for it in my database. But should I try this with AJAX and should I try it through javascript or can I do it with python as well.Or is it even possible? If yes, can anyone help me with it. Any article or video etc. will be of great help. -
Overriding addition is-valid, is-invalid css class to form instance behaviour
I'm creating form with data from GET request and send it back in response. On my page i customized field visualization (green for valid field, red for invalid respectively) depending on '.is-valid' or '.is-invalid' css class which is added at the time i populate form. and i use this template in different scenarios and in some i don't want it to be colored. So my goal is to send form object from view without addition extra css class. Changing template isn't suitable in my case. -
Django-Filter: {{ field.value }} is Empty when rendering form fields
I'm using the Django-Filter library !important. For tags, I'm using Django-taggit. I built the following filter.py: class TaskFilter(django_filters.FilterSet): """Filter for books by author""" tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common()) class Meta: model = Task fields = ['tags'] However, when I pass this filter to the template, it doesn't render the tags properly. In particular {{ field.value }} is empty. Let's look at the following cases: CASE 1. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} <label for="{{ field.id_for_label }}"></label> {{ field.value }} {% endfor %} # out <label for="id_tags_0"></label> <label for="id_tags_1"></label> <label for="id_tags_2"></label> CASE 2. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} <label for="{{ field.id_for_label }}"></label> {{ field }} {% endfor %} # out <label for="id_tags_0"></label> <label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label> <label for="id_tags_1"></label> <label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label> <label for="id_tags_2"></label> <label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label> CASE 3. # template.html {{ filter.form.tags.errors }} {% for field in filter.form.tags %} {{ field }} {{ field.label_tag }} {% endfor %} #out <label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label> <label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label> <label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label> I'm trying to understand why this happens. Why can't I … -
Django 1.11 from request.POST to models
is there anyway I can pass my request.post data to django models in admin panel? My models.py class Source(models.Model): def __str__(self): return self.name + '({}...)'.format(self.url[:20]) url = models.URLField() name = models.CharField(max_length=250, verbose_name='Source_name') timestamp = models.DateTimeField(auto_now_add=True) currency = models.ForeignKey(Currency) my admin.py @admin.register(Source) class SourceAdmin(admin.ModelAdmin): list_display = ['id', 'url', 'name', 'currency'] list_editable = ['url', 'name', 'currency'] def save_model(self, request, obj, form, change): #pseudo code below if request.method == 'POST': variable_1 = request.POST['url'] variable_3 = request.POST['name'] variable_4 = request.POST['currency'] super().save_model(...) or may be I could do a custom view and just save it from there with object.create ? -
Join Django/Python list by commas then slugify each element
From a Python list: categories = ["category 1", "category 2", "category 3"] I want to generate a javascript array of category slugs like this: var categories = ["category-1", "category-2", "category-3"]; I've tried both these, but it's yielding very inaccurate results: var categories = ["{{ categories|join:'", "'|slugify }}"]; var categories = ["{{ categories|slugify|join:'", "' }}"]; So I guess my problem is not only the order of these filters, seems like I need to do something else but I don't know what I'm looking for exactly. NOTE: I know how to do it in a loop, but I was hoping there's a one-liner for this. -
Prepopulate dropdown in all combination in django inline admin
I've a TabularInline in django admin, with 2 dropdown choices independent of each other. I want to prepopulate each row with one unique value of each dropdown box, and create all the extra rows. My admin for the inline looks like class AssesmentComboAdmin(admin.TabularInline): model = AssesmentCombo form = AssesmentComboForm fields = ('topic','skill','assesment','remarks','attachment',) exclude = ['createdBy'] verbose_name='Evaluation' verbose_name_plural='Evaluations' formfield_overrides = {models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':40})},models.DateField:{'widget':AdminDateWidget()}} list_filter = ('topic',) extra = 50 The fields topic and skill are the dropdown boxes with various values.