Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A form with filtering
I'm trying to set some filtering for a query through a form but I don't really know how to build it. So I want to filter by "recruitment", "game" and/or "platforme". The problem is that I don't really know how to build it in my views.py. template.html <form method="POST"> {% csrf_token %} <select name="recruitment" onchange=this.form.submit();> <option disabled {%if form.recruitment == Null%}selected{%endif%}>Recrutement</option> <option value="all" {%if form.recruitment == "all"%}selected{%endif%}>Tout</option> <option value="open" {%if form.recruitment == "open"%}selected{%endif%}>Ouvert</option> <option value="close" {%if form.recruitment == "close"%}selected{%endif%}>Fermé</option> </select> <select name="plateform" onchange=this.form.submit();> <option disabled {%if form.plateform == Null%}selected{%endif%}>Plateforme</option> <option value="all" {%if form.plateform == "all"%}selected{%endif%}>Toutes</option> {%for plateform in plateform%} <option value="{{plateform.guid}}" {%if form.plateform == plateform.guid%}selected{%endif%}>{{plateform.name}}</option> {%endfor%} </select> <select name="game" onchange=this.form.submit();> <option disabled {%if form.game == Null%}selected{%endif%}>Jeu</option> <option value="all" {%if form.game == "all"%}selected{%endif%}>Tous</option> {%for game in game%} <option value="{{game.guid}}" {%if form.game == game.guid%}selected{%endif%}>{{game.title}}</option> {%endfor%} </select> </form> views.py def view_watch_teams(request): media = settings.MEDIA try: myteam = Team.objects.get(owner=request.user) except: pass team = Team.objects.all() game = Games.objects.all() plateform = Plateform.objects.all() if request.POST: form = request.POST My query should be something like this : result = Relation.objects.filter(recruitment=form['recruitment'], on_game=form['game'], on_plateform=form['plateform']) This kind of query only work if all filters are set. So, what is the correct synthax to make a query more dynamic ? Thank you … -
How to get image from input field using jquery
I am trying to send image from an html page to django view. But I am not able to attain the data. The following is my code. <input type="file" id = "imageupload" onchange = "sendimg()" /> <script> var sendimg = function(){ var img = document.getElementById("imageupload") $.ajax({ type: "POST", url: "/test/", data: { "imgfile": img, }, processData: false, contentType: false, success: function(data){ console.log("success"); console.log(data); }, failure: function(data){ console.log("failure"); console.log(data); }, });} </script> The django view is @csrf_exempt def testimg(request): print "the request",request.POST data = {"data": "ok" } return JsonResponse(data) The print statement gives the request <QueryDict: {}> What am I doing wrong ? -
Django-tenant-schemas and GeoDjango together
I want to use django-tenant-schemas and GeoDjango (postgis) in my Django project. I've a single default database. But both django-tenant-schemas and GeoDjango want me to set a custom Engine for the Database in the settings. django-tenant-schemas want it to be set to tenant_schemas.postgresql_backend while GeoDjango wants it to be set to django.contrib.gis.db.backends.postgis. Is there any work around to this issue? -
How to show django ImageField in browser URL
I have a webscraping app that downloads images from a website and stores it in an ImageField of one of my models. models.py class Article(models.Model): title = models.CharField('Title', max_length=300) url = models.CharField('URL', max_length=200) hero_image = models.ImageField(upload_to='pictures', max_length=255) My hero_image field looks like this in my project: "http://localhost:8000/media/pictures/gettyimages-585288019.jpgw210h158crop1quality85stripall" And the images are stored at myproject/myproject/pictures: myproject ├── myproject │ ├── settings.py ├── pictures ├── manage.py When I click the sample link above I automatically download the image, but instead I would like to show the image in the browser. What I've done so far myproject/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('core.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_URL = '/media/' There are a lot of topics similar to my question on SO but I've read a bunch of them and still can't find one that seems to help me solve my problem. -
Service Worker does not fire upon fetch and return cached data
I am using service workers in one of my projects. On call, my service worker gets successfully registered and it caches all provided URLS. But when I reload my page, all cached data is either picked from disk cache or memory cache and not from service worker. I refered this question Service worker is caching files but fetch event is never fired and cross checked that there is not a problem with scoping. service-worker.js var CACHE_NAME = 'home-screen-cache'; var urlsToCache = [ '/static/client-view/fonts/fontawesome-webfont.eot', '/static/client-view/fonts/fontawesome-webfont.woff', '/static/client-view/fonts/fontawesome-webfont.ttf', '/static/client-view/fonts/fontawesome-webfont.svg', '/static/css/cricket.css', '/static/client-view/js/jquery.mobile.custom.min.js', '/static/client-view/js/jquery-2.1.4.min.js', '/static/js/cricket_matches.js' ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { console.log("Found in cache"); return response; } console.log("Not found in cache"); return fetch(event.request); } ) ); }); service-worker registration script if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('{% static 'service-worker.js' %}').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); }); } If you need any kind of additional data, mention in comments. Please help. -
django: update database upon onsubmit dropdown
I am trying to create a ticketing system. What I want to do is when I change the Status dropdown list it should update the status of the ticket in the database. Also, I would like to update and view in the same page. Any insights if that would be possible? forms.py class ViewForm(forms.Form): statuses = [ ('In Progress', 'In Progress'), ('On Hold', 'On Hold'), ('Done', 'Done'), ('ForQA', 'ForQA'), ('QAPassed', 'QAPassed'), ('QARevs', 'QARevs'), ] status = forms.ChoiceField(label='Status', required=True, choices=statuses, widget=forms.Select(attrs={'onchange': 'actionform.submit();'})) views.py def view_sheet(request, project_id): project = Project.objects.get(pk=project_id) tickets = Ticket.objects.filter(project=project_id) form = ViewForm() context = { 'project': project, 'tickets': tickets, 'form': form, } return render(request, 'project/sheet/view.html', context) view.html <div class="tracker-sheet"> <div class="project-name"> <h1>{{project.name}}</h1> </div> <div class="actions"> <a href="{% url 'add_ticket' project.id %}"> <button type="submit">New Ticket</button> </a> </div > <div class="tracker-table"> <table> <tr> <th>Total Worked</th> <th>Status</th> <th>Status Date</th> <th>Received</th> <th>Due Date</th> <th>Agent</th> <th>Sub Type</th> <th>CID</th> <th>Link</th> <th>Task Description</th> <th>Server</th> <th>Qty</th> <th>Info</th> </tr> {% for ticket in tickets %} <tr> <td><span class="table-constant"></span></td> {% for field in form %} <td>{{field}}</td> <!-- Status dropdown list --> {% endfor %} <td><span class="table-constant">{{ticket.status_date}}</span></td> </form> <td><span class="table-constant">{{ticket.received}}</span></td> <td><span class="table-constant">{{ticket.due_date}}</span></td> <td><span class="table-constant"></span></td> <td><span class="table-constant">{{ticket.sub_type}}</span></td> <td><span class="table-vary"></span></td> <td><span class="table-constant">{{ticket.link}}</span></td> <td><input type="submit" value="{{ticket.task_description}}"</td> <td><span class="table-constant"></span></td> <td><span class="table-constant">{{ticket.qty}}</span></td> <td></td> </tr> … -
Django rest framework not work with regex validator
In my model I have a field address = models.CharField(_('address'), blank=True, max_length=42, editable=False, validators=[validators.RegexValidator(regex='^0x[a-fA-F0-9]{40}$')]) But when I tried to apply value more then 42 symbols, I get django error: value too long for type character varying(42) When I set value: test for example, it passes validation(but shouldn't) My serializer is simple: class KYCSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' -
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
how to solve this error " Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) " . It appears when i run my engine.py . Could you give me a help? -
Django query: how to apply the mode calculation in the query?
In a previous question I was asking about how to do a complex query in Django. Here is my example model: class Foo(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=100, blank=True) foo_value = models.CharField(max_length=14, blank=True) time_event = models.DateTimeField(blank=True) # ... and many many other fields Now in my previous question @BearBrown answered me with using the When .. then expression to control my query. Now I need something more. I need to calculate the mode (most repeated value) of the quarter of the month in the time_event field. Manually, I do it like this: - I manually iterate over all records for the same user. - Get the day using q['event_time'].day - Define quarters using quarts = range(1, 31, 7) - Then, append the calculated quarters to a list month_quarts.append(quarter if quarter <= 4 else 4) - Then get the mode value for this specific user qm = mode(month_quarts) Is there a way to automate this mode calculation function in the When .. then expression instead of manually iterating through all records for every user and calculating it? -
How to access extra data sent with POST request in Django Rest Framework serializer
I'm trying to send an extra array with a POST request that creates a group. POST /groups/ { "name": “New Group“, "users_to_invite": [ 1, 2, 6 ] } I'm using Django Rest Framework's ListCreateAPIView to handle the request: class GroupListView(ListCreateAPIView): queryset = Group.objects.all() def get_serializer(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() # Use a dedicated serializer to inspect the field with users to invite if self.request.method == 'POST': return GroupCreateSerializer(*args, **kwargs) return GroupSerializer(*args, **kwargs) I want to get to the contents of the users_to_invite array in a serializer to create invitation objects. However, I'm unable to do so because somehow the array is not there when I'm accessing it in the serializer. class GroupCreateSerializer(ModelSerializer): def create(self, validated_data): # Get user ids to invite # !! It fails here !! invitations_data = validated_data.pop('users_to_invite') # TODO: Iterate over ids and create invitations # Create a group group = Group.objects.create(**validated_data) return group class Meta: model = Group fields = ('id', 'name', ) Array is not there so naturally I'm getting the error: File "...my_api/serializers.py", line 303, in create invitations_data = validated_data.pop('users_to_invite') KeyError: 'users_to_invite' How can I make the array to appear there? Modifying the model does not sound like a good idea because I … -
Deploy Django application on Websphere application Server
I am trying to figure out if Django applications can be deployed to Websphere Application Server. I could not find any relevant results on google, i am not sure ifthat is even possible. Has anyone done this or know a method how to do this. I am very much confused now. -
How Celery executes tasks
In my project I have a Celery task that is sent by the Celery beat to the worker every 30 seconds.I am interested in knowing how celery executes the celery tasks? Whether it spawns a new thread for each task or a new worker for the task.How can we know if a task completes and is removed from the message broker queue for which I am using RabbitMQ. -
Django global name 'request' is not defined
I need in my function user current user Object. When I'm writting for example user = request.user I'm getting: global name 'request' is not defined What Am I doing wrong? -
django cannot assign "": must be a "" instance
I have an ecommerce application which I exteded the user account to serve the Order input and everything seems fine till I submitted an order which gave me the error in my browser Cannot assign "<Account: Account for Chris>": "OrderItem.order" must be a "Order" instance. below is my code Model class Order(BaseOrderInfo): # each individual status SUBMITTED = 1 PROCESSED = 2 SHIPPED = 3 CANCELLED = 4 user = models.ForeignKey(Account, related_name='user_account') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) coupon = models.ForeignKey(Coupon, related_name='orders',null=True,blank=True) discount = models.IntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) ORDER_STATUSES = ((SUBMITTED,'Submitted'), (PROCESSED,'Processed'),(SHIPPED,'Shipped'), (CANCELLED,'Cancelled'),) status = models.IntegerField(choices=ORDER_STATUSES, default=SUBMITTED) ip_address = models.GenericIPAddressField() transaction_id = models.CharField(max_length=20) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items') product = models.ForeignKey(Product,related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) account Models.py class BaseOrderInfo(models.Model): class Meta: abstract = True phone = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=250) state = models.CharField(max_length=50) postal_code = models.CharField(max_length=10) class Account(BaseOrderInfo): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') and my view is def order_create(request): cart = Cart(request) account = load_account(request.user) if request.method == 'POST': form = AccountEditForm(instance = account, data = request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'],price=item['price'], quantity=item['quantity']) cart.clear() return render(request,'order/created.html', {'order': order}) else: form = AccountEditForm(instance = account) return render(request, 'order/create.html',{'cart': … -
Django can't click the button
this is jquery {% block custom_js %} <script> $(function() { $('#jsStayBtn').on('click',function(){ $.ajax({ cache: false, type: 'POST', url: {% url 'org:add_ask' %}, data: $('#jsStayForm').serialize(), async:true, success: function(data) { console.log(data) alert(data) if(data.status == 'success') { $('#jsStayForm')[0].reset(); alert('successful') } else if(data.status == 'fail') { $('#jsCompanyTips').html(data.msg) } }, }) }); }); </script> {% endblock %} this is submit html <div class="right companyright"> <div class="head">Studing</div> <form class="rightform" id="jsStayForm"> <div> <img src="{% static 'images/rightform1.png' %}"/> <input type="text" name="name" id="companyName" placeholder="name" maxlength="25" /> </div> <div> <img src="{% static 'images/rightform2.png' %}"/> <input type="text" name="mobile" id="companyMobile" placeholder="mobile"/> </div> <div> <img src="{% static 'images/rightform3.png' %}"/> <input type="text" name="course_name" id="companyAddress" placeholder="course_name" maxlength="50" /> </div> <p class="error company-tips" id="jsCompanyTips"></p> <input class="btn" type="text" id="jsStayBtn" value="consult >" /> {% csrf_token %} </form> </div> this is urls urlpatterns = [ # 课程机构列表页 url('^list/$', OrgView.as_view(), name="org_list"), url('^add_ask/$',AddUserAskView.as_view(), name='add_ask'), ] There is an input box on the page, which is ajax and is implemented through jquery.But when I'm done, I don't have any reaction to the click of the button, I don't know what went wrong.This should be a POST request,How should I modify the normal submission? -
Consume messages from django
Is it possible to consume messages from rabbitmq using celery in django? Messages are being sent from a different non-django app import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery("test") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.task_routes = { 'task.send_emails':{ 'queue': 'sendmail', 'exchange': 'sendmail', 'routing_key': 'sendmail' } } app.config_from_object('django.conf:settings') -
Django Query - Multiple Inner Joins
we currently have some issues with building complex Q-object queries with multiple inner joins with django. The model we want to get (called 'main' in the example) is referenced by another model with a foreign key. The back-reference is called 'related' in the example below. There are many objects of the second model that all refer to the same 'main' object all having ids and values. We want to get all 'main' objects for wich a related object with id 7113 exists that has the value 1 AND a related object with id 7114 that has the value 0 exists. This is our current query: (Q(related__id=u'7313') & Q(related__value=1)) & (Q(related__id=u'7314') & Q(related__value=0)) This code evaluates to FROM `prefix_main` INNER JOIN `prefix_related` [...] WHERE (`prefix_related`.`id` = 7313 AND `prefix_related`.`value` = 1 AND `prefix_related`.`id` = 7314 AND `prefix_related`.`value` = 0) What we would need is quite different: FROM `prefix_main` INNER JOIN `prefix_related` a INNER JOIN `prefix_related` b [...] WHERE (a.`id` = 7313 AND a.`value` = 1 AND b.`id` = 7314 AND b.`value` = 0) How can I rewrite the ORM query to use two INNER JOINS / use different related instances for the q-objects? Thanks in advance. -
Database design for a shop/warehouses chains (and inventory)
I'm developing a web application (in Django) for managing a group of shoes shops (and linked warehouses). In the database I have a table of Shoes (a row for every kind), then a table of Instances (that is; a foreign key to a model of shoes, size and colours). Now, I also have a table for shops and warehouse, but now I have to design how to represent the state of the inventory for every shop\warehouse (how many items for every place). Which is the best design I should adopt? In a OO world, every Place (Shop or Warehouse) object would have a data structure or something for managing the quantity for every item, but I don't think this is a good way for a database. -
How to have django-oscar alongside other apps?
I am trying to add a django-oscar shop to an existing django website. My problem is that the templates of the two are somehow clashing, such that I can either see the existing website, or the shop, but not both. Here is the overarching urls.py: from django.conf.urls import include, url from django.contrib import admin from oscar.app import application urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('main.urls')), # oscar url(r'^shop/', include(application.urls)), ] And in the settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # os.path.join(BASE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR ], # 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', 'main.context_processors.google_analytics' ], 'loaders': [ 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ], }, }, ] If I switch the order of the loaders, either the original website (in app 'main'), or the Oscar shop, can no longer be accessed/viewed. So I'm not sure what esoteric detail I'm overlooking, and the docs don't cover this. Cheers. -
Django filter DateTimeField by TimeField value
I have a Timeslot model with start and end fields of type DateTimeField. Another class Constraint also has start and end fields but of type TimeField. I can filter Constraint objects by the start and end values of a given timeslot: Constraint.objects.filter(start=timeslot.start) But now I am in need of filtering Timeslot based on the value of a given constraint. The scenario is having multiple timeslots that define different datetime ranges throughout a time domain, and I want to select those outside a given time range specified by an existing constraint: Timeslot.object.filter(Q(end__lte=constraint.start) | Q(start__gte=constranit.end)) For example, let's say I have timeslots going through October 23rd to October 29th, each day starting at 10am and ending at 1pm. The duration would be of 1 hour, so each day would have 3 timeslots, which totals in 21 timeslots. 23 Oct, 10am-1pm (3 timeslots) 24 Oct, 10am-1pm (3 timeslots) 25 Oct, 10am-1pm (3 timeslots) 26 Oct, 10am-1pm (3 timeslots) 27 Oct, 10am-1pm (3 timeslots) 28 Oct, 10am-1pm (3 timeslots) 29 Oct, 10am-1pm (3 timeslots) And a constraint that defines the range 11am-12pm. I would like to select the timeslots outside that range. The result would be the timeslots between 10am and 11am, and those … -
Issue with DataTable.ajax.reload and stored procedure
Hi I have trouble using Datatable.reload.ajax with my stored procedure. View (index): def index(request): listOPT = [] Data = [] Req = TbMouvementinit.objects.exclude(dateheureclot=u'') data = getDataQuery(Req) django = json.dumps(data) cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") Req = dictfetchall(cursor) sql = json.dumps(Req) finally: cursor.close() fluxState = settings.FLUX_MANAGER_STATE if fluxState != True: listOPT.append('FLUX AXEREAL : OFF') else: listOPT.append('NULL') cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = dictfetchall(cursor) finally: cursor.close() return render(request, 'index.html', locals()) View (listMVTInit) : def listMVTinit(request): #Req = TbMouvementinit.objects.exclude(dateheureclot=u'') #data = getDataQuery(Req) #return HttpResponse(json.dumps(data), content_type = "application/json") cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") Req = dictfetchall(cursor) finally: cursor.close() return HttpResponse(json.dumps(Req), content_type = "application/json") Template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Liste Mouvement initiaux</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="../static\css/Gestion_Mouvements.css" rel="stylesheet"> <link href="../static\css/index.css" rel="stylesheet"> <link href="{% static 'css/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css" rel="stylesheet' %}" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min.js' %}"></script> <script src="{% static 'js/jquery-ui.min.js' %}"></script> <script> $(document).ready(function() { table = $('#indexTab').DataTable({ ajax: "{% url 'listMVTinit' %}", }); }); setInterval(function(){table.ajax.reload();}, 2000); </script> </head> <body> <div id="wb_Shape1" style="position:absolute;left:4px;top:5px;width:1300px;height:100px;z-index:0;"> <img src="../static\images/img0001.png" id="Shape1" alt="" … -
Xml request django use zeep library
Sorry for my english. Before i didnt work whith xml and for me it something new. I have soap api, and i need get some data frome this xml api. Now i try create test request and print something. I user zeep library for my project. I write python -mzeep 'my link' and i have some instruction. Example: ns0:AccountInfo(number: xsd:string, secret: xsd:string, country: xsd:string, language: xsd:string, behalfOf: xsd:string) getVersionInfo(accountInfo: ns0:AccountInfo) -> responseStatus: ns0:ResponseStatus, data: {country: xsd:string, build: xsd:string, date: xsd:dateTime, licensed: xsd:boolean}[] Then i write code in pythone: class Test(View): def get(self, request, *args, **kwargs): client = Client("link") account = client.get_type("ns0:AccountInfo") account_info = account(number="111111", secret="123123123123", country="ua", language="en") response = client.service.getVersionInfo(accountInfo=account_info) print(response) return HttpResponse('Hello, World!') But i have error: Exception Value: A request was found for which no data versions could be retrieved. -
How to write this query in django queryset? Find all topic_name for gaurd name = Algebra?
Defined Models Are... Gaurd(name, category) Chapter(Gaurd, Chapter, rates) and Topic(chapter, topic_name, level) These three are connected via foreign key with each other. -
django-filter and DRF: AND clause in a lookupfield
This question expands on this one. Suppose my models are class Car(models.Model): images = models.ManyToManyField(Image) class Image(models.Model): path = models.CharField() type = models.CharField() and my filter class is class CarFilter(django_filters.FilterSet): having_image = django_filters.Filter(name="images", lookup_type='in') class Meta: model = Car then I can make queries like ?having_image=5 and get all cars that have an image with pk=5. That's fine. But what if I need to return both cars with this image AND also cars with no images at all, in one list? How do I unite two conditions in one django_filters.Filter? -
Django migration from dynamic fields
i' ve the following django model: class Apple(models.Model): text = models.TextField() . I' ve already many records, and i' d like to add a subject field to the model, so it' ll look like: class Apple(models.Model): text = models.TextField() subject = models.CharField(max_length = 128) . In this case i run a makemigrations, but since subject can be empty, i need to set a default value either in the model, or in the migration file. What would be the correct procedure if i' d like to take the subject from the text for the already existing database lines (for instance: text[:64])? My solution would be to create a migration with a default value, run a management commend to update the values, and with a new migration remove the default value for the subject. Is there a better solution, right? What is it? Can i somehow combine / do this in the migration itself? Python: 3.4.5 Django: 1.9.2 .