Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rest-framework How to display links to images from three models
There are 3 django models: Basic model describing the job model: class Homework(models.Model): date_to = models.DateField(auto_now=False) date_created = models.DateTimeField(auto_now=True) lesson = models.CharField(max_length=100) group = models.TextField(max_length=10) body_text = models.TextField(default=None, null=True, blank=True) answer_text = models.TextField(default=None, null=True, blank=True) Job photo model: class Body_Images(models.Model): body_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) body_image = models.ImageField(upload_to='media/homework/body') And the model of the photo of the answers to the task class Answers_Images(models.Model): answer_homework = models.ForeignKey(Homework, default=None, on_delete=models.CASCADE) answer_image = models.ImageField(upload_to='media/homework/answers') There are also three serializers class GetHomeworkSerializer(serializers.ModelSerializer): body_image = GetHomeworkSerializerBodyImages(many=True) answer_image = GetHomeworkSerializerAnswersImages(many=True) class Meta: model = Homework fields = ('date_to', 'date_created', 'lesson', 'group', 'body_text', 'answer_text', 'body_image', 'answer_image') class GetHomeworkSerializerAnswersImages(serializers.ModelSerializer): answer_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Answers_Images fields = ('answer_homework', 'answer_image',) class GetHomeworkSerializerBodyImages(serializers.ModelSerializer): body_homework = serializers.RelatedField(source='Homework', read_only=True) class Meta: model = Body_Images fields = ('body_homework', 'body_image') I get an error when trying to get data Got AttributeError when attempting to get a value for field body_image on serializer GetHomeworkSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Homework instance. Original exception text was: 'Homework' object has no attribute 'body_image'. How can I get links to images from Body_Images and Answers_Images in one request? -
How to pass a model instance from one function to the next in Django to prevent hitting the database repeatedly
In the below example you can see that get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) is called three times and hits the database three times. How do I call it only once and pass it around? class InitializeAMAUser(ChoSaaSacLoginRequiredMixin, FormView): template_name = 'components/form.html' def get_form(self, form_class=None): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return AmaUserInitializationForm(city=ama.city, request=self.request, email=ama.email, phone = ama.phone, **self.get_form_kwargs()) def get_success_url(self): ama = get_object_or_404(Ama, uuid=self.kwargs.get('uuid')) return ama.get_absolute_url() def form_valid(self, form): form.save() messages.add_message(self.request, messages.SUCCESS, 'User created Successfully') Activity(actor=self.request.user, verb='Initialized Ama User Login') return super().form_valid(form) -
django chat server i get not found on the socket
This is the error. :( [14/Nov/2020 14:19:54] "GET /chat/lobby/ HTTP/1.1" 200 1649 Not Found: /ws/chat/lobby/ [14/Nov/2020 14:19:54] "GET /ws/chat/lobby/ HTTP/1.1" 404 2708 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 51974) Traceback (most recent call last): File "/usr/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/usr/lib/python3/dist-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/lib/python3/dist-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- i dont know where I got this bug and why do i get it and how to connect the socket in my server import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) my routing.py from django.urls import re_path from . import consumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumer.ChatConsumer.as_asgi()), ] views.py from django.shortcuts import render def chat(request): return render(request, "chat/chat.html") def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) and urls.py from django.urls import path from . import views urlpatterns = [ path("", views.chat, name='index'), path('<str:room_name>/', views.room, name='room'), ] … -
put <elem> values in xml into an array
I have an xquery that returns this example of xml <root> <elem> xd </elem> <elem> lol </elem> <elem> hihi </elem> </root> how do I put the values of the element inside an array? example: x = [xd,lol,hihi] -
SORRY GUYS MAY YOU PLEASE ASSIST WITH THESE FEW ERRORS BELOW:
ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor f or 'User.user_permissions'. *** here is my code It made me stacked for some days without any solutions , please help on how to clear these errors below. username, password, email class Username(models.Model): username = models.CharField(max_length=100) class Password(models.Model): password = models.CharField(max_length=100) class Email(models.Model): email = models.CharField(max_length=100) # home class User(AbstractUser): is_user = models.BooleanField(default=False) is_ceo = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) class Use(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.ManyToManyField(Username, related_name='uses') password = models.ManyToManyField(Password, related_name='privates') class Ceo(models.Model): ceo = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.ManyToManyField(Username, related_name='supervises') password = models.ManyToManyField(Password, related_name='protections') email = models.ManyToManyField(Email, related_name='emailing_from') -
FieldError at / Related Field got invalid lookup: is_null
I'm creating a comment api but when i run the server give this error: FieldError at / Related Field got invalid lookup: is_null i don't know how to fix it. i'm creating a nested comment api. this is my code: #serializer class CommentSerializer(serializers.ModelSerializer): loadParent = serializers.SerializerMethodField("loadPrentData") def loadPrentData(self, comment): comments = Comment.objects.filter(parent=comment) comments_ser = CommentSerializer(comments, many=True).data return comments_ser class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created', 'loadParent'] class ProductSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField("loadProductComments") def loadProductComments(self, _product): _comments = Comment.objects.filter(product=_product, parent__is_null=True) _comments_ser = CommentSerializer(_comments, many=True, read_only=True).data return _comments_ser class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } #views: @api_view() def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) comments_ser = CommentSerializer(comment,many=False, read_only=True).data return Response(comments_ser, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) -
ImportError: cannot import name 'fields' from 'django.db.models.fields'
I got the following error during creation of django serializer. ImportError: cannot import name 'fields' from 'django.db.models.fields' (/home/user_name/anaconda3/lib/python3.7/site-packages/django/db/models/fields/__init__.py) and the serializer.py file is from django.db.models.base import Model from django.db.models.fields import fields, files from rest_framework import serializers from .models import Lead #create serializers for Lead class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' my current django version is 3.0.7. what is wrong in this code ? -
iterating image in dajngo not woking in table row using boostarp Carousel
i am loading images from database to my template the issue is that if i click sliding button of any image any row only sliding happens in the image of first row in table her is my code: HTML <table class="table table-striped table-hover"> <thead> <tr> <th> </th> <th>Room Type</th> <th>Price</th> <th>sleeps</th> <th>Total Rooms</th> <!-- <th>Room Feature</th> --> <th></th> </tr> </thead> <tbody> {% for room in rooms %} <tr> <td> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" id="ca"> <div class="carousel-item active"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1525253013412-55c1a69a5738?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1525253086316-d0c936c814f8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://images.unsplash.com/photo-1524641234638-4c303747c310?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <!-- <img style="width: 100%;" src="/static/image/{{room.room_image1}}" alt=""> --> </td> <td>{{room.room_type}}</td> <td>{{room.room_price}}</td> <td>{{room.sleeps}}</td> <td>{{room.room_available}}</td> <!-- <td></td> --> <td> <a href="{%url 'room_edit' room.id %}" class="edit"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="{%url 'room_delete' room.id %}" class="delete" onclick="window.mytest('{{room}}')" id="delcheck{{room}}" data-id="{{room.room_name}}"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> </td> </tr> {%endfor%} </tbody> </table> this my template table view hear when i click sliding button any row image sliding happens … -
Django annotate whether field is null
I want to annotate a datetime field to know whether it is null. Something like: Table.objects.all().annotate(date_is_null=XXX(YYY)).values(date_is_null, .....) What do I need to replace XXX(YYY) to check if the field is null? (I'm using .values().annotate() later for a Group By, so it must be in annotate first) -
The full request tracing is not complete for micro services via Jaeger UI
Appreciate your support for the below issue as I built my demo as the below steps, I built two microservices one by Django and the another by Go, Django send HTTP request to Go service, Jaeger tool is configured for UI tracing, Django tracing and Go tracing are separated in Jaeger tool and I do not know the reason although I received Django parent trace id in the request header and it is normal to be all Django request tracing including Go tracing as one request tracing in Jaeger, My Git repo: https://github.com/OmarEltamasehy/django-gotracing-example The below is Django code for calling Golang service def second_view(request): res = requests.get("http://localhost:5000/api/trial") ss = SomeModel.objects.create(name="asdasd") # r.set("soso", "mpmp") return HttpResponse('Hello man') from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.requests import RequestsInstrumentor from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor # for using redis from opentelemetry.instrumentation.redis import RedisInstrumentor from opentelemetry.sdk.trace import TracerProvider from opentelemetry import trace # implementing jaeger from opentelemetry.exporter import jaeger from opentelemetry.sdk.trace.export import BatchExportSpanProcessor trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) # create a JaegerSpanExporter jaeger_exporter = jaeger.JaegerSpanExporter( service_name='kokowawa', # configure agent agent_host_name='localhost', agent_port=6831, # optional: configure also collector # collector_host_name='localhost', # collector_port=14268, # collector_endpoint='/api/traces?format=jaeger.thrift', # collector_protocol='http', # username=xxxx, # optional # password=xxxx, # optional ) # Create a BatchExportSpanProcessor and add … -
Django get information from AJAX and render template
i've a problem with Django when i try to render a template after getting information from AJAX in a datatable. Can you help me? Here is the code: https://nopaste.xyz/?ccbe158548c85b5e#AxwFMud2UafGzzQVV3Gc7TKpzuo5UYxh6i7f675TRjDU I read i cannot use render template after using request from AJAX. -
Django- 404 error when embedding Youtube link via frontend post form
Introduction: Hello, I am new to Python and Django. Started my first blog project that enable users to create their blogs from the frontend. Problems: When I embed a youtube code in the form text area, it will return a 404 (see=image attached). On the other hand, there is no problem doing it via Django admin panel. Error given when youtube link is embedded via front end Here are the files. Views.py from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm from django.urls import reverse_lazy from django.shortcuts import render class HomeView(ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' def CategoryListView(request): category_menu_list = Category.objects.all() return render(request, 'category_list.html', {'category_menu_list': category_menu_list}) class PostDetailView(DetailView): model = Post template_name = 'post_detail.html' class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' class AddCategoryView(CreateView): model = Category template_name = 'add_category.html' fields = '__all__' class UpdatePostView(UpdateView): model = Post form_class = PostForm template_name = 'update_post.html' class DeletePostView(DeleteView): model = Post template_name = 'delete_post.html' success_url = reverse_lazy('home') def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts}) Urls.py from .views import HomeView, PostDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, \ CategoryListView from django.urls import … -
How to change the length of a django form field
I have a django form and I want to increase the length of a field html <td class='email_field'><span class='email_field'>{{ signup_form.email }}</span></td> css .email_field{ width: 350px; background-color: blue; } The background is coloured for 350px, but the field remains at the standard width (180px) What is wrong? -
Why can I run multiple django apps on the same ip address and port in debug mode?
I have a question. When I run a django app, he runs it in localhost: 8000. But if I rerun the app, it reruns it in localhost: 8000. Shouldn't it give error as the server (localhost) with that port (8000) is already busy? -
Is there a way to display json results in html in a nice way passed as a context from django view?
I have my django views which returns a json and passing it as context to my html template but unfortunately i can't find a good way loop through all the results in the html template (which uses Bootstrap 4 cdn) in a nice format with their thumbnails. Here is my view from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader from youtubesearchpython import SearchVideos import urllib.parse import json def index(request): if request.method == 'POST': query = request.POST['video_name'] search = SearchVideos(str(query), offset = 1, mode = "json", max_results = 10) ytresults = search.result() result_dict = json.loads(ytresults) context = { "result" : result_dict, } template_name = "youloader/results.html" return render(request, template_name, context) else: template_name = "youloader/index.html" return render(request, template_name) in my template i tried to pass only the context key so i can make sure the results are returned as expected. and here is the sample of my template {% extends 'youloader/base.html' %} {% block content %} <div style="padding-top: 20px"> {{ result }} </div> {% endblock %} and i have added the sample output -
Read Excel file from Memory in Django
I am trying to read an excel file from memory in django but keep getting the following error: NotImplementedError: formatting_info=True not yet implemented Here's the code: from pyexcel_xls import get_data def processdocument(file): print("file", file) data = get_data(file) return 1 when I am reading the same file from the local storage it works perfectly data = get_data(r"C:\Users\Rahul Sharma\Downloads\Sample PFEP (2).xlsx") I had a workaound solution in mind i.e. to save the uploaded file temporary in django os and then pass its URL to the function. Can I do that? -
Get word from URL or Title django
i want to get data from URL or article Title, for example if word Scorpio is in URL get somethings.. i try this but need full URL how to get this ? ** **{% if b in article.Title %} <h1>irakli</h1> {% endif %}** ** -
Passing zip object to "include" tag
I am trying to use include to embed one child template into parent template. In the parent template, suppose I need to pass variables as following ( as per the documentation here): {% include "table/order_item_modals.html" with item_change_form_list=item_change_form_list %} This works if the variable item_change_form_list is non-object type (such as string, numeric, of normal list, etc). If I want to pass a zip object, the above tag does not work. The reason I want to pass a zip object is because in my child template, I would like to use for loop over multiple lists in parallel, similar to a problem in this thread. Here, my variable item_change_form_list is defined as following in the view: item_change_form_list = zip (list1, list2, list3) Is it possible to pass a zip object in the include tag? Thanks. -
How to build Django queries to get list of data that satisfy many conditions?
I am trying to get a list of user_id by executing such sqlite query. SELECT u.user_id FROM users u WHERE u.role_id IN ( 1, 2 ) AND ( SELECT COUNT( * ) FROM purchases p WHERE p.user_id = u.id ) >= 1 AND ( SELECT tagged.tag_id FROM tagged INNER JOIN ( SELECT polled.answer_id FROM polled WHERE polled.user_id = u.id ) AS a WHERE a.answer_id = tagged.answer_id ) IN ( 1,2 ) How can run that sql using django orm? It's so hard to understand logic querysets like this... Users.objects.annotate(cnt=Count('purchases')).filter(Exists(Polled.objects.filter(user=OuterRef('pk')))).filter(cnt__gt=1).filter(role__in=[1, 2]).values_list('user_id', flat=True) ForeignKeys Relations Image Please help to build correct queries to get list of users that satisfy the conditions. Thanks. -
VSCode: Auto Format on Save
I use last version of VSCode, I am on Windows. When I do the following: {% extends 'base.html' %} {% block content %} <h1>Test About section</h1> {% endblock %} The code is automatically auto formatted when I save: {% extends 'base.html' %} {% block content %} <h1>Test About section</h1> {% endblock %} I am trying to deactivate it, but I have been unable to. This is what I've tried: CTRL + Shift + P: 'Disable all Extensions' and also 'Disable all Extensions in Workspace' In the Settings, the "editor.formatOnSave" is set to false (I have checked in User Settings, Settings for the Workpspace, Settings for Workspace JSON, etc) Disabled Jinja and Prettier Even tho I disabled my Extensions, when I hit [Save], the code is automatically formatted. I am not sure where the settings get imported. The project is new, I use Django, it's not linked to Git as well. What I am doing wrong? I've been reading articles for the past hour but the issue keeps occurring, did I miss a setting or does a hidden setting get imported somewhere? -
Error while downloading Excel from django with nginx
The django server served using nginx creates an excel file using pandas and BytesIO and then returns an HttpRespose as follows: data = export_data.export_data() response = HttpResponse(data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="Download.xlsx"' return response The template has an anchor that references to this view. This works fine with only django ( local testing ) but in production ( with nginx ) it gives me the following error : The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. NGINX CONFIG : upstream my-server { server unix:/tmp/gunicorn.sock fail_timeout=0; } server { listen 8000; server_name 11.11.1.3; keepalive_timeout 5; client_max_body_size 4G; access_log /my-server/logs/nginx.access.log; error_log /my-server/logs/nginx-error.log; location /static/ { alias /my-sever/static/; } location /media/ { alias /my-server/media/; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://my-server; } } Please help me in resolving this problem. Thank you in advance -
Group blocks from StreamField Wagtail
What am I trying to achieve will be easier to explain on lists. e.g list_of_blocks=[1,2,3,4,5,6,7,8,9,10,11,12] block_first_row = list_of_blocks[:3] block_rest_rows = [list_of_blocks[i:i+4] for i in range(3, len(list_of_blocks), 4)] block_rows = block_rest_rows.insert(0, list_of_blocks) I want to group blocks from StreamField and display them in template grouped by those rows. Is there a way to do it in my model? Or should i do it somehow in template.. I've tried to do: operate on StreamField as on list deconstuct StreamField.. then operate as on list -
Django Profile Update From is not Showing in the Templates
Hi all i am trying to create a form to update user profile but when i passed the instance of form to the template then nothing is shown in the template. forms.py class UserUpdateForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = KeepSafeUserModel fields = ['username','email','first_name','last_name'] class ProfilePicUpdateForm(forms.ModelForm): class Meta: model = KeepSafeUserModel fields = ['profile_image'] views.py @login_required() def profile(request): u_form = UserUpdateForm() p_form = ProfilePicUpdateForm() context = {'u_form': u_form,'p_form':p_form} return render(request,'profile.html',context) -
How can an array of object be posted using Django DRF if this objects contain a file and other data?
I want to post an array of objects via the Django DRF. The array comes from my React JS frontend and contains a file and other data: [{"image":"file object", "title_picture":"false"}, {"image":"file object", "title_picture":"true"},{"image":"file object", "title_picture":"false"}} I get the image via a FileFild and the title_picture via a CharField, with the code below (following this approach) I can post a image list, but I lose the title_picture i.e., i get something like that [{"image":"file object",}, {"image":"file object",}, {"image":"file object"}] ###Model### class Photo(models.Model): image = models.FileField(upload_to='audio_stories/') title_picture = models.CharField(max_length=100, null=True, default='some_value') ###Serializer### class FileListSerializer (serializers.Serializer): image = serializers.ListField( child=serializers.FileField( max_length=1000, allow_empty_file=False, ) ) def create(self, validated_data): image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img) return photo ###View### class PhotoViewSet(viewsets.ModelViewSet): serializer_class = FileListSerializer parser_classes = (MultiPartParser, FormParser,) http_method_names = ['post', 'head'] queryset=Photo.objects.all() Basically my question is how to post an array (list) of objects if these objects contain a file and some other data. -
get value from POST request in Django
I want to get the value of the key 'result' but every time I'm trying to get it it becomes empty if request.method == 'POST': result = request.POST after printing the result as you can see there is something there but when I'm trying to print: request.POST.get('result') or request.POST['result'] I'm getting an empty string