Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible Django model filter by LogEntry by user added in ModelAdmin?
I am working with a blog site. I want to add some feature that like admin filter post can modify only that user added. I want to use Django builtin LogEntry model. Any can help me? -
How to return multiple items in a get_queryset function in Django?
So I have a web app where the user can enter their information, and eventually I want to display all of it, but at the moment this code right here class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) first_name = get_object_or_404(User,first_name=self.kwargs.get('first_name')) return Post.objects.filter(author=user).order_by('-published_date') It gives me an error, and it says User not found. I have tried add this to the end of the return statement .order_by('-published_date'),first_name However this did not work. This is the relevant urls.py file responsible for the user posts path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), This is the UserProfileInfo model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) description = models.CharField(max_length=150) image = ProcessedImageField(upload_to='profile_pics', processors=[ResizeToFill(150, 150)], default='default.jpg', format='JPEG', options={'quality': 60}) joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField( default=False) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And here is the relevant bit of the user-posts.html <div class="sidebar"> <p class="active" href="#">{{ view.kwargs.username }}</p> <button class="commentbtn"><a class="aclass" href="#">Connect with {{ view.kwargs.username }}</a></button> <p>{{ view.kwargs.first_name }}</p> <p>Lorem</p> </div> I want to be able to display the first name of the person in the ```{{ view.kwargs.first_name }}, however everything I have tried has failed to work I expected no … -
python django 2.2.4 ImportConfigured Error in urls.py
Question When I ran Django web server with 'python manager.py runserver', some error happened. It seems like [django.core.exceptions.ImproperlyConfigured: The included URLconf 'myproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.] Project tree is like below: root project myapp: __init__.py urls.py views.py myproject: __init__.py urls.py settings.py uwsgi.py manage.py __init__.py myproject/urls.py code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls', namespace='myapp')), ] myapp/urls.py code: from myapp import views from django.urls import path urlpatterns = [ # path('/', views.Home.as_view(), name='home'), path('signup/', views.Signup.as_view(), name='signup'), path('signin/', views.Signin.as_view(), name='signin'), path('signout/', views.Signout.as_view(), name='signout'), path('make_csr/', views.MakeCSR.as_view(), name='make_csr'), path('upload_csr/', views.UploadCSR.as_view(), name='upload_csr'), path('publish_cer/', views.PublishCER.as_view(), name='publish_cer'), ] Detailed error message: (cert_mgmt) C:\Users\wenca\Desktop\Python\virtual_environment\cert_mgmt\python\Src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Program Files\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper … -
SQL injection in Django Update Radiolist - Burp Suite
I'm new to programming. I have developed a Web application using python django framework. I have a particular view that updates the status of a particular row in the database from active to inactive and vice versa. and i have used html forms (Radiolist) and django templates in the hmtl page to create a front end. I have used Django's ORM - Update method to update the fields accordingly. But when I run a security audit using Vega security audit tool, I get an alert saying that there is a possible sql injection. I have tried everything but this error doesn't seem to go this is the html code <form class="" action = "{% url 'CHApp_new:update_statement' %}" method="post"> {% csrf_token %} <table class="table table-striped table-dark two" align="center"> {% for x in sobjects %} <tr> <td>{{forloop.counter}}</td> <td>{{x.statement}}</td> {% if x.status == 'y' %} <td>Active</td> {% else %} {% if x.status == 'n' %} <td>Inactive</td> {% endif %} {% endif %} <td style= "text-align:center"><input id= "{{forloop.counter}}" type="checkbox" name= "{{forloop.counter}}" value={{x.id}}></td> <input type="hidden" name="radiolist" value="{{forloop.counter}}"> </tr> {% endfor %} </table> <table align = "center"> <tr> <td><input type="submit" class = "btn btn-primary" name="Update" value="Cycle Activate/Deactivate"></td> </tr> </table> </form> and this is the django view. … -
Is there a way to get the url of a particular image from a django formset?
The challenge I'm facing right now is that I can't seem to display a particular image saved using formset by using the code {{items.images.url}} on my django template. I want to display the first image Before I edited my model to have a separate class to hold my advert images, I could display a particular image using {{items.image_1.url}} but now I can't. I have tried media/{{items.images.values.first.image}}, it worked but I don't think it's the right way to go about it, what if I want to display just the second image on the formset, then that code won't work. Please help. My models class Advert(models.Model): """All adverts""" STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=49) description = models.TextField() price = models.PositiveIntegerField() date_created = models.DateTimeField(auto_now_add=True) date_posted = models.DateTimeField(auto_now=True) category = models.ForeignKey( Category, related_name='advert', on_delete=models.DO_NOTHING) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ['-id'] def __str__(self): return self.title class AdvertImage(models.Model): advert = models.ForeignKey( Advert, related_name='images', on_delete=models.CASCADE) image = models.ImageField( upload_to='product_pictures') def __str__(self): return self.advert.title My views def view_all(request): """View All view""" view_all_list = Advert.objects.all().order_by('date_posted') context = { "view_all_list": view_all_list } return render(request, 'view-all.html', context) My template <!-- list BEGIN --> {% for items in vehicle_list %} <a> <img … -
How to solve method not allowed (Post) http error 405
Codes in views class UpdateVote(LoginRequiredMixin,UpdateView): form_class = VoteForm queryset = Vote.objects.all() def get_object(self,queryset=None): vote = super().get_object(queryset) user = self.request.user if vote.user != user: raise PermissionDenied('can not change another user vote') return vote def get_success_url(self): movie_id = self.object.movie.id return reverse('core:movie_detail', kwargs={'pk':movie_id}) def render_to_response(self, context, **response_kwargs): movie_id = context['object'].id movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id}) return redirect(to=movie_detail_url) -
Auto increment field of model in viewset during saving
Episode model has episode_number field, which has to be auto incremented while creating new episode. Every story will have episodes with episode_number field starting with one. How to do that? Now I user have to manually enter episode_number. story_id comes from url class Episode(models.Model): title = models.CharField(max_length=255) cover = models.ImageField(upload_to=upload_location) story = models.ForeignKey(Story, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) episode_number = models.IntegerField(null=True) class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer permission_classes = [BasicAuthorizationPermissions] def get_queryset(self): story_id = self.kwargs['story_id'] return Episode.objects.filter(story=story_id) def perform_create(self, serializer): try: story = Story.objects.get(pk=self.kwargs['story_id']) except Story.DoesNotExist: raise NotFound if self.request.user != story.author: raise PermissionDenied return serializer.save(story=story) -
How to use (or open) args in python when some inputs are named and others are not?
I want to make a few user using create_superuser method. I am currently doing this: CustomUser.objects.create_superuser( 'amin@gmail.com', 'password', first_name='Amin', ) But I want to create more than one user. I did not want to give first_name, I would do this: a=[['user1@gmail.com', 'pass'], [user2@gmail.com', 'pass'], ] [CustomUser.objects.create_superuser(*user) for user in a] But in my case, in which I have a third input for which I need to put the name 'first_name', how can I do what I did in above? -
how to add quantity of products and update total in cart using django?
I have cart model and product model this code work fine to add each product one time into cart ,but I wanna be able to add quantity of a product and update the total after added but I'm not sure where I should add the quantity field any ideas ? My cart model :- class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() else: cart_obj = Cart.objects.new() new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self): return self.model.objects.create() class Cart(models.Model): products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) cart views.py file:- def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) context = { 'cart': cart_obj, } return render(request, "carts/home.html", context) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: item = Product.objects.get(id=product_id) except Product.DoesNotExist: print("show message to user, product doesn't exist") return redirect("carts:cart") cart_obj, new_obj = Cart.objects.new_or_get(request) if item in cart_obj.products.all(): cart_obj.products.remove(item) else: cart_obj.products.add(item) return redirect("carts:cart") I update the subtotal of the cart using m2m_changed signal and then using pre_save signal to add a fixed shipping cost … -
How to authenticate or logged in the user account with admin permission
I'm new to with django application, I want to check/login a users account without password through admin permission. Is there any built-in feature in Django? Please help or guide me on how to do that? Many thanks! This kind of feature provided by laravel in PHP here is the sample code of PHP: <pre> use Illuminate\Http\Request; use App\User; public function loginAsUser(User $user){ auth()->guard('admin')->logout(); auth()->guard('web')->loginUsingId($user->id); return redirect(route('user.dashboard')); } </pre> -
Local File Directory for Django
I have followed the Digitalocean website tutorial for deploying a Django site. I did it all through the Command Prompt, so all of my files (settings.py, index.html) were accessed through there. Is there a local file directory that I can access so that I can edit all of my files in in a text editor? I also want to easily add CSS files and to the folders. I have to keep on editing on the command prompt. -
How to get episodes from exact story
I have episode, which is related with story(foreign key) with url router = routers.DefaultRouter() router.register('', StoryView, basename='stories') router.register('episodes', EpisodeView, basename='episodes') View: class EpisodeView(viewsets.ModelViewSet): I need to get episodes of story. How to do that is this case? -
Shared domain hosting or private hosting?
i want to develop website based on Django framework and I am unable to decide whether i will need private hosting or public hosting as I will have to install python and many more dependencies. I want to know type of hosting for django based sites. I tried contacting contacting hostgator and hostinger. -
Django and Subprocess: Development Server is Terminated on signal.SIGTERM
I am using subprocess.Popen in a Django application. I then store the pid in a database. The user can then send a rest request to /api/task/task.id/stop/ in order to kill the task. This all works fine, except that when I kill the subprocess the Django development server is also terminated. How do I go about killing the subprocess without killing the dev server? I start my process like this: process = subprocess.Popen(["nohup {} {} {}".format(settings.PYTHON, "task.py", task.id) ], shell=True ) task.pid = process.pid task.save() And I am terminating it like this: os.killpg( os.getpgid(task.pid), signal.SIGTERM ) -
settigns django template variable before extending a template
in jinja2 this is possibe {% set needs_youtube_library = False %} {% extends 'layouts/basic_layout.html' %} as passing a variable into an extends, does not work in a different way afaik. now with django templates, this doesn't even seem to be possible at all, or am I missing something? -
schema design for ecommerce product
I am exploring models in django where I am trying to create a model for e-commerce product. The schema that I have designed is follow for now from django.db import models class Category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) total_stock = models.PositiveIntegerField(default=0) def __str__(self): return self.name class Attribute(models.Model): ''' attribute can be like color, material, size and many more ''' name = models.CharField(max_length=80) def __str__(self): return self.name class AttributeValue(models.Model): ''' Values for the selected attribute like for size attr the values can be Large, Medium, Small and etc ''' name = models.CharField(max_length=100) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10) discount = models.DecimalField(decimal_places=2, max_digits=10) stock = models.PositiveIntegerField(default=0) def __str__(self): return self.name class ProductAttribute(models.Model): ''' Associate Particular attribute to Particular product ''' product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self): return self.product.name class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to = 'pic_folder/') def __str__(self): return self.product.name My question is when i researched for scalable e-commerce product design(scalable in terms of better table relation and covering most of the factors in e-commerce), i saw various tables like ProductVariant, ProductVariantImage, ProductOptions and etc. So i got confused on those terminology. … -
Trying to get email activation to work, but it fails
Trying to get this tutorial to work in my app: https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef The 'uid' fails whether or not I include the .decode(). message = render_to_string('premium/activation_email.html', {'user':user, 'token': account_activation_token.make_token(user), #this fails both with the .decode() and without 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), }) mail_subject = 'Activate your membership account.' send_mail(mail_subject, message,'info@clinicpricecheck.com', [request.user.email]) These are the two errors: Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name Then if I add .decode(): str object has no attribute decode() here is my urls.py with the activate tag: path('activate/<uidb64>/<token>/', views.activate, 'activate'), my activate view is exactly the same as the one in the tutorial -
Django - KeyError: 'profile' - Trying to save the user profile with DRF and Ajax
I'm trying to save the user profile data with DRF and Ajax but I have an error KeyError. I was reading the DRF docs, especifically this part: Writable Nested Representations that is what i want but, doesn't work for me. I hope you can help me this is my serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user', 'avatar', 'dob', 'headline', 'country', 'location', 'cp', 'background', 'facebook', 'twitter', 'github', 'website',) read_only_fields = ('user', ) # I tried removing this part but, not work (In some forums say it) class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'is_active', 'user_permissions', 'groups', 'last_login',) read_only_fields = ('username', 'email', 'date_joined', ) def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.username = validated_data.get('username', instance.username) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.avatar = profile_data.get('avatar', profile.avatar) profile.dob = profile_data.get('dob', profile.dob) profile.headline = profile_data.get('headline', profile.headline) profile.country = profile_data.get('country', profile.country) profile.location = profile_data.get('location', profile.location) profile.cp = profile_data.get('cp', profile.cp) profile.background = profile_data.get('background', profile.background) profile.facebook = profile_data.get('facebook', profile.facebook) profile.twitter = profile_data.get('twitter', profile.twitter) profile.github = profile_data.get('github', profile.github) profile.website = profile_data.get('website', profile.website) profile.save() return instance my views.py class ProfileRetrieveAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticatedOrReadOnly, IsAuthenticatedOrReadOnly, ) lookup_field … -
I can't figure out how to serve Static Files using AWS Elasticbeanstalk
I have been working on this for two days straight and I can't figure it out. Any help would be appreciated. I'm using Python 3.6 running on 64bit Amazon Linux/2.7.7 of Elastic Beanstalk. This is my file structure: - analytics -- (a bunch of files that I think are irrelevant here) - db.sqlite3 - ecs_site -- __init__.py -- __pycache__ -- settings.py -- static -- css -- (a bunch of files - important) -- fonts -- (a bunch of files - important) -- images -- (a bunch of files - important) -- templates -- (a bunch of files that I think are irrelevant here) -- urls.py -- wsgi.py - manage.py - pages -- (a bunch of files that I think are irrelevant here) - requirements.txt In the settings.py file here's what's there: #STATIC_ROOT = os.path.dirname(__file__) STATIC_ROOT = os.path.join(BASE_DIR, "ecs_site", "static") #SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) #STATICFILES_DIRS = [os.path.join(SITE_ROOT, 'static/')] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' #STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ecs_site/static/'), os.path.join(BASE_DIR, 'ecs_site/static/images/'), #os.path.join(BASE_DIR, 'ecs_site/static/fonts/'), os.path.join(BASE_DIR, 'ecs_site/static'), os.path.join(BASE_DIR, 'ecs_site/static/images'), #os.path.join(BASE_DIR, 'ecs_site/static/fonts')] #STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static/'), os.path.join(BASE_DIR, '/static/images/'), #os.path.join(BASE_DIR, '/static/fonts/'), os.path.join(BASE_DIR, '/static'), os.path.join(BASE_DIR, '/static/images'), #os.path.join(BASE_DIR, '/static/fonts')] In the configuration file here's what I have (set within the AWS EB console): -
ImproperlyConfigured Circular Import error Django2 Python3
I continue to get this error even after updating syntax to django2/python3 compatible. No mis-naming that I can see after checking repeatedly. I have tried using url instead of path and django 1 but this still does not fix the issue hackuta/urls.py: from django.urls import include, path from django.contrib import admin from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('first_app/',include('first_app.urls'),namespace = 'first_app'), path('first_app/',include('django.contrib.auth.urls')), path('test/',views.TestPage.as_view(),name='test'), path('thanks/',views.ThanksPage.as_view(), name='thanks') Error displayed when trying to migrate: File "/home/bbwslayer/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 593, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'hackuta.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. How do I fix this issue for a smooth migration? -
How do I sort the user model by fields in the profile model (1: 1)?
skill_note_reputation is a field in the Profile model that has a 1: 1 relationship with Profileuser. How do I sort user models by skill_note_reputation values? user_list = User.objects.all () Thanks for letting me know how to fix it -
How can i switch from one app to another in Django while passing data?
I am writing a Django application and i got stuck at this line of code in html in one of my Django apps: <a href="{% url "order:order_page" request.cart %} "> ORDER </a> I want the word 'ORDER' to redirrect to a html page in another app while passing the data from 'cart'. How can i do that? (order is the second application, 'order_page' is the name in its view which renders the second html page and 'cart' is a data that i want to pass to it, because i want to display it) -
Vue Nuxt Auth Login Token not stored
I'm currently using a Django backend (with Django Restframework and djangorestframework-simplejwt Package for JWT Token authentication) and Nuxt as the frontend with the Nuxt auth module. Here is my auth part in the nuxt.config.js: auth: { strategies: { local: { endpoints: { login: { url: '/api-token-auth/', method: 'post', propertyName: 'token' }, logout: false, user: { url: '/user/', method: 'post', propertyName: false } logout: { url: '/api-token-logout', method: 'post' }, }, tokenRequired: true, tokenType: 'JWT', } } }, Unfortunately the login doesn't work on the client side. My login view successfully returns: { "refresh":"eyJ0eXAiOiJKV1QiLCJhbhUjOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU2OTc5MjM2NSwianRpIjoiZGZmYjAzNTAUjkwNGY5Zjk0ODdkYTYzMTQ2YmIxYWUiLCJ1c2VyX2lkIjoiZDMyOGMwYTAtMDU3YS00NDRkLWJlZjUtMTgwOGMyYmU0MzcwIn0.V4AHLHdKCAViVM-_vnOA3thOxgluJo0rP6S_qs8On2I", "access":"eyJ0eXAiOiJKV1jULHUhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTY5NzA2MjY1LCJqdGkiOiJjZDRhZjdjYHzjZTI0OTlmOTlhMTAzNjdkYTMzZWQxNSIsInVzZXJfaWQiOiJkMzI4YzBhMC0wNTdhLTQ0NGQtYmVmNS0xODA4YzJiZTQzNzAifQ.2I2LV3Lzu2WSFjA2OT_L4mXr5Qp0hb2RZF4mzuIYKP0" } I already tried to change the propertyName to access instead of token but also without success. But it has todo with that setting, because when I change to a different JWT package which only returns something like this (in the login view): { "token":"eyJ0eXAiOiJKV1jULHUhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTY5NzA2MjY1LCJqdGkiOiJjZDRhZjdjYHzjZTI0OTlmOTlhMTAzNjdkYTMzZWQxNSIsInVzZXJfaWQiOiJkMzI4YzBhMC0wNTdhLTQ0NGQtYmVmNS0xODA4YzJiZTQzNzAifQ.2I2LV3Lzu2WSFjA2OT_L4mXr5Qp0hb2RZF4mzuIYKP0" } Then it works just fine :/ -
Django + Apache + wsgi
I make app with Django and I wanna to host in my Raspberry Server, but chrome tell me Internall Error. Below my conf file: V-Host: <VirtualHost *:80> ServerAdmin gielas.g@gmail.com DocumentRoot /var/www/html/ptmeble ServerName www.ptmeble.pl ServerAlias ptmeble.pl CustomLog /var/www/logs/ptmeblepl.log combined ErrorLog /var/www/logs/ptmeblepl.log Alias /static /var/www/html/ptmeble/static <Directory /var/www/html/ptmeble/static> Require all granted </Directory> <Directory /var/www/html/ptmeble/ptmeblepl> <Files wsgi.py> Options FollowSymlinks </Files> </Directory> WSGIDaemonProcess ptmeble.pl python-path=/var/www/html/ptmeble/src:/home/pi/grzEnv/lib/python3.6/site-packages WSGIProcessGroup ptmeble WSGIScriptAlias / /var/www/html/ptmeble/ptmeblepl/wsgi.py </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet wsgi.py: WSGI config for ptmeblepl project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ptmeblepl.settings') application = Cling(get_wsgi_application()) apache2/error.log: [Sat Sep 28 23:13:12.390528 2019] [core:notice] [pid 29063] AH00052: child pid 30066 exit signal Aborted (6) Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' I don't know what I'm doing bad. Please someone help me -
Django Rest Framework Flatten nested self-referential objects
I have a problem with nested self-referential objects. I have field responses which is children of this Message. It looks like tree but I'd like do this in one level. Is it possible in a simple way? How can I solve this? It's my serializer: class RecursiveField(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class MessageSerializer(serializers.ModelSerializer): message_id = serializers.SerializerMethodField() sender_user_id = serializers.SerializerMethodField() sender_user_fullname = serializers.SerializerMethodField() sender_user_email = serializers.SerializerMethodField() read = serializers.SerializerMethodField() attachments = serializers.SerializerMethodField() responses = RecursiveField(many=True) class Meta: model = Message fields = [ 'message_id', 'sender_user_id', 'sender_user_fullname', 'subject', 'body', 'created_at', 'read', 'read_at', 'attachments', 'responses' ] My present result looks like this: { "results": [ { "message_id": 115, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Temat", "body": "<p>Wiadomość</p>", "created_at": "2019-09-28T19:33:40.846822Z", "read": true, "read_at": "2019-09-28T19:35:58.889000Z", "attachments": {}, "responses": [ { "message_id": 116, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Re: Temat", "body": "<p>Odpowiedź</p>", "created_at": "2019-09-28T19:35:52.485656Z", "read": true, "read_at": "2019-09-28T19:36:21.932000Z", "attachments": {}, "responses": [ { "message_id": 117, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Re: Re: Temat", "body": "<p>Odpowiedź do odpowiedzi</p>", "created_at": "2019-09-28T19:36:20.717966Z", "read": true, "read_at": "2019-09-28T19:36:20.714495Z", "attachments": {}, "responses": [], } ] } ] } ] } I'd like sth like this: { "results": [ { "message_id": 115, "sender_user_id": 1, "sender_user_fullname": "user1", "subject": "Temat", "body": …