Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do a GROUP_BY in django queryset with returned model fields?
I'm using django 1.11. I would like to use the group_by behavior (mysql) on a queryset. Is there a way to get a QuerySet grouped by one or two fields with every returned model fields, without use values() or values_list() method ? My query get job offers and i would like to get one job per network agency. I have a user model (custom with around 20 fields) and a job_offer model (with also 20 fields). The distinct() on fields is not supported by MySQL. For the moment, my only solution is to use RawSQL... -
How to run celery worker in Django 1.11
I have upgraded Django from version 1.7 to version 1.11.2 and Celery from version 3.1.25 to version 4.0.1. Before this upgrade I was able to run celery workers throw django-celery package in this way: python manage.py celery worker -Q <my_queue> --app=proj.celery:app --concurrency=5 Reading Celery release notes and documentation, I found out that for using Django ORM as a result backend, I can't use anymore django-celery package but I have to use django-celery-results and django-celery-beat, instead of it. With the same command I'm not able to run workers anymore. More in detail I try to run the following command: celery worker -app=proj.celery:app -l info Where celery is the celery.exe file in my virtualenv (virtual_env_name\Scripts\celery.exe). This raised the following error: Traceback (most recent call last): File "c:\python27\Lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "c:\python27\Lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\virtualenv\<virtual_env_name>\Scripts\celery.exe\__main__.py", line 5, in <module> File "path\of\my\project\celery.py", line 8, in <module> from celery import Celery ImportError: cannot import name Celery celery.py file from __future__ import absolute_import import os from celery import Celery import django django.setup() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) project structure - main - proj - __init__.py - … -
deploying a django project to Heroku: ImproperlyConfigured error; STATIC_ROOT setting
Thank you for look at here! I met a problem when I want to deploy a Django project to Heruko. Here is the error information. remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote: ! Error while running '$ python manage.py collectstatic -- noinput' remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 When I try: '$ python manange.py collectstatic --noinput' I got: python: can't open file 'manange.py': [Errno 2] No such file or directory Here is my settings(the same as https://devcenter.heroku.com/articles/django-assets): # Heroku settings if os.getcwd() == '/app': import dj_database_url DATABASES = { 'default': dj_database_url.config(default='postgres://localhost') } # let request.is_secure() admit X-Forwarded-Proto header SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # support all host header ALLOWED_HOSTS = ['*'] PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) I have seen the similar questions on stack overflow, but they did not work for me. Any guide could be helpful. Thanks! -
Django : not all arguments converted during string formatting
I'm getting a little problem between models and forms in my Django project. I created a new app : Divorce My models.py file looks like : #-*- coding: utf-8 -*- from django.db import models from Identity.models import Person from Mariage.models import Acte_Mariage from django.utils.encoding import force_text from django_countries.fields import CountryField class Acte_Divorce(models.Model): fk_epoux = models.ForeignKey(Person, related_name='EpouxDivorce', verbose_name='Epoux', null=False) fk_epouse = models.ForeignKey(Person, related_name='EpouseDivorce', verbose_name='Epouse', null=False) fk_temoin1 = models.ForeignKey(Person, related_name='Temoin 1 Divorce+', verbose_name='Temoin 1', null=True) fk_temoin2 = models.ForeignKey(Person, related_name='Temoin 2 Divorce+', verbose_name='Temoin 2', null=True) fk_temoin3 = models.ForeignKey(Person, related_name='Temoin 3 Divorce+', verbose_name='Temoin 3', null=True) fk_temoin4 = models.ForeignKey(Person, related_name='Temoin 4 Divorce+', verbose_name='Temoin 4', null=True) mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie', default=' ') fk_mariage = models.ForeignKey(Acte_Mariage, related_name='ID', verbose_name="ID", null=False, default= '0') divorce_date = models.DateField(null=True, blank=True, verbose_name='Date du mariage (optionnel)') divorce_heure = models.TimeField(null=True, blank=True, verbose_name='Heure du mariage (optionnel)') created = models.DateTimeField(auto_now_add=True) utilisateur = models.CharField(max_length=100, null=False, verbose_name="utilisateur", default=" ") As you can see, I have two fields with two different Foreign_Key : the first one is pointing to Person model and the second one to Acte_Mariage model. Now, I have in my Divorce application a forms.py file : class CustomLabelModelChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): self._label_from_instance = kwargs.pop('label_func', force_text) super(CustomLabelModelChoiceField, self).__init__(*args, **kwargs) def label_from_instance(self, obj): return self._label_from_instance(obj) class Acte_Divorce_Form(forms.ModelForm): … -
URL rendered as home_page after internationalization
I have a Django Website that I am trying to internationalize. Until now it looked like this: Homepage: www.myhomepage.com Another page: www.myhomepage.com/content/cities Now I am trying to make it like this: Homepage: www.myhomepage.com/en www.myhomepage.com/de Another page: www.myhomepage.com/en/content/cities www.myhomepage.com/de/content/cities Following this and this, I managed to make the homepage work, so with www.myhomepage.com/en I see the homepage in English and with www.myhomepage.com/de I see it in German. The problem comes when I want to go to any other page, like www.myhomepage.com/en/content/cities. Then, the page rendered is still the homepage. Before changing any settings to internationalize it www.myhomepage.com/content/cities was showing up properly. My guess is that the problem is with the view rendering or the url, but I do not manage to make it work. Note that the view for www.myhomepage.com belongs to one app and the view for content/cities belongs to a different app. This is the code I have: settings.py MIDDLEWARE_CLASSES = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.i18n', ], }, }, ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGE_CODE = … -
Pinax Stripe Subscriptions not cancelled on failed charges
I have a problem with customer subscriptions not cancelling when there is a failed charge on a recurring payment. I am using the pinax stripe starter project so all the code is right out of the box. I created a plan with a 1 day free trial, and used the stripe test card that ends in 0341 which fails for testing purposes. For 1 day, the customer's subscription said "trialing". Okay perfect. When the charge failed, stripe immediately cancelled the subscription in the dashboard and sent all the necessary webhooks that were received and processed. Yet that particular subscription now says "active" in my project. If the charge failed and stripe cancelled the subscription, why does the subscription go from trialing to Active? The "delinquent" option on that account was set to true. What could be causing this? I am confused because the admin is telling me the webhooks were "successfully" processed. Thanks! -
Django cli print correct traceback
I'm trying to get Django to print the traceback of the error raised instead of the one of its choosing: class Comand(BaseCommand): ... def handle(self, *args, **options): try: ... except: e, c, b = sys.exc_info() traceback.print_tb(b) # <-- this prints what I want raise CommandError, 'message', b # <-- this results in wront traceback In other words, I want that when manage.py is called like this: ./manage.py command --traceback the traceback printed will be the one from the actual error, and not the Django one. I couldn't find where Django prints the actual message it prints. -
Circular Import with app models
I have an app in two different models, The error is 'cannot import name sku', which i believe is because of a circular import. How can I still reference this app.model without referencing the model import the way I am currently. Model PurchaseOrderDetail App Purchase_order from product.models import InventoryTransaction class PurchaseOrderDetail(AuditMixin, models.Model): purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.PROTECT) sku = models.ForeignKey(Sku, on_delete=models.PROTECT) qty_received = models.IntegerField(default=0, null=True, blank=True) reason_code = models.IntegerField(default=0, null=True, blank=True) def _get_sku_code(self): return self.sku.sku_code def _set_sku_code(self, value): tenant = self.purchase_order.tenant sku = Sku.objects.get(tenant=tenant, sku_code=value) self.sku = sku sku_code = property(_get_sku_code, _set_sku_code) def calc_received(self): # calculate sum of qty_received from inventory_transactions sum_quantity = InventoryTransaction.objects.filter( sku=self.sku, po_number=self.purchase_order, transaction_type='100' ).aggregate( quantity_sum=Sum(F('quantity')) ) return sum_quantity Model Inventorytransaction app Product from purchase_order.models import PurchaseOrderDetail class InventoryTransaction(models.Model): tenant = models.ForeignKey(Tenant) po_number = models.CharField(max_length=100) inventory_transaction = models.ForeignKey(PurchaseOrderInventoryTransaction) def save(self, *args, **kwargs): super().save(*args, **kwargs) # update the PO detail with the qty_received obj = PurchaseOrderDetail.objects.get( purchase_order=self.po_number, sku=self.inventory_transaction.sku ) obj.qty_received = obj.calc_received() obj.save() -
Django TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Newbie here. I'm writing a loader script for a website that uses a csv downloaded from wrapsnet.org. When I try to run the loader I receive the message "TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'." Full traceback: File "loader.py", line 30, in <module> ref.save() File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/base.py", line 961, in _do_insert using=using, raw=raw) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/query.py", line 1060, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1098, in execute_sql for sql, params in self.as_sql(): File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1051, in as_sql for obj in self.query.objs File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1051, in <listcomp> for obj in self.query.objs File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1050, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 990, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 766, in get_db_prep_save prepared=False) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 758, in get_db_prep_value value = self.get_prep_value(value) File "//anaconda/envs/django/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1849, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like … -
get_object_or_404 Nameerror
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, redirect, render from .models import Post, Comment ,Question , Call , Upload ,call_Comment , question_Comment , Search , Font from .forms import CommentForm, PostForm , CallForm, QuestionForm , UploadForm , QuestionCommentForm , CallCommentForm from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .extracting_existing_fonts import estand, eflatten, econversion from .font_similarity import stand, flatten, conversion, jacsim def index(request): post_list = Post.objects.all() question_list = Question.objects.all() call_list = Call.objects.all() search_list = Search.objects.all() upload_list = Upload.objects.all() #Search function query = request.GET.get("q") if query: search_list = search_list.filter(title__icontains=query) return render(request, 'blog/post_list.html', { 'post_list' : post_list, 'question_list':question_list, 'call_list':call_list, 'search_list':search_list, 'upload_list':upload_list, }) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', { 'post' : post, }) def question_detail(request, pk): question = get_object_or_404(Question, pk=pk) return render(request, 'blog/question_detail.html', { 'question' : question, }) def call_detail(request, pk): call = get_object_or_404(Call, pk=pk) return render(request, 'blog/call_detail.html', { 'call' : call, }) def upload_detail(request, pk): import pdb pdb.set_trace() upload = get_object_or_404(Upload, pk=pk) """ efont = get_object_or_404(Font, pk=pk) upload_font = conversion(upload.photo.path) stored_font = [] for etitle, efontfile in efont: stored_font.append({etitle : jacsim(upload_font, econversion(efontfile.path))}) """ return render(request, 'blog/upload_detail.html', { 'upload' : upload, }) @login_required def post_new(request): if request.method=="POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.save() … -
Python 3.6 Django Registration Redux SMTPAuthenticationError at /accounts/register/
Unable to Register despite trying several times please tell how do i fix it! code : DEBUG = True ALLOWED_HOSTS = [] EMAIL_HOST ='smtp.gmail.com' EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD='**********' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Getting IndentationError: using Python and Django
I have an issue. I am getting the below error while setting my view.py page. I am explaining my error below. File "/opt/lampp/htdocs/myproject/crud/views.py", line 10 c = Context({'message': 'Hello world!'}) ^ IndentationError: unindent does not match any outer indentation level My view.py file is given below. from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader, Context # Create your views here. def index(request): t = loader.get_template('index.html') c = Context({'message': 'Hello world!'}) return HttpResponse(t.render(c)) Here I need to resolve this error. Please help me. -
Template not getting rendered on django
views.py file: from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('upload/testpage.html') return HttpResponse(template.render) app/templates/app/testpage.html file: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple /> <a href="" onclick="document.getElementById('upload').click(); return false">Upload</a> </body> </html> app/urls.py file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'),] project/urls.py file: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^upload/', include('upload.urls')),] Getting an error when running file on local server 127.0.0.1:8000/app of "TemplateDoesNotExist at /app/" How can this be resolved? -
Unable to Upload document and update model
Currently I'm having a issue uploading a document to my Django app and then update my model with the new data and indicators. I'm getting the correct show object and I think I'm passing the data correctly, but nothing is updating when I go to check it. view.py def documents_view(request, show_id): """render documentation view""" show_object = get_object_or_404(Show, pk=show_id) showDocumentID = show_id showChecklist = show_object.show_checklist site_diagram_document = DocumentSubmitForm(request.POST) service_agreement_document = DocumentSubmitForm(request.POST) insurance_certificate_document = DocumentSubmitForm(request.POST) product_shot_list_document = DocumentSubmitForm(request.POST) permit_app_submitted_document = DocumentSubmitForm(request.POST) if request.method == "POST": print("document") print(request.FILES) # check if object already has documents for doc in request.FILES: if doc == "service_agreement": document = DocumentSubmit(request.FILES[doc]) print(document) show_object.show_checklist.service_agreement_document = document if (show_object.show_checklist.service_agreement != True): show_object.show_checklist.service_agreement = True show_object.save() elif doc == "insurance_certificate": break elif doc == "product_shot_list": break elif doc == "permit_app_submitted": break messages.success( request, 'You have successfully submitted documentation') return redirect('website:dashboard') return render( request, 'website/show_document_view.html', {'showChecklist': showChecklist, 'site_diagram_document': site_diagram_document, 'service_agreement_document': service_agreement_document, 'insurance_certificate_document': insurance_certificate_document, 'product_shot_list_document': product_shot_list_document, 'permit_app_submitted_document': permit_app_submitted_document, 'showDocumentID': showDocumentID}) models.py class DocumentSubmit(models.Model): """Document Submit model - model for submitting documents""" document = models.FileField( null=True, blank=True) class PermitCheckList(models.Model): """PermitCheckList model - contains properties for PermitCheckList""" site_diagram = models.BooleanField(default=False) site_diagram_document = models.ForeignKey( DocumentSubmit, related_name='site_diagram_document', null=True, blank=True) service_agreement = models.BooleanField(default=False) service_agreement_document = models.ForeignKey( DocumentSubmit, related_name='service_agreement_document', … -
Iter through object and append if in group
I'm trying to figure out how to iter through a object, called 'item', that looks like this. <OL> <LI> <name>Foo</name> <type>Spam</type> <group>Wood</group> <....>ETC</....> </LI> <LI> <name>BAR</name> <type>Spam</type> <group>Iron</group> <....>ETC</....> </LI> </OL> And I want to create a new list where I can choose every 'NAME' from each 'LI' where the 'GROUP' is 'WOOD'. I'm new to this and all I figured out is this. for a in item.iter('name'): woodList.append(a.text) This takes all 'NAME' from all 'GROUP'. I tried with some IF. But can't find right syntax to check which 'GROUP' it belongs to. Help much appreciated. -
Installing Django 1.11.2 with pip install. Pip.exe trying to install SONAR.AM.C.J!g9 virus?
I have set up a virtual environment for my first Django project, and have tried to install Django using pip install Django However, when I do so, Norton warns that pip.exe is trying to download the SONAR.AM.C.J!g9 virus. Based on what I've read, I don't want to take the risk of going further so am having to remove pip.exe from the environment. I've searched for similar issues but not having any luck so far. Can anyone advise me how I should proceed? Many thanks! Set up is Windows 10 64 bit, Python 3.5 -
Django-MySQL is unable to recognise model.column in queryset extra?
I have SQLite and MySQL installed on my local and development machine respectively. Following is working fine on my local machine(with SQLite): select_single = {'date': "strftime('%%Y-%%m-%%d',projectName_Modelname.created)"} queryset.extra(select=select_single) But since strftime doesn't work with MySQL(link), I tried using DATE_FORMAT() as suggested in given link and other places too. Though now when I execute below: select_single = {'date': "DATE_FORMAT(projectName_Modelname.created, '%%Y-%%m-%%d')"} queryset.extra(select=select_single) Following error comes: DatabaseError: (1054, "Unknown column 'projectName_Modelname.created' in 'field list'") where 'created' is Datetime field in Django model 'Modelname' of app 'projectName' To debug when I replace projectName_Modelname.created with NOW() no error comes. I have also tried just Modelname.created instead of projectName_Modelname.created though with no benefit? Note: I am using Django1.5.5 -
when i delete rows from my database the primary key increases
I tried deleting the data from my table from Django administration (I use default database), but the primary key keeps on increasing, i.e I had two instances in my table, I deleted them, and added a new one, so shouldn't the primary key be 1, but it becomes zero. how do I make it 1 again? Should I auto increment? -
Saving data type when creating a dictionary
I'm trying to save the data type when creating a dictionary. The following example always stores all variables as a string: arr = {} for value in self.method_list[method]: try: arr[value] = urllib.parse.unquote(request.GET[value]) except KeyError: pass result: {'sign': '123'} I need to have the numeric data stored as int: arr[value] = int(urllib.parse.unquote(request.GET[value])) result: {'sign': 123} How can I automatically create a dictionary with the right types? -
limit ForeignKey choices based on another ForeginKey field
Let's say I have an app's structure that looks like this : ** models.py ** Class School(models.Model): name = models.CharField(max_length=500) Class Manager(models.Model) name = models.Charfield(max_length=500) school = models.ForignKey(School) Class Group(models.Model) name = models.Charfield(max_length=500) school = models.ForeignKey(School) manager = models.ForeignKey(Manager, related_name="group_manager") In the template I want users to be able to create groups (in the school page) and choose among managers who belong to the same school only! Any idea? -
Serve one Django app on several Apache Virtualhosts
We have a Django application served by Apache with such config : <VirtualHost vhost:80> # ... WSGIScriptAlias / /path/to/wsgi.py </VirtualHost> We're looking to serve that single application into 2 virtualhosts : vhost:80 and vhost:443 ... the time necessary for the client's migration and finally only keep it on the https virtualhost. Is it possible to duplicate the instruction WSGIScriptAlias / /path/to/wsgi.py into a second virtualhost (vhost:443) or will we encounter problems running twice the same app with same DB? -
Django not committing form to database
I need some help, I’ve spent 3 days on this and I’m still stuck. The use case is that a logged in use, can call up their profile into a form, edit it and it gets updated in the database. With the code below the correct Profile data can be viewed. It can also be called up into an editable form. The form allows the data to be edited , but when it is submitted, the database is NOT updated and the original profile is displayed. I’ve tried everything, including console print statements so I know that it is getting to the POST portion of the code, is a valid form and doing the initial save(). Any insights would be appreciated (I am using Django 1.11). I do not want to start a rabbit running but the only thing I have not tried is breakink the OneToOne relationship with User and using a foriegnkey because I want the profile entry creaed when the user registers. Notes: When I popped this in for testing purposes: save_data.user = request.user I get the error: Exception Value:'User' object has no attribute 'cleaned_data'`from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save Models.py … -
DRF: appending data to each response
We are using Django 1.11 with Django Rest Framework. We are trying to implement some advanced permissioning system. Currently, we have some tehnical issues and one of them is: return linked permissions for currently logged in user (by request.user) on every request. Example: endpoint http://localhost:8000/articles/1/ should return information about that article and linked permissions to the user. Something like this: {'title': 'Article Title', 'pages': 50, 'permissions': ['can_read_article', 'can_update_article'] ...} Those permissions should be managed inside Django Admin > Users & Groups system. Thanks a lot, any help will be appreciated -
Passing email address with url failed in Django
I am new in Django rest framework. I am trying to develop an API for my ios app. i need to pass email address with url. Below is the code for my urls.py file from django.conf.urls import url from . import views app_name = 'account' urlpatterns = [ url(r'^accounts/$', views.AccountView.as_view() , name='post_get_account'), url(r'^accounts/(?P<id>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.])/$',views.AccountDetails.as_view(), name='account_details'), ] My first url works fine. But the second url is not working. It responds with Unexpected '<' in Postman My code for views.py is given below from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from .models import Account as model from . import AccountSerializer # Create your views here. class AccountView(APIView): def get(self,request): """ METHOD: Get a list of Account Records """ list = model.objects.all() serializer = AccountSerializer.AccountSerializer(list,many=True) return Response(serializer.data) def post(self,request): """ METHOD: Create a Account Record """ serializer = AccountSerializer.AccountSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class AccountDetails(APIView): def get_object(self,account_id): """ METHOD: Find an Account Record """ try: return model.objects.get(account_id=account_id) except model.DoesNotExist: return False def get(self,request,id,format = "None"): """ METHOD: Get a particular Account Record """ print("function fired ") account = self.get_object(account_id = id) if not account: return Response("404 Not Found") serializer = AccountSerializer.AccountSerializer(account) return Response(serializer.data) … -
Cleaning formset as a whole
models.py: class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) num = models.IntegerField() forms.py: B_FormSet = forms.models.inlineformset_factory(A, B, extra=3, fields=['num']) I have this scenario above, and I want to clean the B_FormSet as in: no two Bs instance of that formset can have the same num. But I'd like to do that inside the forms.py, not in the views.py. I've tried to use the BaseFormSet, but with no luck: class BaseB_FormSet(forms.BaseFormSet): def clean(self): pass B_FormSet = forms.models.inlineformset_factory(A, B, formset=BaseB_FormSet, extra=1, fields=['num']) When I instantiate the formset using the instance= keyword as: formset = B_FormSet(request.POST, instance=xx) It throws: TypeError: __init__() got an unexpected keyword argument 'instance'