Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Blank pages after RollingUpdate for web deployment
We have a webserver based on Django+Gunicorn that is running in a kubernetes deployment. When we deploy a new version, we use RollingUpdate strategy. Any client that was connected to the webserver before the deployment gets a blank page. we suspect this could be due to an issue that is caused by browser cache, because it does seem to get resolved with a hard refresh. Is there a way to force refresh or store the cache in a different way so it won't impact the clients when we update the pods? any other suggestion will also be greatly appreciated -
Loading a pickle file into Django
I am working to develop on the website an application that built a picke file containing an object of a class defined on that project with specific data. I did not create that application and have no much knowledge of how pickle works. Now I want to move this app to a web version and I decided to go with django. To do not repeat the proces of creating those models I thought of directly load the pickle file in views.py and use the object already to make some operations. However, I am not sure how to make this load process as directly making the query: reg_model = pickle.load(open(r"C:\Users\...\pickle_file.pkl", 'rb')) throws error: An error occurred: No module named 'model' Error type: ModuleNotFoundError I started my django project from zero so I did not add any of the code from the app which creates the pickle. Should I? What am I missing? -
Django - website - ecommerce - ADD to cart ERROR
I am learning Python and Django and trying to create a Pilates Studio Website (as an e-commerce website, I'm following some tutorials) and I have a problem with ADD TO CART. I don't know why it doesn't work. When I click the button which supposes to add a product to a cart and I inspect the website I see that there is this error: POST http://127.0.0.1:8000/cart/add/ 500 (Internal Server Error) ` o = o("abort"); try { r.send(i.hasContent && i.data || null) } catch (e) { if (o) throw e }` Please, can you help me with it? I am totally stuck!!! I tried to add this product to a cart. I have tried to check if there are any problems with models etc. but everything looks good. I honestly have no idea what else can I do especially because I have just started learning Django and I don't know so much about it yet. views.py: `def cart_summary(request): return render(request, 'cart_summary.html', {}) def cart_add(request): # Get the cart cart = Cart(request) # test for POST if request.POST.get('action') == 'post': # Get stuff product_id = int(request.POST.get('product_id')) # product_qty = int(request.POST.get('product_qty')) # lookup product in DB product = get_object_or_404(Product, id=product_id) # Save to … -
Event type not found while using 2 consumers in a single django project
I have 2 consumers class KDPConsumer(JsonWebsocketConsumer): def connect(self): try: self.accept() self.user = self.scope["user"] print(f"User {self.user} connected.") if not self.user.is_authenticated: self.send_json({"error": "Incorrect authentication credentials."}) self.close() return # Join realm group self.realm = self.user.realm.name print(f"User {self.user.username} joined realm: {self.realm}.") async_to_sync(self.channel_layer.group_add)(self.realm, self.channel_name) except Exception as e: print(e) def disconnect(self, close_code): # Leave room group try: async_to_sync(self.channel_layer.group_discard)(self.realm, self.channel_name) print(f"User {self.user.username} disconnected from realm: {self.realm}.") except Exception as e: print(e) def receive_json(self, content, **kwargs): print(f"Received content: {content}") message = content.get("message") event_type = content.get("notification_type") if event_type == "send_notification_socket": self.handle_send_notification_socket(content) else: # Send message to room group self.send_message_to_channels_group(self.realm, message) def realm_message(self, event): try: print(f"Received realm message event: {event}") messages = event["message"] for message in messages: self.send_json( { "message": message, "user": self.user.username, } ) except Exception as e: print(e) @classmethod def send_message_to_channels_group(cls, realm, app_id): try: if app_id == AppTypes.umbrella: contracts = async_to_sync(cls.get_contracts)(realm) for contract in contracts: async_to_sync(channel_layer.group_send)(realm, {"type": "realm_message", "message": contract}) else: drafts = async_to_sync(cls.get_drafts)(realm) for draft in drafts: async_to_sync(channel_layer.group_send)(realm, {"type": "realm_message", "message": draft}) except Exception as e: print(e) @staticmethod @sync_to_async def get_contracts(realm): try: return Contract.objects.filter( created_by__realm__name=realm, module_type="Contract", kdp_status_done=False, created_on__gt=datetime.datetime.now() - datetime.timedelta(hours=1), ).all() except Exception as e: print(e) @staticmethod @sync_to_async def get_drafts(realm): try: return Draft.objects.filter( realm=realm, link__contains=settings.AWS_CLM_DOCUMENT_STYLUS_BUCKET_NAME, created_on__gt=datetime.datetime.now() - datetime.timedelta(hours=1), ).all() except Exception as e: print(e) def handle_send_notification_socket(self, … -
How to resolve uploading multiple images works, but the API call returns an empty array?
I have a Django REST API and I have a function for uploading multiple images in the admin of Django. And everything works fine: a user can upload multiple images and also the images are stored in the database table DierenWelzijnAdmin_animalimage But if I call: http://127.0.0.1:8000/api/animals/ I see an empty array returned: { "id": 30, "images": "https://dier.blob.core.windows.net/media/media/photos/animals/amphibiance_X04Eh6N_1z0N4Gs_9EPmeMA_6j3axdY_da4cpTO_2VAY67x_hcUVB7f.jpg", "animal_images": [] }, This is the model: import sys from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.contrib.auth.models import Permission from PIL import Image from django.db import models from django.conf import settings class AnimalImage(models.Model): animal = models.ForeignKey( 'Animal', related_name='imag', on_delete=models.CASCADE) image = models.ImageField(upload_to='media/photos/animals') def __str__(self): return f"Image for {self.animal.name}" class Animal(models.Model): images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) def img_preview(self): # new return mark_safe(f'<img src = "{self.images.url}" width = "300"/>') img_preview.short_description = "Huidige Foto" def img_previews(self): images = self.images.all() return mark_safe(''.join([f'<img src="{img.image.url}" width="100"/>' for img in images])) img_previews.short_description = "Thumbnails" class Meta: verbose_name = "Dier" verbose_name_plural = "Dieren" # permissions = [("set_display_flag", "Check name is display or not",)] super(Animal, self).save() def __str__(self): return self.name admin.py file: from django.contrib import admin from django.db import models from django.forms import RadioSelect from django.http import HttpResponseRedirect from django.urls import reverse … -
Unable to Filter Decimal128 Field in MongoDB with Django, But Can Filter Integer and String Fields
I'm working on a Django project using MongoDB as my database. I have a Product model with a Decimal128 field for storing product prices. I'm trying to filter products based on price, but I'm encountering issues when attempting to filter using the Decimal128 field. Here's the relevant part of my code: class FilterProducts(View): def get(self, request): try: category = request.GET.get("category") min_prices = request.GET.get("min_price") max_price = request.GET.get("max_price") all_products = Product.objects.all() if category: all_products = all_products.filter(category=category) if min_prices: all_products = all_products.filter(price__gte=min_prices) print(min_prices) if max_price: all_products = all_products.filter(price__lte=max_price) response = [ { "title": product.name, "category": product.category, "price": product.price.to_decimal(), "description": product.description, } for product in all_products ] return JsonResponse(response, status=200, safe=False) except Exception as e: return HttpResponseBadRequest(str(e), status=400) Below is the Model created for Product: class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.CharField(max_length=100) brand = models.CharField(max_length=100) shipping = models.CharField(max_length=100) description = models.TextField(max_length=500) price = models.DecimalField(decimal_places=2, max_digits=8) category = models.CharField(max_length=100) is_featured = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name The Issue: When I try to filter the Decimal128 price field, no results are returned, even when I know that matching data exists. Filtering based on integer or string fields works perfectly fine like Category. I've tried converting the … -
default=timezone.now in DateTimeField. What's timezone.now and what's the difference between it and auto_now_add?
class Post(models.Model): ... publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) GPT gave me this explanation: default=timezone.now: Sets the field to the current time by default but can be overridden when creating an object. auto_now_add=True: Automatically sets the field to the current time when the object is created and cannot be overridden. Is that it? I feel that this explanation isn't complete, that there's also something else. GPT says that timezone.now() in Django returns the current datetime in the current timezone as set in your Django project settings. Why to set datetimefield in the current timezone? I feel that there's some other difference besides just the ability to be overriden, or no? -
Video streaming with django from jellyfin
I made a streaming application with django from a jellyfin server, I use video js to play my video media. the problem is that when I try to play videos that are more than 1 hour long and longer it takes crazy time it seems that the video is first downloaded and then played and what's more I can't advance the media and put in the position I want, I first suspected a video js option called preload, so I tried the values 'none', 'metadata' and 'auto', but nothing there Actually, a colleague gave me a guess that maybe django doesn't support this kind of functionality! Can anyone confirm this? what could be the solution with django -
What is the better way to create multiple user types in Django? abstract classes or proxy models?
I want to create multiple user types in Django. The user types are 'Admin', 'Company' and 'Individual'. Should I use abstract models or proxy models for this requirement. I have already done this using proxy models. How would it be done using abstract models instead? Is any one of them better than the other? If so, how? Here is how I have implemented it using proxy models. models.py: class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) email = models.EmailField(max_length=150, unique=True, null=False, blank=False) role = models.CharField(max_length=50, choices=Role.choices, null=False, blank=True) is_staff = models.BooleanField(null=False, default=False) is_active = models.BooleanField(null=False, default=True) is_superuser = models.BooleanField(null=False, default=False) objects = AccountManager() USERNAME_FIELD = "email" def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_staff def has_module_perms(self, app_label): return self.is_superuser class Admin(User): objects = AdminManager() class Meta: proxy = True def custom_method_for_admin_only(self): return something class AdminProfile(models.Model): admin = models.OneToOneField( Admin, on_delete=models.CASCADE, related_name="admin_profile" ) first_name = models.CharField(max_length=50, null=False, blank=False) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=False, blank=False) def __str__(self): return f"{self.first_name} {self.last_name}" class Company(User): objects = CompanyManager() class Meta: proxy = True def custom_method_for_company_only(self): return something class CompanyProfile(models.Model): company = models.OneToOneField( Company, on_delete=models.CASCADE, related_name="company_profile" ) name = models.CharField(max_length=50, null=False, blank=False) is_verified = models.BooleanField(default=False, null=False, blank=True) logo = models.ImageField(upload_to="images/", null=True, blank=True) … -
creating a django project using 3.9.18 version in anconda prompt
i want to create a djongo project using python version = 3.9.18 . in my system i intalled python version is 3.12.4. how i can do this . my project related to the virsion is 3.8.18 i am expeting answer how i can (base) C:\Users\ACER\Desktop\newone>django-admin startproject new Traceback (most recent call last): File "C:\Users\ACER\anaconda3\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\ACER\anaconda3\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\ACER\anaconda3\Scripts\django-admin.exe_main.py", line 4, in File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\management_init.py", line 19, in from django.core.management.base import ( File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\management\base.py", line 14, in from django.core import checks File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\checks_init.py", line 26, in import django.core.checks.templates # NOQA isort:skip File "C:\Users\ACER\anaconda3\lib\site-packages\django\core\checks\templates.py", line 5, in from django.template.backends.django import get_template_tag_modules File "C:\Users\ACER\anaconda3\lib\site-packages\django\template_init_.py", line 44, in from .engine import Engine File "C:\Users\ACER\anaconda3\lib\site-packages\django\template\engine.py", line 7, in from .base import Template File "C:\Users\ACER\anaconda3\lib\site-packages\django\template\base.py", line 60, in from django.utils.html import conditional_escape, escape File "C:\Users\ACER\anaconda3\lib\site-packages\django\utils\html.py", line 11, in from django.utils.encoding import punycode File "C:\Users\ACER\anaconda3\lib\site-packages\django\utils\encoding.py", line 5, in from types import NoneType ImportError: cannot import name 'NoneType' from 'types' (C:\Users\ACER\anaconda3\lib\types.py)create a project and also how i can run the project. -
creation d'une authentification avec QR code en utilisant python Django
Comment crée une authentification avec QR code en utilisant python Django ? j'ai essayer le module django-qrauth, et ca pas marcher ainsi le module django_qr_code-4.1.0, et aussi ca pas marcher mais sans résultat ... quelqu'un peux m'aider a passer cette étape ? -
How to store user credentials temporarily for email verification in a django web app?
I want to create my own email verification flow, where the user enters his credentials and gets an OTP on the given email. When user enters the correct OTP within the time limit of 10 minutes, it will register the user and his credentials will be stored permanently in my database. How do I store the credentials temporarily for a time limit of 10 minutes ? I am thinking of storing the credentials after hashing using django_pbkdf2_sha256 library and storing it in my redis cache for a time of 10 minutes. If the user tries to enter it after this time, they will require a new OTP to register. Is this a good idea ? -
How to run periodic task in Django without using celery?
I need run a periodic task in Django to update some Prometheus metrics, then I realized that I cannot use celery, because celery runs in other workers while Prometheus metrics are in-memory objects. I am quite new to Django. If I do this in Go, I will start a thread (go-routine), but I am not sure if I should start a thread in Django as Django is like a block-box to me. If I should, then where to start to thread? In settings.py or elsewhere? -
django cannot redirect to index or admin after login
Can't redirect to the admin dashboard page or to the index after logging in even though the username and password are correct for views.py from django.shortcuts import redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.contrib import messages from auth.views import AuthView class LoginView(AuthView): def get(self, request): if request.user.is_authenticated: # If the user is already logged in, redirect them to the home page or another appropriate page. return redirect("index") # Replace 'index' with the actual URL name for the home page # Render the login page for users who are not logged in. return super().get(request) def post(self, request): if request.method == "POST": username = request.POST.get("email-username") password = request.POST.get("password") if not (username and password): messages.error(request, "Please enter your username and password.") return redirect("login") if "@" in username: user_email = User.objects.filter(email=username).first() if user_email is None: messages.error(request, "Please enter a valid email.") return redirect("login") username = user_email.username user_email = User.objects.filter(username=username).first() if user_email is None: messages.error(request, "Please enter a valid username.") return redirect("login") authenticated_user = authenticate(request, username=username, password=password) if authenticated_user is not None: # Login the user if authentication is successful login(request, authenticated_user) # Redirect to the page the user was trying to access before logging in if "next" in request.POST: … -
IntegrityError null value in column "home_id" of relation "WebApp_shorttermrental" violates not-null constraint for one Django model, not the other
I have two models with the same field. When I try to add a new instance to my database, one throws the error in the title, the other does not. models.py class Housesit(BaseModel): user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) home = models.ForeignKey(Home, on_delete=models.DO_NOTHING) title = models.CharField(max_length=256) <more fields> def __str__(self): return self.title class ShortTermRental(BaseModel): user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING) home = models.ForeignKey(Home, on_delete=models.DO_NOTHING) title = models.CharField(max_length=256) <more fields> views.py def add_housesit(request): active_user = request.user if not active_user.is_authenticated: return warn_redirect_login(request) new_housesit = Housesit.objects.create(user=active_user) return redirect("update_housesit", pk=new_housesit.id) def add_short_term_rental(request): active_user = request.user if not active_user.is_authenticated: return warn_redirect_login(request) new_short_term_rental = ShortTermRental.objects.create(user=active_user) return redirect("update_short_term_rental", pk=new_short_term_rental.id) urls.py urlpatterns = ( [ path("housesit/add/", views.add_housesit, name="add_housesit"), path( "short_term_rental/add/", views.add_short_term_rental, name="add_short_term_rental", ), ] I can't for the life of me figure out what's different between them and why one throws an error and the other doesn't. I'm fully migrated. Where else could the source of the discrepency possibly be? A simple solution would be to simply add "null=True" to my Home field, but I'm trying to figure out why it's broken. Any insight greatly appreciated! -
Django STATIC_URL value "/static/" vs "static/"?
I'm a junior dev and know how pathing works. I'm wondering what the paths for the directory that static files will be served from are if the values for are STATIC_URL="/static/" and STATIC_URL="static/". I know there is a different since the latter cause my app to not find the static files even though it's the default value. Thank you! -
nesting a serializer by year then month
class Transactions(models.Model): id = models.CharField(max_length=100, primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date = models.DateField() watch = models.CharField(max_length=100) purchase_price = models.IntegerField() sale_price = models.IntegerField() My Transactions model has a date field, purchase price, and sale_price. @api_view(['GET']) @permission_classes([IsAuthenticatedOrReadOnly]) def profit_chart(request): current_year = datetime.now().year queryset = Transactions.objects.filter(date__year=current_year).values(month=ExtractMonth('date'), year=ExtractYear('date')).annotate( profit=Sum(F('sale_price')) - Sum(F('purchase_price'))).order_by('month') serializer = ProfitChartSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) My view sorts transactions by the current year and month and then calculates the profit for that month. class ProfitChartSerializer(serializers.ModelSerializer): year = serializers.IntegerField() month = serializers.IntegerField() profit = serializers.IntegerField() class Meta: model = Transactions fields = ['year', 'month', 'profit'] The response I get from DRF is below. [ { "year": 2024, "month": 8, "profit": 5000 } ] The question I am trying to figure out is how I can manipulate the above response to look like below. [ year: 2024 data: { month: 8 profit: 5000 } ] -
ImportError: cannot import name 'RSAAlgorithm' from 'jwt.algorithms'
The RSAAlgorithm PyJWT algorithm method fails to import, but I do have the PyJWT installed. Error: ImportError: cannot import name 'RSAAlgorithm' from 'jwt.algorithms' I checked if the package is available by running this command: poetry show|grep -i pyjwt pyjwt 2.9.0 JSON Web Token implementation in... -
Handling long create update tasks in django
I have task to create routes. A route can be an object with origin, destination, type. Origin and Destination are just a FK from Location ojbect. Imagine I have 3 Locations, a, b, c. with three types, X, Y, Z. Then possible routes are. routes = [(a,b,x), (a,c,x), (b,a, x), (b,c,x), (c, a, x), (c, b, x) , (a,b,y), (a,c,y), (b,a, y), (b,c,y), (c, a, y), (c, b, y) , (a,b,z), (a,c,z), (b,a, z), (b,c,z), (c, a, z), (c, b, z) ] Now, Im able to create the routes with same output. but the problem I'm going to have more than 43 thousands unique locations, on estimation it is going to be around 5.5B unique routes based on 3 types. So I wanted to have a different type approach where I can resume the process if something fails. we don't have problem if this takes days, but there will be a problem if we are starting it from Zero if something fails. So any idea or concept would be appreciated. We are using Django application to handle this. here's the real Models and Code. Im planning to use this create_route functions in the background with the help of celery and … -
ADMIN_MEDIA_PREFIX
Want to deploy a Django project. I want to use S3 in my project. In the Django settings.py, should i use? Is it still working in Django 5.1 ADMIN_MEDIA_PREFIX = "static/admin/" Thanks very much. -
Django runserver_plus sometimes does not return a response without a delay or another incoming request
I am running a Django server locally using runserver_plus with --nothreading option. Sometimes I send a request to any endpoint (from different clients, like the React frontend running in Google Chrome, Django admin, or Postman) and it takes a very long time to respond (usually 1.5+ minutes). Let's call the first request #1. While this request is being processed, if I open another tab and open any endpoints - thus, send request #2, the server immediately responds to request #2 and then immediately responds to request #1. The processing of request #1 does not start executing until the processing of request #2 is finished. Django 4.2, Django extensions 3.2, DRF 3.15. -
Best framework for a custom ERP
I am currently working as a developer at a company that manufactures and sells machines and equipment intended for the industrial sector. This company is currently using an ERP tool with a QML frontend and a Python backend. This tool was not originally designed by a professional developer, and while it is still usable today, more and more features are becoming unsustainable in the long term. New developments are based on poor programming principles, which perpetuates the software's lack of maintainability. I am therefore considering the following question: what would be the best framework to develop from scratch an internal ERP for a company that would allow for several things: Complete tracking of the company's projects, from order confirmation to after-sales service, including the sharing of production plans between a design office and a workshop, and the production stages of orders An open-source framework that would allow a small team to work effectively on the same project and ensure the software's maintainability (the company is currently small, but the software should remain viable even if the company experiences significant growth) A cross-platform application (Windows, Mac, Android, iOS) that would ensure the software's security against cyber attacks Integration with external APIs … -
TypeError: BaseForm.__init__() got an unexpected keyword argument 'request'
I'm using Django to make an authentication page (login, registration...) While I writing the login program I ran into this error and I can't understand where it come from users/urls.py path('login/', CustomLoginView.as_view(), name='login'), users/views.py class CustomLoginView(LoginView): form_class = AuthenticationForm template_name = 'users/login.html' # shitty patch to bypass the error def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = super().get_form_kwargs() # Remove 'request' from kwargs if it exists kwargs.pop('request', None) return kwargs users/form.py User = get_user_model() class AuthenticationForm(forms.Form): identifier = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username, Email, or Phone', 'class': 'form-control', })) password = forms.CharField(max_length=50, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', 'data-toggle': 'password', 'id': 'password', 'name': 'password', })) remember_me = forms.BooleanField(required=False) # this is from ChatGPT that suggested it to me to debug the problem... but it didn't clarify my ideas much def __init__(self, *args, **kwargs): print("Initialization arguments:", args, kwargs) # Debugging line super().__init__(*args, **kwargs) def clean(self): identifier = self.cleaned_data.get('identifier') password = self.cleaned_data.get('password') if identifier and password: user = authenticate(username=identifier, password=password) if not user: try: user = User.objects.get(email=identifier) if not user.check_password(password): raise forms.ValidationError("Invalid login credentials") except User.DoesNotExist: # Try to authenticate with phone number try: user = User.objects.get(phone=identifier) if not user.check_password(password): raise forms.ValidationError("Invalid login credentials") except User.DoesNotExist: raise forms.ValidationError("Invalid login credentials") … -
how can I debug TypeError at /cart/add_cart/2/
The problem occurs when I try to add a product on cart just by clicking on add to cart button. the following bug occures. please cooperate with me in this regard thanks. How can I modify my code so that as i click on add to cart button. concerned product will added in cart page carts>views.py from .models import Cart from .models import CartItem, Product # Create your views here. def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) #get the product try: cart = Cart.objects.get(cart_id = _cart_id(request)) #get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.QUANTITY += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') def cart(request): return render(request, 'store/cart.html')```` **urls.py file** ````from django.urls import path from .import views urlpatterns = [ path('', views.cart, name='cart'), path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'),```` ] -
How to remove prefix e: from library spyne?
from spyne.application import Application from spyne.decorator import rpc from spyne.model.complex import ComplexModel from spyne.model.primitive import String, Integer from spyne.service import ServiceBase from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication from spyne import Unicode from django.views.decorators.csrf import csrf_exempt from lxml import etree class StatusData(ComplexModel): date = String class AppealsExternalStatusRequest(ComplexModel): messageId = String class DataWrapper(ComplexModel): AppealsExternalStatusRequest = AppealsExternalStatusRequest class AppealsService(ServiceBase): @rpc(DataWrapper, _returns=String, _body_style='bare', _operation_name='data') def receive_status(ctx, data_wrapper): print(data_wrapper) return "Received" soap_app = Application([AppealsService], tns='certain_path, in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) django_soap_app = DjangoApplication(soap_app) django_soap_app = csrf_exempt(django_soap_app) When I try to access to this via http://localhost/soap_api?wsdl, I receive in this format: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="path" xmlns:e="app.soap_service"> <soapenv:Header/> <soapenv:Body> <v1:data> <e:AppealsExternalStatusRequest> <!--Optional:--> <e:messageId>?</e:messageId> <e:statusData> <!--Optional:--> <e:date>?</e:date> <!--Optional:--> </e:statusData> </e:AppealsExternalStatusRequest> </v1:data> </soapenv:Body> </soapenv:Envelope> But I want to remove those e: prefixes, how that is possible? I added namespace in that case, it adds just other prefixes, and when I remove the namespace it adds e: prefixes.