Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model Field added using custom SQL not detected by Django
I have added a field to my model. But I have added the field to the model in DB through a custom sql query(Alter Field). Now when I try to create other Migration files, Django creates migration for adding the field to that model in DB. How to make django not do this? -
I want that Django model field can have only two possible values
class Proposta(models.Model): descrizione = models.TextField() titolo = models.CharField(max_length=200) richiedibile = models.BooleanField(default=False) inRichiesta = models.BooleanField(default=False) archiviata = models.BooleanField(default=False) # tesi or AP tipologia = models.CharField(max_length=50) I want that the 'tipologia' field can have only two possible value: 'tesi' or 'AP'. In other words I want the field looks like a list in which user can choose the value he want. -
What's the strange format data in python?
When I use the ajax post to my api, I get the bellow information, I did not saw this data type, who can explain this: {u'params[memory_cpu_address][3][cpu]': u'1\u6838', u'params[bandwidth][bandwidth]': u'1M', u'params[security_setting][example_name]': u'liaodalin01', u'params[memory_cpu_address][2][model]': u'\u6807\u51c6\u578b\u4e00', u'params[server_count][server_length]': u'1\u53f0', u'params[operating_system][system_edition]': u'Windows2003', u'params[memory_cpu_address][0][address]': u'\u6df1\u5733', u'params[security_setting][user_name]': u'root', u'params[storage][data_disk][disk_length]': u'0', u'params[storage][system_disk][type]': u'SSD', u'params[security_setting][user_password]': u'liaodalin01', u'params[memory_cpu_address][4][memory]': u'1G', u'params[total_prices][prices]': u'430', u'params[memory_cpu_address][1][usable-area]': u'\u6df1\u5733\u4e00\u533a', u'params[operating_system][system_name]': u'Windows', u'params[storage][data_disk][type]': u'SSD', u'params[time_buying][deta_time]': u'1\u6708', u'params[storage][system_disk][disk_length]': u'40' } My ajax code is : $.ajax({ type:'post', url:'/app_api/buy_server/', data:{'params':buy_data}, # buy_data is a dictionary in js success:success_func, }) My views.py code is : if request.method == 'POST': post_querydict = request.POST post = post_querydict.dict() print (post) How can I get the normal dictionary format? because this type data, I can not get the data like this post.get("params") method. -
Mocking external library in django
I'm trying to mock external library import in my django app, however tests keep complaining that library is not found. It works fine if I put tests into tests.py file together with the rest of the code, like models.py, urls.py and views.py. However, if I put tests under tests directory, it starts throwing no module named.. exception. I have these two imports in views.py: import xml_to_struc.process import csv_to_struc.process and I have the following in tests to mock them: import sys from unittest.mock import MagicMoc module = MagicMock() sys.modules['xml_to_struc'] = module sys.modules['xml_to_struc.process'] = module sys.modules['csv_to_struc'] = module sys.modules['csv_to_struc.process'] = module As I said, if I put them into tests.py together with the rest of the files, this mocking works fine, but doesn't work if I put them under tests directory. Error message I get: ImportError while importing test module '(...)/converter/urls.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: converter/urls.py:3: in <module> from converter import views converter/views.py:8: in <module> import xml_to_struc.process E ModuleNotFoundError: No module named 'xml_to_struc' How can I mock this import? I've tried mocking in tests/__init__.py, but it looks like import is happening a lot earlier in the process, before mocking. -
Django filtering based on count of related model
I have the following working code: houses_of_agency = House.objects.filter(agency_id=90) area_list = AreaHouse.objects.filter(house__in=houses_of_agency).values('area') area_ids = Area.objects.filter(area_id__in=area_list).values_list('area_id', flat=True) That returns a queryset with a list of area_ids. I want to filter further so that I only get area_ids where there are more than 100 houses belonging to the agency. I tried the following adjustment: houses_of_agency = House.objects.filter(agency_id=90) area_list = AreaHouse.objects.filter(feriehus__in=houses_of_agency).annotate(num_houses=Count('house_id')).filter(num_houses__gte=100).values('area') area_ids = Area.objects.filter(area_id__in=area_list).values_list('area_id', flat=True) But it returns an empty queryset. My models (simplified) look like this: class House(TimeStampedModel): house_pk = models.IntegerField() agency = models.ForeignKey(Agency, on_delete=models.CASCADE) class AreaHouse(TimeStampedModel): area = models.ForeignKey(Area, on_delete=models.CASCADE) house = models.ForeignKey(House, on_delete=models.CASCADE) class Area(TimeStampedModel): area_id = models.IntegerField(primary_key=True) parent = models.ForeignKey('self', null=True) name = models.CharField(null=True, max_length=30) -
how to count the values(any string,integer,mixture of both) of single column but if there is any repeat entry it should not be counted?
Here i'm using this formula "COUNTA(A5:A65536)"...its working but it is counting repeated entries sheetname.write(2, 0, Formula("COUNTA(A5:A65536)")) i want the number of count in A2 cell my excel sheet column: Total number of entries 3 Number of entries 21w3331 21w3332 21w3332 here the total no of entries should be "2" as "21w3332" is repeated but i'm getting Total number of entries = 3 -
Spider not found: Django Scrapy integration
I am trying to run a Scrapy spider inside my Django project's view. This is my project structure. ScrapyPro . ├── ScrapyPro │ ├── __init__.py │ ├── items.py │ ├── pipelines.py │ ├── settings.py │ └── spiders │ ├── __init__.py │ └── demo_spider.py └── scrapy.cfg │ WebCrawlerPro ├── WebCrawlerApp │ ├── __init__.py │ ├── urls.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── views.py │ ├── WebCrawlerPro │ ├── __init__.py │ ├── urls.py │ ├── wsgi.py │ ├── settings.py └── scrapy.cfg Here, ScrapyPro is scrapy project and WebCrawlerPro is Django project. And here is the view from where I am trying to run a spider: from django.shortcuts import render import urllib from scrapy.crawler import CrawlerRunner from scrapy.utils.project import get_project_settings # Create your views here. def home_crawl(request): if request.method == "POST": keyword = request.POST.get("search") keyword = urllib.quote(keyword) url =( "https://some_example.com/q/%s" % keyword) crawler = CrawlerRunner(get_project_settings()) crawler.crawl('example', url=url) crawler.start() return render(request,'index.html',{"foo":"bar"}) But when I POST a request through the form in this view. This error appears : KeyError at / 'Spider not found: example' And when I manually run the spider from ScrapyPro project by : scrapy crawl example It executes successfully. What am I doing wrong? -
Django filtering with kwargs
I have the following code. def alpha(**kwargs): q_obj_list = [Q(str(i), kwargs.get(i)) for i in kwargs.keys()] reduce(operator.and_, q_obj_list) return q_obj_list q = Elements.objects.all() q = q.filter(alpha(id=1, is_active=False)) For this code I am receiving an error saying TypeError: 'bool' object has no attribute 'getitem'. I was intending to replace the below code with this. q = Elements.objects.all() id = kwargs.get("id") active = kwargs.get("is_active") q.filter(id=id,is_active=active) How to I fix such an error ? -
Call object in template after _meta.get_fields()
So I have lots of models with relations to the parent model. Like this class Part(models.Model): name = models.CharField(max_length=550) class Stock(models.Model): name = models.CharField(max_length=550) class StockArea(models.Model): area = models.CharField(max_length=550) stock = models.ManyToManyField(Stock, related_name='stockarea_stock') class Si(models.Model): name = models.CharField(max_length=50) si_unit = models.CharField(max_length=10) class Quantity(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) si = models.ManyToManyField(Si, related_name='quantity_si') part = models.ManyToManyField(Part, related_name='quantity_part') stockarea = models.ManyToManyField(StockArea, related_name='quantity_stockarea') class Image(models.Model): image = models.FileField() part = models.ManyToManyField(Part, related_name='image_part') When I want to have a detail view of a part, I want to show Name of part, Quantity, Image, stockarea etc. So the viw looks like this for the detail view def details(request, part_id): part = get_object_or_404(Part, pk=part_id) part = part._meta.get_fields() context = { 'part': part, } return render(request, 'part/details.html', context) The problem comes when trying to call for everything in the template. I can show object with calling just part: {{ part }} But I want to be able to call the name of the part, like: {{ part.name }} I understand this would be troublesome since related fields also are called 'name'. So I thought I was gonna be able to call it like this: {{ part.Part.name }} or when I want to show quantity: {{ part:Quantity.quantity }} None … -
Django templated docs creating tmp file in /tmp/
Hello i am using django templated-docs to generate pdf invoices but the challenge is that it generates the files in /tmp/ (root directory of ubuntu) i want it to generate the files inside django directory here is my codes: """ Mail Receipt """ ctx = { "customer_names": receipt.customer_full_name, "customer_phone": receipt.phone_number, 'date_assessed': receipt.date_time.strftime('%d-%m-%Y %H:%M'), 'grand_total': gross, "amount": total, "invoice_number": receipt.invoice_number, "smart_card_no": receipt.smart_card_number, "receipt_signature": response['signature'], } print "***********Generating Pdf Invoice now" filename = fill_template(template_name='email_templates/invoice.ods', output_format='pdf', context=ctx) print '************************** Finished generating file *******************' visible_filename = 'invoice.{}'.format('pdf') f = FileResponse(filename, visible_filename) # print 'Tmp File name {}'.format(f) print f # fs = FileSystemStorage(f) # filename = fs.save(filename, f) # invoice = os.path.join('files/' + filename) import shutil import os source = os.listdir("/tmp/") destination = os.path.join('files/invoice_{}.pdf'.format(receipt.invoice_number)) for files in source: if files.endswith(".pdf"): shutil.move(files, destination) # print 'Invoice Generated {}'.format(invoice) # msg = EmailMessage("Sales Receipt", "Receipt", 'user@server.com', [receipt.email_address]) msg.attach_file(destination) msg.send(fail_silently=True) print 'Sent Invoice' Anyone having an idea of how to do this please, -
django error using pagination
I m trying to use pagination, but it gives me this error: Traceback (most recent call last): File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/tester/tables/views.py", line 44, in addview details = paginator.page(1) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/paginator.py", line 57, in page number = self.validate_number(number) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/paginator.py", line 46, in validate_number if number > self.num_pages: File "/home/omega/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/paginator.py", line 91, in num_pages if self.count == 0 and not self.allow_empty_first_page: File "/home/omega/venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/omega/venv/local/lib/python2.7/site-packages/django/core/paginator.py", line 84, in count return len(self.object_list) TypeError: object of type 'RawQuerySet' has no len() This is the part i m using for the tables paginations. models.py def addview(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name tbl_detail = AllTables.objects.raw(tbl_details) paginator = Paginator(tbl_detail, 25) page = request.GET.get('page') try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) crawled_tables = AllTablesFilter(request.GET, queryset=tbl_detail) return render(request, 'tables/table_list.html', {'tbl_name': table_name, 'details': tbl_detail, 'filter': crawled_tables, 'detail_page': details}) End this is the part of html where i … -
Django: Uploading multiple files. List of files needed in cleaned_data['file']
I followed the pattern of the docs, to upload several files with one forms.FileField: https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#uploading-multiple-files Unfortunately cleaned_data['file'] does contain one file, not both files. What needs to be done to have all uploaded files on cleaned_data['file']? -
Permanently setting up Postgres parameters on Heroku, without running SET on each request
I am trying to permanently set up a posgres parameter on a Heroku database. Running the SET command would only set it up for the current connection. So I have to run this command for each request in the application, which I don't want to do. I would normally do this in postgres.conf, but I don't know how to access that file on Heroku. I am working on a Django appilcation, so I tried setting the init_command on in the django database settings, but it seems that psycopg2 does not support this. Is there a way to do this, without running the SET command? I know the SET is very fast, but still I don't want to do it for each request. Or maybe I am wrong with this? -
Python 2.7 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am new at learning Django, I am using django-1.11.4. By default I was using python 2.7. I have gone through some of the similar questions but no luck. Please suggest. This is my Traceback: Traceback (most recent call last): File "C:/Users/skum/PQP_Bridge/qspraw7_data/views.py", line 8, in <module> from models import PqpModel File "C:\Users\skum\PQP_Bridge\qspraw7_data\models.py", line 14, in <module> class PqpModel(DjangoCassandraModel): File "C:\Python27\lib\site-packages\django_cassandra_engine\models\__init__.py", line 448, in __new__ name=name File "C:\Python27\lib\site-packages\django_cassandra_engine\models\__init__.py", line 489, in _add_django_meta_and_register_model app_config = apps.get_containing_app_config(module) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\Python27\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. These are the apps I installed: INSTALLED_APPS = [ 'django_cassandra_engine', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'qspraw7_data.apps.Qspraw7DataConfig', 'chartit', ] apps.py; from __future__ import unicode_literals from django.apps import AppConfig class Qspraw7DataConfig(AppConfig): name = 'qspraw7_data' -
How do i pass extra context from DRF Custom authentication class
I am using DRF for building an API in django. I have written a custom authentication class based on rest_framework.authentication.BaseAuthentication, that validates a incoming JWT. Within the JWT payload i have an attribute, say "organisation_id":"123", which i would like to access in the view that processes the request. Is there any possibility to add the attribute to the context of the request object? According to the DRF docs, the authenticate method of the BaseAuthentication should only return the tuple (user, auth). -
Django UpdateView update filed in view
I am making simple app in django, I have UpdateView for updating my model once is in the database. I update form I didn't include all fields I would like to update some of them in the background. Something like: #... invoice.organization = request.user.groups.first() invoice.user_input = self.request.user.get_full_name() invoice.price = form.cleaned_data['price'] #i update this field in UpdateView invoice.quantity = form.cleaned_data['quantity']#i update this field in UpdateView #this is what I do in form where I create my model I would like to do something like that in UpdateView too if form.cleaned_data['price'] is not None and form.cleaned_data['quantity'] is not None: narocilnica.sum_price = float(form.cleaned_data['price']) * float(form.cleaned_data['quantity']) else: narocilnica.sum_price = form.cleaned_data['cena_brez_DDV'] #... This is how my UpdateView looks like: class InvoiceUpdate(LoginRequiredMixin, generic.UpdateView): login_url = '/accounts/login' redirect_field_name = 'redirect_to' success_url = '/' template_name = 'invoice/invoice_update.html' model = Narocilnica fields = [ 'number', 'price', 'quantity', 'comment', 'notes', ] How can I know update fields in UpdateView class? -
Django form changes the type of variable when reloaded after validation error
I have spent some time on this but cannot figure out the exact cause of the following behaviour. I have a Django form and in the template I am trying to see if an int is in a list and then doing something with it. {% if pk in form.area.value %} {# form.area.value is a list like [7,21] #} do something {% endif%} Everything works fine except in cases where the form is reloaded after a validation error. In such cases, the list that I am comparing with, gets converted to list of strings (from a list of ints) on its own and the if test fails. So [7,21] above becomes ['7','21'] In case it helps, this is how the form is being rendered in the view: On the GET request (where the if condition works fine): form = SchoolForm(instance = school) return render(request, 'edit-school.html', {'form': form, 'school_id': school_id}) After the POST request (where the if condition fails): form = SchoolForm(request.POST or None, instance=school, request=request) return render(request, 'edit-school.html', {'form': form, 'school_id': school_id}) -
Django url pattern multiple Parameters (without pk)
I'm new to the Django Framework and one thing bothers me. I want a simple Rest Call: www.abc.com/users/1/cantonments/1/ If i use 'pk' in the url pattern everything works out of the box (pk, pk1, pk2....). But i have some permission functionality which expects the parameters in kwargs in the form 'upk' and 'cpk' for user and cantonment. So if i change pk to upk everything breaks. Somehow the url needs ONE pk. This works: url(r'^users/(?P<pk>[0-9]+)/cantonments/(?P<cpk>[0-9]+)/$', views.CantonmentDetail.as_view()), This doesnt: url(r'^users/(?P<upk>[0-9]+)/cantonments/(?P<cpk>[0-9]+)/$', views.CantonmentDetail.as_view()), Is there any way to have an url pattern that does not need one entry with pk? P.S. The error: Expected view CantonmentDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. -
Django search site remove model form
I have a code that gives model form for feedback. There are forms for feedback and search form. I need to remove model forms from webpage if users will search something and give search results. Is it possible Code below view.py class FeedbackSendForm(CreateView): model = Feedback fields = [ 'title', 'user_name', 'user_lastname', 'email', 'text', ] template_name = 'feedback.html' success_url = reverse_lazy('school:feedback') def form_valid(self, form): messages.success(self.request, message='Successfully added') return super(FeedbackSendForm, self).form_valid(form) def search(self, request): news_list = News.objects.all() search_query = request.GET.get('search') if search_query: news_list = news_list.filter( Q(news_title__icontains=search_query) | Q(news_text__icontains=search_query) ) print(search_query) -
How to render multiple forms in a single page using Material Design for django forms?
How can we display two forms in a single page using the Material Design for django forms? In the forms.py, we can add code like template = Template(""" {% form %} {% part form.username prefix %}<i class="material-icons prefix">account_box</i>{% endpart %} {% part form.email prefix %}<i class="material-icons prefix">email</i>{% endpart %} {% part form.password prefix %}<i class="material-icons prefix">lock_open</i>{% endpart %} {% endform %} """) And then in the template we have {% block formbody %} {% include form.template %} {% endblock %} How we can add one more form to the page say form2? -
Django ForeignKey field type
I have a model Products: class Products(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=255) image = models.CharField(max_length=255, blank=True, null=True) status = models.IntegerField() """created_by = models.IntegerField(blank=True, null=True) updated_by = models.IntegerField(blank=True, null=True)""" created_by = models.ForeignKey('User', db_column='created_by', related_name='created_product') updated_by = models.ForeignKey('User', db_column='updated_by', related_name='update_product') created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) the mysql shell shows the id field of type: | id | int(10) unsigned | NO | PRI | NULL | auto_increment | I'm trying to create a ForeignKey to this table in such a way: class ProductVarieties(models.Model): id = models.PositiveIntegerField(primary_key=True) product = models.ForeignKey(Products) variety = models.CharField(max_length=200, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) on running migrations, I get an error django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') If I do describe product_varieties, I get: +------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+-------+ | id | int(10) unsigned | NO | PRI | NULL | | | variety | varchar(200) | YES | | NULL | | | created_at | datetime(6) | YES | | NULL | | | updated_at | datetime(6) | YES | | NULL | | | product_id | int(11) | NO | | NULL | | +------------+------------------+------+-----+---------+-------+ Notice type … -
Sort more then one table separately
I have a django template containing more then tables with the same headers and I want to sort each table separately. For that I´m using the webstack-django-sorting package https://github.com/webstack/webstack-django-sorting When I click a header in my example it sorts all 4 tables but i only want to sort one table. Can anybody give me a hint how to solve this? {% extends 'base.html' %} {% load sorting_tags %} <!-- input field --> {% block body %} <form class="container" action="/customer/newOrders/" method="post"> <label>{% csrf_token %} Please choose a production plan :</label> <select name="dropdown-menu"> <option disabled selected value> -- select an option -- </option> {% for production_numbers in production_numbers %} <option class="dropdown-item" value="{{ production_numbers }}"> {{production_numbers}} </option> {% endfor %} </select> <input type="submit" value="Hinzufügen" class="btn btn-success myButton"/> </form> <!--{% for message in messages %}--> <!--<div class="alert {{ message.tags }} alert-dismissible" role="alert">--> <!--<button type="button" class="close" data-dismiss="alert" aria-label="Close">--> <!--<span aria-hidden="true">&times;</span>--> <!--</button>--> <!--{{ message }}--> <!--</div>--> <!--{% endfor %}--> <div class="container"> <h1>Pending</h1> {% autosort articles_pending %} <table class="table"> <thead> <tr> <th>{% anchor production_nr _("Production #") %}</th> <th>{% anchor article_nr _("Article #") %}</th> <th>{% anchor article_name _("Article name") %}</th> <th>{% anchor amount _("Amount") %}</th> <th>{% anchor price_offer _("Price") %}</th> <th>{% anchor create_date _("Create date") %}</th> <th>{% anchor … -
How to JOIN three tables with Django ORM with WHERE clause
I have three models: class model_A(models.Model): data_1 = models.CharField(max_length=60) data_2 = models.SmallIntegerField() data_3 = models.IntegerField(blank=True, null=True) class model_B(models.Model): data_a = models.ForeignKey(model_A) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() class model_C(models.Model): data_a = models.ForeignKey(model_A) data_1 = models.CharField(max_length=5) data_2 = models.IntegerField() so as you can see there is a one-to-one relationship between model_B → model_A and model_C → model_A, it's very simple. I need to make a JOIN of these three tables with a WHERE clause, so with RAW SQL it would be: SELECT * FROM `model_A` JOIN `model_B` ON `model_A`.`data_1` = `model_B`.`data_a` JOIN `model_C` ON `model_A`.`data_1` = `model_C`.`data_a` WHERE `model_B`.`data_1` = 1 AND `model_C`.`data_1` = 1 How can i make a JOIN of these three tables (using filter statement (WHERE clause)) by using Django ORM? -
'StateApps' object has no attribute 'label' while running migration
As I am trying to run the this migration: def add_user_data(apps, schema_editor): Group = apps.get_model('auth', 'Group') Permission = apps.get_model( 'auth', 'Permission') Profile = apps.get_model('user', 'Profile') User = apps.get_model('user', 'User') andrew_user = User.objects.create( email='django@jambonsw.com', password=make_password('hunter2'), is_active=True, is_staff=True, is_superuser=True) andrew_profile = Profile.objects.create( user=andrew_user, name='Andrew', slug='andrew', about='The author of this site!') ada_user = User.objects.create( email='ada@djangogirls.org', password=make_password('algorhythm'), is_active=True, is_staff=True, is_superuser=False) ada_profile = Profile.objects.create( user=ada_user, name='Ada Lovelace', slug='the_countess', about=( ' ')) contributors = Group.objects.create( name='contributors') ada_user.groups.add(contributors) permissions = [ 'add_post', 'change_post', ] for perm in permissions: contributors.permissions.add( Permission.objects.get( codename=perm, content_type__app_label='blog')) def remove_user_data(apps, schema_editor): Group = apps.get_model('auth', 'Group') Profile = apps.get_model('user', 'Profile') User = apps.get_model('user', 'User') Profile.objects.get(slug='andrew').delete() Profile.objects.get( slug='the_countess').delete() User.objects.get( email='django@jambonsw.com').delete() User.objects.get( email='ada@djangogirls.org').delete() Group.objects.get( name='contributors').delete() class Migration(migrations.Migration): dependencies = [ ('blog', '0005_post_permissions'), ('user', '0002_profile'), ] operations = [ migrations.RunPython( add_user_data, remove_user_data) ] I ran in this error: AttributeError: 'StateApps' object has no attribute 'label' I don't really know what the 'StateApps' does. But As the error message states it has something to do with assigning the permissions. Can someone help? This code is from a tutorial using Django 1.8 so I think that it is django 1.11 which is making the code error. -
filter multiple objects and returns 'new field' in Serializer
Just like Youtube, I want to see what categories my post is in. My approach is... Get whole list of categories belong to user Get whole list of categories belong to user and the post compare them and return JSON While building a Seriailizer, I feel like I'm totally stock. So frustraing... :( Please feel free to change my approach if you have any better idea. Expected JSON outputis below { ... "categories": [ { "id": 1, "name": "asd" "added": True }, { "id": 2, "name": "workout" "added": True }, ... ] } Here is views.py class PostDetailView(generics.RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'pk' Here is serializers.py (this is a problem) class PostDetailSerializer(serializers.ModelSerializer): ... def get_categories(self, obj): # Right Here! Get whole categories associated with user all_categories = Category.objects.filter(owner=self.context['request'].user) # And the categories associated with user AND the post categories = obj.categories.filter(owner=self.context['request'].user) return CategorySerializer(categories, many=True).data class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ( 'id', 'name', 'added' <- here I want to add 'added' field but I don't know how. ) In case you need a model class Post(models.Model): ... user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) content = models.CharField(max_length=30) ... class Category(models.Model): name = models.CharField(max_length=20) owner = …