Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Flask using jinja in Javascript
This is my Route.py def route_template(template): x = 3 return render_template("home/" + template, segment=segment,x=x) i want to show x in Javascript var graph = Morris.Donut({ element: 'morris-donut-chart', data: [{ value: 100, # here want to add jinja label: 'Data 1' }, { value: 1, label: 'Data 1' }, ], }); i try this but not working value: {{X}}, .. what is best way to add jinja in Javascript -
Visualisation on html using Django / matplotlib
I created an app on Django using my database , I have a graph , I can show my graph using matplotlib What I have to add please in my code to see the graph on my results.html? views.py: def inf_norm_detection(df_abs, crop_left, crop_right, clean_param=500): ''' infinum norm outlier detection, it is the first step of outlier detection computes matrix of inf norm (max of absolute values) of the samples one to onother inputs: clean_param (int) - usualy 150-500, smaller means more outliers, df_abs (pandas DataFrame) - data of interest, usualy absorbance or asmptotic data crop_left, crop_right - values to crop the data according to MPF measurments. output: indexes of df_abs that are suspected to be outliers, if none were identified, None is returned ''' X = df_abs.iloc[:, crop_left:crop_right].to_numpy() l = X.shape[0] D = np.zeros((l, l)) idx = range(len(X)) for j in range(1, X.shape[0]): idx = list(set(idx) - {j}) A = X[idx] - X[j] D[j, idx] = np.abs(A).max(1) D = np.maximum(D, D.transpose()) d = D.sum(0) / l diff = np.sort(d)[1:] - np.sort(d)[:-1] if np.where(diff > clean_param * np.median(diff))[0].size != 0: threshold = np.sort(d)[np.where(diff > clean_param * np.median(diff))[0] + 1].min() return df_abs.iloc[np.where(d >= threshold)].index def show_absorbance(df_abs, crop_left, crop_right, clean_param): outliers = inf_norm_detection(df_abs,crop_left, … -
return bool field in django view set
I wanna return boolean field of a model in view set but I have an error model: class AdviceRequests(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name="user_advice_requests") ADVICE_REQUESTS = ( ('Yes', 'yes'), ('No', 'no'), ) phone_number = PhoneNumberField(default='+989121111111', null=False, blank=False) advice_requests = models.CharField( choices=ADVICE_REQUESTS, default='YES', max_length=10) active = models.BooleanField(default=False) my view: class AdviceRequestsActiveView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = AdviceRequestsSerializer def get_queryset(self, **kwargs): advice_req = AdviceRequests.objects.get(user=self.request.user) active = advice_req.active print(active) return active I have a question when my user come to my site like do you need advice? after that I have a boolean field named active,when user answer the question no matter is yes or not be True now I wanna return this field in the view. Error is:object of type 'bool' has no len() -
How and where to call post_migrate where Django's own Permission model is the sender
In my current project I want to use Django Group model objects as access roles. I'm trying to programmatically assign permissions to the group instances that should have them (for example, 'delete_something' for 'moderator', and Permission.objects.all() for 'admin'), but even though the code runs without errors, no permissions are assigned. After reading a few similar questions, I have a guess that it must be connected to either the order of migrations or some specifics of Permissions migration. Currently, my code runs from the AppConfig class of one of my project's apps that contains most of the models, and is called by its ready() function. I wonder if that is the right place to call that code. I also think that it would make sense for Permission model to be the signal sender, but I don't understand at what point I should be able to call it (when it is registered/ready) and from which part of my project? I attach my current apps.py code below. from django.apps import AppConfig from django.db.models.signals import post_migrate class ReviewsConfig(AppConfig): name = 'reviews' verbose_name = name.capitalize() def setup_permissions(self, sender, **kwargs) -> None: """Get and set permissions for the groups that should have them.""" from django.contrib.contenttypes.models import … -
Django Admin: How to display currently logged in user's ID on the display list?
I am very new to Django and trying to make my first project. I find it difficult to display currently logged in user's ID on the list in Django admin model. I found a solution of how to get the appriopriate ID thanks to Shang Wang (Django admin: Get logged In users id in django) But I don't know how to display this ID on the list, right next to Patient ID, Unit and Create time (mentioned in the code below). My admin.py looks like this : class GeneralAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super(GeneralAdmin, self).save_model(request, form, obj, change) list_display = ('id_patient', 'unit', 'create_time') search_fields = ('id_patient', 'unit', 'create_time') readonly_fields = ('unit', 'Birth_date','create_time',) How to put obj.user's ID into list_display to display it on the list like id_patient, unit, or create_time? -
ValueError: Field 'id' expected a number but got ''
I would like to ask for a little help regarding a code since when I start it tells me this following error: enter image description here Here are the views and code def add(request): cart = get_or_create_cart(request) producto = Producto.objects.get(pk=request.POST.get('product_id')) cart.productos.add(producto) return render(request, 'carts/add.html', { 'producto': producto }) enter image description here enter image description here -
Best practice for serializing different data for a ModelSerializer
I have a model named Client that looks like this: class Client(models.Model): first_name = models.CharField("First Name", max_length=50) last_name = models.CharField("Last Name", max_length=50) email_1 = models.EmailField("Email", max_length=50) phone_1 = models.CharField("Phone", max_length=15) My app receives data from 2 different sources Source A source_a_data = { "first_name": "John", "last_name": "Doe", "email_1": "johndoe@gmail.com", "phone_1": "5555555555" } Source B source_b_data = { "firstName": "John", "lastName": "Doe", "email1": "johndoe@gmail.com", "phone1": "5555555555" } I know that creating a serializer for Source A would look like this: serializers.py class SourceAClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" serializer = SourceAClientSerializer(data=source_a_data) serializer.is_valid(raise_exception=True) serializer.save() Would it make sense to create a new ModelSerializer for source B? Or is there something I'm missing? -
Why I am getting black image while converting to jpeg?
from PIL import Image Image.open("image.tiff").convert("RGB").save("some.jpg", "JPEG", quality=100) I have some images with tiff format and while converting them to JPEG format I am getting whole black images for only some images. Why is that happening to only some images ? -
How to get outdated list in history
I want to get list of outdated processes in history list. the backend in django framework. Can anybody give me hints about it?******************************************************************************************* This is my functions in process_resources.py def get_object_list(self, request): tenant = get_tenant_by_header(request) query = Q(tenant=tenant) if (request.GET.__contains__("outdated")): query.add(~Q(process_status__project_status_name='outdated'), Q.AND) return super(ProcessResource, self).get_object_list(request).filter(query) This is location where I have to make changes in react versions.tsx file. { key: 'status', name: __('status'), fieldName: 'status', minWidth: 180, maxWidth: 180, onRender: (record: Process) => record && ( <Stack horizontal> <Stack.Item> <div className={styles.tagStyles} style={{ backgroundColor: record.status.color }}> <Text className={record.status.color == '#000000' ? styles.textStyles : ''} variant={'smallPlus'}> {__(String(record.status.project_status_name))} </Text> </div> </Stack.Item> <Stack.Item> <TooltipHost content={__('view the process review')} directionalHint={DirectionalHint.bottomCenter}> <IconButton onClick={() => clickProcessReview(record)} iconProps={{ iconName: 'SingleColumnEdit' }} /> </TooltipHost> </Stack.Item> </Stack> ), }, ]; useEffect(() => { getVersions(); }, []); const getVersions = () => { const url = `?outdated=true`; props.searchProcessesAction(url, (res: any) => { res.data.objects.length > 0 && setFetchedProcesses(res.data.objects); }); }; const getOutDatedVersions = () => { return fetchedProcesses.filter((i: Process) => i); }; const renderList = () => { if (fetchedProcesses) { return ( <div className={styles.tableWrapper}> <Stack className={styles.table}> <DetailsList items={getOutDatedVersions()} columns={columnsList} setKey="none" layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={true} selectionMode={SelectionMode.none} /> </Stack> </div> ); } return <></>; }; const renderTable = () => { return ( <DocumentCard className={styles.cardStyles}> … -
Unable to add initial tags using tagulous by post-save signal
Hello to all actually i am a new to coadding and also to stack over flow I apologies if the data provided in wrong way. Just correct me in all the issues. I am Unable to add initial/auto tags tags using tagulous by post-save signal I am working on a project which contains smart phones Brands, models, and their specific firmware files. what i want to do is to while posting a table i want to copy brand name model name and the files title into the tags field along with presets of tags. to do so i am using post save signals from django. and getting the below error. 'list' object has no attribute 'pk' Tagulous verison 1.3 below are the code settings i used Models.py class Skill(tagulous.models.TagTreeModel): class TagMeta: initial = [ "Python/Django", "Python/Flask", "JavaScript/JQuery", "JavaScript/Angular.js", "Linux/nginx", "Linux/uwsgi",] space_delimiter = False autocomplete_view = "resource_skills_autocomplete" class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(max_length=200, null=True,blank=True) Tags = tagulous.models.TagField( to=Skill, help_text="This field does not split on spaces" ) Settings.py SERIALIZATION_MODULES = { 'xml': 'tagulous.serializers.xml_serializer', 'json': 'tagulous.serializers.json', 'python': 'tagulous.serializers.python', 'yaml': 'tagulous.serializers.pyyaml', } Admin.py class … -
How to retrieve detail object from mongodb using classic django urls and views?
I'm working on recording server access log into mongodb database; I'm able to record server access log into mongodb database and also able to list all recorded logs applying django-filter in rest api view. But when I'm wondering if there is a possible way to retrieve log detail so that I can use django provided RetrieveUpdateAPIView. I'm using djongo and my log models is from djongo import models as mongo_models class AccessLog(mongo_models.Model): _id = mongo_models.ObjectIdField() user_id = mongo_models.BigIntegerField(null=True, blank=True) user_email = mongo_models.EmailField(null=True, blank=True) path = mongo_models.CharField(max_length=1024, blank=True, null=True) method = mongo_models.CharField(max_length=10, blank=True, null=True) data = mongo_models.TextField(blank=True, null=True) ip_address = mongo_models.CharField(max_length=45, null=True, blank=True) status_code = mongo_models.IntegerField(null=True, blank=True) flag = mongo_models.BooleanField(default=False) remarks = mongo_models.TextField(null=True, blank=True) created_at = mongo_models.DateTimeField(auto_now_add=True) updated_at = mongo_models.DateTimeField(auto_now=True) And my log list views class AccessLogListView(generics.ListAPIView): permission_classes = (AccessLogPermissions, ) filter_backends = [ filters.SearchFilter, DjangoFilterBackend ] filterset_fields = [ 'user_id', 'user_email', 'method', 'ip_address', 'status_code', 'flag', ] search_fields = [ 'remarks', ] serializer_class = AccessLogSerializer queryset = AccessLog.objects.all() And my detail views as class AccessLogUpdateView(generics.RetrieveUpdateAPIView): permission_classes = (AccessLogPermissions,) lookup_field = '_id' serializer_class = AccessLogUpdateSerializer queryset = AccessLog.objects.all() And urls.py as urlpatterns = [ path('', views.AccessLogListView.as_view(), name='list-access-log'), path('<str:_id>/', views.AccessLogUpdateView.as_view(), name='update-access-log'), ] When I try to get by _id the django throws 404 … -
(mysql.W002) MariaDB Strict Mode is not set for database connection 'default'
Please Help me guys??? I want to integrate laravel web app database to my django project and it gives me this error when I run command migrate it gives me this error (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors -
Country code flag icon is not showing on form in for loop
I am trying to getting flag icon on every edit form of each datatable row have edit button. but unfortunately I can see flag icon only in 1st row of edit form of datatable grid. and in other rows I am not able to see flag icon. Can you help us how can I modified my javascript so I can see flag icon on every edit form of each row of datatable. NOTE : We have code is in Django Python and the variable is in DTL (djnango Template Language) <!--Edit Model Start from Here--> {% for vr in adduser.adduser.all %} <div class="modal fade" id="userEditModal-{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <form method="POST" action="{% url 'edituser' vr.id %}" class="needs-validation" novalidate> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Edit Contact Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!--Form Start--> <div class="form-row"> <div class="form-group col-md-6"> <label for="FirstName">First Name<span style="color:#ff0000">*</span></label> <input type="text" class="form-control" name="firstname" id="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}" required /> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> </div> <div class="form-group col-md-6"> <label for="LastName">Last Name<span style="color:#ff0000">*</span></label> <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}" required /> </div> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out … -
If users log out will their status change?
In django, if a user logs out, will their status change from 'active' to 'not active? Please, I really need to know. Thanks in advance. -
Implementing Django Dropdown with ForeignKeys
I am trying to implement a django dependent dropdown with help of foreign keys in shopping project CRUD models polls models class Products(models.Model): Categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) Colors = models.CharField(max_length=15) Size = models.CharField(max_length=15) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) categories models class Categories(models.Model): category_name = models.ForeignKey(Products,on_delete=models.CASCADE) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) I am unable to get the dropdown,where am I going wrong? -
Esignature workflow implementation
I need to implement a form in my application with the frontend in flutter and the backend in django. The form needs to be signed by two people. The workflow will be as follows: User A adds their info in the form and signs it. User B adds their info in the same form and signs it. The issue is that I need the form to be in a single-page pdf but once user A signs the pdf, more information cannot be added by user B. I am using Docusign for the e-signatures. How can I implement this workflow? -
Return a model field in django view set
I have a problem with my views,I'm trying to write a view to return my user membership if user has in site,but I get an error membership model is: class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) price = models.DecimalField(max_digits=10, default=0, decimal_places=3) def __str__(self): return self.membership_type user membership is: class UserMembership(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='user_membership') membership = models.ForeignKey(Membership, on_delete=models.DO_NOTHING, null=True, related_name='membership', default='Free') def __str__(self): return self.user.email view is: class MembershipView(viewsets.ModelViewSet): model = UserMembership serializer_class = UserMemberShipSerializer def get_queryset(self): user_membership_qs = UserMembership.objects.get(user=self.request.user) if user_membership_qs: membership = user_membership_qs.membership return membership I tried Return Response(membership) too,but didn't work, Error is: object of type 'Membership' has no len() -
Run a PHP script with library inside a python django project
I want to run a php script which uses a library "simonblee/aba-file-generator" in a python project. PHP script can be run easily but I dont know where to install this library, as python will not support it. -
AttributeError: 'JpegImageFile' object has no attribute '_committed'
Here I have a small util function which will convert any images to jpeg and stores into a model But while storing I am getting this error AttributeError: 'JpegImageFile' object has no attribute '_committed' function def convert_and_create_image(): img = Image.open("some_img.tiff").convert("RGB") with BytesIO() as f: img.save(f, format='JPEG') f.seek(0) im = Image.open(f) MyModel.objects.create(image=im) When I create model outside IO block then I got this error AttributeError: 'PixelAccess' object has no attribute '_committed' Outside IO block with BytesIO() as f: img.save(f, format='JPEG') f.seek(0) im = Image.open(f) img = im.load() MyModel.objects.create(image=img) -
why can't delete user in django?
Why can't I delete "User"? Every time I get an object of type "User" and do a .delete() to remove it from the database, it jumps out to me that the "relationship" does not exist (see the images below). below), I don't know how to fix that thing :/ def eliminar_pac_pag(request, pk): user = Usuario.objects.get(pk=pk) return render(request, "eliminar_paciente.html", {"Usuario": user}) def eliminar_paciente(request, pk): u = Usuario.objects.get(id=pk) if request.method == "POST": p = Paciente.objects.get(user_id=pk) turno = Turno.objects.filter(solicitante_id=p.pk, confirmado=True) if not turno.exists(): u.delete() p.delete() messages.success(request, "Se borro al paciente exitosamente!") return redirect("Show_users") else: messages.info( request, "No se puede borrar al paciente por que tiene turnos confirmados") return redirect("Show_users") This is the function I created and below is my models. import datetime from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import (BaseUserManager) from django.core.exceptions import ValidationError from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. from abc import ABC, abstractmethod # Cambiar para que se vea más como elde la página o create superuser def validate_decimal(dni): if not dni.isdecimal(): raise ValidationError(f"El dni debe ser numerico") class CustomUserManager(BaseUserManager): def create_user(self, dni, password, nombre_completo, fecha_nac, email, clave, **extra_fields): if not dni: raise ValueError("El dni … -
Celery beat is sending due tasks but the tasks are not getting executed
Problem statement: The celery beat is sending the scheduled task on time. But the worker is not able to receive the task and execute it. I am using the following celery version django-celery-beat==2.2.0 celery==4.4.0 django-celery==3.3.0 The command is being used for celery-beat celery -A project_path.dev beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler The command is being used for celery-worker celery worker -A project_path.dev --pool=solo -Q celery -l info task.py @periodic_task(run_every=(crontab(minute='*/30')), options={'queue': settings.CELERY_QUEUES_DICT["celery-periodic"]}) def celery_task(): print("Executing Task") celery-beat logs: [2022-07-03 23:00:00,501: INFO/MainProcess] Scheduler: Sending due task path.to.celery_task (path.to.celery_task) celery-dev logs: [tasks] . path.to.celery_task I see a couple of other tasks are not getting executed. Can I get some help here to understand the issue? -
await self.disconnect(message["code"]) TypeError: ChatConsumer.disconnect() takes 1 positional argument but 2 were given
consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer # from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name ='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name, ) routing.py from django.urls import path from room import consumers websocket_urlpatterns=[ path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings') application = ProtocolTypeRouter({ "http":get_asgi_application(), "websocket":AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) }) error: Exception inside application: ChatConsumer.disconnect() takes 1 positional argument but 2 were given Traceback (most recent call last): File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch … -
Tenant not found at 0.0.0.0 django and django-pgschemas
I am using django-pgschemas for multitenancy in my django app. Django version 3.2, python 3.10.5. I have added static tenants in this way, TENANTS = { "live": { "APPS": [ "django.contrib.auth", "django.contrib.sessions", "django.contrib.admin", 'django.contrib.messages', "app_name", ], "DOMAINS": ["live.domain.com"], "URLCONF": "app.urls", }, "public": { "APPS": [ "django.contrib.contenttypes", "django.contrib.staticfiles", "django_pgschemas", "engine", ], }, "default": { "TENANT_MODEL": "engine.Client", "DOMAIN_MODEL": "engine.Domain", "APPS": [ "django.contrib.auth", "django.contrib.sessions", "app_name_2", ], "URLCONF": "app_2.urls", } } This works perfectly with localhost. I am able to access live.localhost:8000 but when I deploy it on digitalocean using docker or apache I get the page not found error. No tenants found at http://0.0.0.0:9000. I have added the domain name in my ALLOWED_HOSTS but it doesn't seem to recognize the static tenant here. -
React component imports from a Django app package
I have created a Django project with a React front-end. I'd like to reuse some of the Django apps and their corresponding React components, so I moved them to a separate Python package following the Django docs: Advanced tutorial: How to write reusable apps. The React components are in the static folders for each Django app and are included with the Python package. The problem I'm running into is that after this new Python package is built and installed in a new Django project, to import a React component I have to import it from the Python package directory (site-packages). Is there a cleaner way to import the React components other than like this? import Comp1A from 'venv/lib/python3.10/site-packages/app_pkg/app1/static/app1/js/comp1a'; This is problematic since the location of site-packages can vary from project to project. Is there at least a dynamic way to generate this path? I can use module.exports.resolve.alias in my webpack.config.js to only set it once in the project, but I would, at least, like to be able to generate the alias automatically. -
how can I change django application server port number in spyne
I am trying to run the spyne Django soap server project on my computer but I can't run the project because the default port number which is 8000, is already in use so I want to change the port number of django soap server. the related project the related code: class Attributes(DjangoComplexModel.Attributes): django_model = FieldContainer django_exclude = ['excluded_field'] class HelloWorldService(Service): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name class ContainerService(Service): @rpc(Integer, _returns=Container) def get_container(ctx, pk): try: return FieldContainer.objects.get(pk=pk) except FieldContainer.DoesNotExist: raise ResourceNotFoundError('Container') @rpc(Container, _returns=Container) def create_container(ctx, container): try: return FieldContainer.objects.create(**container.as_dict()) except IntegrityError: raise ResourceAlreadyExistsError('Container') class ExceptionHandlingService(DjangoService): """Service for testing exception handling.""" @rpc(_returns=Container) def raise_does_not_exist(ctx): return FieldContainer.objects.get(pk=-1) @rpc(_returns=Container) def raise_validation_error(ctx): raise ValidationError(None, 'Invalid.') app = Application([HelloWorldService, ContainerService, ExceptionHandlingService], 'spyne.examples.django', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) hello_world_service = csrf_exempt(DjangoApplication(app))