Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get converted data from a model and with validating still works in Serializer in a concise way?
I have a serializer class look like this: class ReceiverInfoSerializer(ModelSerializer): create_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S') change_at = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S') user_id = serializers.IntegerField(required=False) receiver_phone_num = serializers.SerializerMethodField() def get_receiver_phone_num(self, instance): secret_phone_num = get_encryption_phone_num(instance.receiver_phone_num) if instance.receiver_phone_num else None return secret_phone_num receiver_phone_num is also a model field. These are plain text form phone numbers store in db table. Now, I want to retrieve it with * replacing middle 4 digits. Like, from 18812345678 converting to 188****5678. And this is what get_receiver_phone_num does. But when I use this SerializerMethodField, the validating for receiver_phone_num becoming invalid, cause it is read-only. In that way, I have to make converting in to_representation method instead like below: def to_representation(self, instance): res = super().to_representation(instance) res['receiver_phone_num'] = get_encryption_phone_num( instance.receiver_phone_num) if instance.receiver_phone_num else None return res and I do not think it is convenient cause I have to override it. Do you have any other workaround about this, please show me. -
python SerpScrap library import issue
Hi python community im facing python SerpScrap library import issue its not install enter image description here -
Ajax Repeating form several time
I am trying to add Ajax to my like button, it is working perfectly fine except that when I press the first time i is added when I press to unlike on more time it starts to automatically repeat itself several times and the more I press the more repeated like and unlike. This the first time I have seen this error before Here is the models.py class Post(models.Model): likes = models.ManyToManyField( User, related_name='liked', blank=True) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Here is the views.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True context = { 'total_likes': post.total_likes, … -
django-ckeditor: how to make carrige return insert a <br> instead of a new <p>?
In my CKEditor instances, I need ENTER to insert a <br> instead of a new <p> element, mainly because of the line separation. I found this question in the CKEditor forums and gave it a try (although they talk about fckconfig.js and not config.js), but it didn't work. Also found this question here, but I don't know how to apply the solution. How can I change this? -
Multiple Nested Serializers from Different Models with Django Rest Framework
My end goal is a json response similar to: { "card_id": "72e81de94dfc0373b006ca75e9c851a1", "item_id": "A.J.Burnett11610311269941028099991216231498183825508164480371614", "name": "A.J. Burnett", "playerattribute": { "team": "Marlins", "contact_l": 16, "power_l": 14 }, "playermarketlisting": { "buy": 420, "sell": 69, } }, Here is my model.py (simplified for the sake of this question): class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) item_id = models.CharField(max_length=120) # used for matching with attributes table name = models.CharField(max_length=120) class PlayerAttribute(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, ) team = models.CharField(max_length=120) contact_l = models.IntegerField() power_l = models.IntegerField() class PlayerMarketListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, ) buy = models.IntegerField() sell = models.IntegerField() Here are the serializers. class PlayerMarketListingForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerMarketListing fields = ( 'buy', 'sell', ) class PlayerAttributeForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerAttribute fields = ( 'team', 'contact_l', 'power_l' ) class PlayerProfileSerializer(serializers.ModelSerializer): playermarketlisting = PlayerMarketListingForProfileSerializer() playerattribute = PlayerAttributeForProfileSerializer() class Meta: model = PlayerProfile fields = ( 'card_id', 'item_id', 'name', 'playermarketlisting' 'playerattribute' ) Relevant view: class PlayerProfileView(viewsets.ModelViewSet): serializer_class = PlayerProfileSerializer queryset = PlayerProfile.objects.all() filter_backends = (filters.DjangoFilterBackend,) filterset_class = PlayerProfileFilter def get_queryset(self): queryset = super(PlayerProfileView, self).get_queryset() order_by = self.request.query_params.get('order_by', '') if order_by: order_by_name = order_by.split(' ')[1] order_by_sign = order_by.split(' ')[0] order_by_sign = '' if order_by_sign == 'asc' else '-' queryset = queryset.order_by(order_by_sign + order_by_name) return … -
Django channels with Spring Boot Websockets (StompSession) do not work
Hey there we want to use Django just to execute python code and use channels for the results. Implemented everything the websockets are not working as they should. If I try to send something from our Angular frontend to Django it works fine. And otherwise our Spring Boot StompSession Websockets work fine with other Spring Boot Applications and Angular. But Django and Spring Boot do not. What I can see from the Django server logs: WebSocket HANDSHAKING /ws/card-detection/ [127.0.0.1:53209] i'm in connect method WebSocket CONNECT /ws/card-detection/ [127.0.0.1:53209] i'm in receive method text_data: CONNECT This gets executed as soon as the websocket request comes in. The django consumer (without the prints that are logged above): class MyConsumer(WebsocketConsumer): groups = ["broadcast"] def connect(self): self.accept() def receive(self, text_data=None, bytes_data=None): self.send(text_data="Hello world!") def disconnect(self, close_code): pass From Spring Boot we send an base64 encoded image. But also everything else does not work. As you can see the text_data is just CONNECT. Spring Boot: StompSessionHandler sessionHandler = new CardDetectionStompSessionHandler(request, user, webSocketMessagingService); createStompClient().connect(djangoServiceWSPath, sessionHandler); } private WebSocketStompClient createStompClient() { WebSocketClient client = new StandardWebSocketClient(); WebSocketStompClient stompClient = new WebSocketStompClient(client); stompClient.setMessageConverter(new MappingJackson2MessageConverter()); return stompClient; } The stomp session handler to give you an idea how it looks. … -
ModuleNotFoundError: No module named 'register'
I am working on a Django project. I am working on the register page. When I try to import my register/views.py to my mysite/urls.py file I get an error message. ModuleNotFoundError: No Module named 'register'. Both files are are in the same directory. from django.contrib import admin from django.urls import path, include from register import views as v -
DJANGO initial values in form not shown in template (some do some don't)
I have these Models, Tipos, Prioridad and Estado, related to Tarea as defined below: class Tipos(models.Model): tipo = models.CharField(max_length=16, verbose_name='tipo') abrv = models.CharField(max_length=4, null=True, blank=True, default='') class Meta: verbose_name = "Tipo" verbose_name_plural = "Tipos" def __str__(self): return self.tipo class Prioridad(models.Model): prioridad = models.CharField(max_length=16, verbose_name='prioridad') abrv = models.CharField(max_length=4, null=True, blank=True, default='') orden = models.IntegerField(u'orden', blank=False) class Meta: verbose_name = "Prioridad" verbose_name_plural = "Prioridades" def __str__(self): return self.prioridad class Estado(models.Model): estado = models.CharField(max_length=16, verbose_name='estado') abrv = models.CharField(max_length=4, null=True, blank=True, default='') class Meta: verbose_name = "Estado" verbose_name_plural = "Estados" def __str__(self): return self.estado class Tarea(models.Model): numtar = models.AutoField(primary_key=True) cliente = models.ForeignKey(User, related_name='user_cliente', null=True, on_delete=models.DO_NOTHING) apoyo = models.ForeignKey(User, related_name='user_apoyo', null=True, on_delete=models.DO_NOTHING) asignado = models.ForeignKey(User, related_name='user_asignado', null=True, on_delete=models.DO_NOTHING) descorta = models.CharField(max_length=140) deslarga = models.TextField(max_length=8195) estado = models.ForeignKey(Estado, null=True, on_delete=models.SET_NULL) tipo = models.ForeignKey(Tipos, null=True, on_delete=models.SET_NULL) prioridad = models.ForeignKey(Prioridad, null=True, on_delete=models.SET_NULL) creacion = models.DateTimeField(auto_now_add=True) revision = models.DateTimeField(auto_now=True, blank=True) cierre = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = "Tarea" verbose_name_plural = "Tareas" def __str__(self): return '%s' % (str(self.numtar)) and I call the following view: @login_required(login_url='/login') def newincid_view(request): perfil = ExUserProfile.objects.get(user=request.user) prioridad_media = Prioridad.objects.get(prioridad='Media') estado_abierta = Estado.objects.get(estado='Abierta') tipo_incidencia = Tipos.objects.get(tipo='Incidencia') datos_apertura = {'cliente': perfil.user, 'tipo': tipo_incidencia, 'prioridad:': prioridad_media, 'estado': estado_abierta } if request.method == 'POST': form = newincidForm(request.POST,initial=datos_apertura) if form.is_valid(): … -
Stylesheet location reference (?) causing Django NoReverseMatch error
I am currently working on a project in Django and I am having a strange issue. Before I go in depth about the details, here are the html documents and python functions in question: def editpage(request, name): page = util.get_entry(name) #Imported forms as django_forms as not to interfere with forms.py class WikiEditForm(django_forms.Form): title = django_forms.CharField(initial={"title":name}, label='Title:', required=True, widget=django_forms.TextInput(attrs={'placeholder':'Title'})) body = django_forms.CharField(initial={"body":page}, widget=django_forms.Textarea(attrs={'placeholder':'Enter Markdown Content','style':'text'}), required=True, label='Body') if request.method == "GET": search_form = forms.SearchWikiForm() return render(request, 'encyclopedia/editpage.html', { "search_form":search_form, "wiki_edit_form":WikiEditForm(), }) else: search_form = forms.SearchWikiForm() wiki_edit_form = WikiEditForm(request.POST) if wiki_edit_form.is_valid(): page_content = util.get_entry(name) util.save_entry(name, page_content) return HttpResponseRedirect(reverse('encyclopedia:wikipage', name)) layout.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'encyclopedia:findpage' %}" method="get"> {% csrf_token %} {% block search %}{% endblock %} </form> <div> <a href="{% url 'encyclopedia:index' %}">Home</a> </div> <div> <a href="{% url 'encyclopedia:newpage' %}">Create New Page</a> </div> <div> <a href="{% url 'encyclopedia:randompage' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> page.html: {% extends "encyclopedia/layout.html" … -
How to read list in django template
Could someone shed a light to help me to solve this nested list problem in Django template. I come across a list as such summary = [['Summary 1 CODE018'], [['Directory/File Name', 'Result']], [[['dir/var1/file1.txt', 'pass'], ['dir/var2/file2.txt', 'pass'], ['dir/var1/file3', 'pass'], [[['null']]]] How do I loop the above list so that I can get a table such as the first index is the table title, index1 is the table title and the rest (except when is it null) is the table body? Please take note that the last item could be [[['null']]] or [[['null', 'Info on directory CODEA18']]] which should be skip when null is detected. Expected: Summary 1 CODE018 Directory/File Name Result dir/var1/file1.txt pass dir/var2/file2.txt pass dir/var3/file3.txt pass My faulty code as below <table id="myTable"> {% for list in summary %} <tr> <td> {{ list.0 }} </td> <tbody> <td> {{ list.0.0 }} </td> <td> {{ list.0.0.0 }} </td> </tbody> </tr> </table> -
Django - How to change the column name after do query (objects.filter)?
I got this query: flight_list = FlightScheduleV2.objects.filter(departure_airport = departure_airport, arrival_airport = arrival_airport, departure_scheduledtime__gte = CURRENT_TIMESTAMP ).values("key", "flightnumber", "departure_scheduledtime") Obviously, it would return something like this: {'key': ......., 'flightnumber': ....., 'departure_scheduledtime':....} However, the front-end expects to receive something like this {'flight_id' : ....., 'flight_number': ...., 'departure_time': ....} Literally, I need to change the key name of the result, however, I did not know which Django function could do so. -
Implement Ajax in a Django Project not working properly
I am trying to implement a like button to my blog post using Ajax, I am facing an error which I am unable to fix so I started from scratch more than once with the following steps: Created Post model and Like model Added the views which is currently working perfectly fine when I click like and unlike I took the like section from the post_detail.html and added it in a separate html like_section.html added the ajax with the correct values Now my problem is that when I press the like button a new page is opened with ajax output {"form": "....(html and ajax codes repeated)......"} How do I fix this error so that I can submit a like without refreshing the page? Here are the models for Posts.py class Post(models.Model): ---------other attributed like: title, content, author, date_posted, slug----- likes = models.IntegerField(default=0) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Here are the views: def like_post(request): user = request.user if request.method == 'POST': post = request.POST.get('post_id') post_obj = Post.objects.get(id=post) current_likes = post_obj.likes if user in post_obj.liked.all(): post_obj.liked.remove(user) current_likes = current_likes - 1 else: post_obj.liked.add(user) current_likes = current_likes + 1 post_obj.likes=current_likes post_obj.save() like, created = Like.objects.get_or_create(user=user, post_id=post) if not … -
H18 error occurs when a POST request is sent from django to a server hosted by Heroku
I made an API for writing posts including image using django rest frameworks. We then hosted this server in heroku and used the cloudinary to store the image. But whenever I send a POST request to this API, the following error is sent from heroku. sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/feed/post" host=coatcode.herokuapp.com request_id=c39478d9-b8e3-4b25-9b5f-2a9a04bc87b0 fwd="221.168.22.204" dyno=web.1 connect=1ms service=398ms status=503 bytes=484 protocol=https When I searched, I realized that this error was a matter of speed or image capacity. Then how can I improve my django code to speed up and solve this error? Here's my code. views.py class CreatePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(owner=self.request.user) def create (self, request, *args, **kwargs) : super().create(request, *args, **kwargs) return Response({'success': '게시물이 저장 되었습니다.'}, status=201) serializers.py class PostSerializer (serializers.ModelSerializer) : owner = userProfileSerializer(read_only=True) like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() images = ImageSerializer(read_only=True, many=True) liked_people = LikeSerializer(many=True, read_only=True) tag = serializers.ListField(child=serializers.CharField(), allow_null=True, required=False) comments = CommentSerializer(many=True, read_only=True) class Meta : model = Post fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data, created_at=str(datetime.now().astimezone().replace(microsecond=0).isoformat())) for i in range(1, 6) … -
Creating a Bootstrap Carousel in Django project, Can click on prev
I am trying to create a carousel in my django project using bootstrap. I am trying to the carousel with captions. I am using a for loop t go through my data. I can click next, but I cannot click on previous. Any help? thanks **<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleCaptions" data-slide-to="1" ></li> <li data-target="#carouselExampleCaptions" data-slide-to="2" ></li> </ol> {% for post in slider_posts %} <div class="carousel-inner"> <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ post.image.url }}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> {% for tag in post.tag.all %} <button class="btn btn-info"><a class="cat" href="{% url 'tag_detail' tag.slug %}">{{ tag.title }}</a></button> {% endfor %} <a href="{% url 'detail' pk=post.pk slug=post.slug %}"><h4>{{ post.title }}</h4></a> <p>{{ post.content | truncatechars:150 }}</p> <div class="date"> <a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> {{ post.publishing_date}}</a> <a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a> </div> </div> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleCaptions" 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="#carouselExampleCaptions" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div>** -
django-ckeditor: How can I limit TextColor and BGColor choices in toolbar?
This is my CKEDITOR_CONFIGS in settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom': [ ['Italic', 'Underline'], {'name': 'colors', 'items': ['TextColor', 'BGColor']}, ] }, } That's all I need for now. However, I'm getting a whole lot of color choices for TextColor and BGColor, and I want to limit them to a very specific set of colors. Is there a way in which I can choose the colors that I want to be available? I can't find how to customize that. -
Editing is_staff permissions for Djnago admin panel
I want to edit the is_staff role permissions so that they are only capable of viewing the data on the admin panel and not making any changes, I want to give the support staff this role. I understand the is_staff has edit, add, delete and view permissions. How would I create a group so that I can add any new staff members to this group I am really new to django, so please explain in the simplest of manner -
Add Prometheus metrics outside manage.py - docker related
My manage.py looks like this: import os import sys from prometheus_client import start_http_server, Summary import random import time if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") s = Summary('request_latency_seconds', 'Description of summary') s.observe(4.7) # Observe 4.7 (seconds in this case) try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) If I run my django app using docker, I am able to see added Summary metrics. However, if I try to run Django management command, created metric object will be not added to Prometheus. I am basically trying to add many metrics the same way I did it with Summary, but I dont want my exposed port to be stopped (if I run loop inside manage.py, it will stop)... ideally, if I would be able to run management command (I will exec to running container, and run command like "python … -
AttributeError: 'str' object has no attribute 'likes'
I am trying to get the count of likes related to post so I created the following in the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.IntegerField(default=0) I am already able to get the no. of likes but I am trying a different method, I am just trying to know how the method works. Here is the views where I try to add to it when a like is made def like_post(request): user = request.user post = request.POST.get('post_id') current_likes = post.likes <------------Error coming from here if request.method == 'POST': post_obj = Post.objects.get(id=post) if user in post_obj.liked.all(): post_obj.liked.remove(user) current_likes = current_likes - 1 else: post_obj.liked.add(user) current_likes = current_likes + 1 post.likes=current_likes post.save() like, created = Like.objects.get_or_create(user=user, post_id=post) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post': post, } return redirect('blog:post-detail', slug=post_obj.slug) The issue now is that I am receiving AttributeError at /blogs/like 'str' object has no attribute 'likes' I have tried to fix it but I don't know how. The source of error is highlighted here: current_likes = post.likes -
Should I rewrite my code to make use of through fields?
I built the models in my Django projects before learning about through fields, and now I realize I could have made use of them. I'm wondering what the benefits of using through fields are, and if I am missing out on them with my model structure: models.py (non-relevant fields removed) class Language(models.Model): name = models.CharField(max_length=255) class Collaborator(models.Model): name = models.CharField(max_length=255, blank=True) language = models.ManyToManyField(Language, verbose_name="languages", related_name='language_collaborator_languages', blank=True) class Item(models.Model): name = models.CharField(max_length=255, unique=True) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_item_language', blank=True) class Document(models.Model): name = models.CharField(max_length=255) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_document_language', blank=True) class Dialect(models.Model): document = models.ForeignKey('Document', related_name='document_dialect_document', on_delete=models.CASCADE, null=True, blank=True) item = models.ForeignKey('Item', related_name='item_dialect_item', on_delete=models.CASCADE, null=True, blank=True) collaborator = models.ForeignKey('Collaborator', related_name='collaborator_dialect_collaborator', on_delete=models.CASCADE, null=True, blank=True) language = models.ForeignKey('Language', related_name='language_dialect_language', on_delete=models.CASCADE) name = models.CharField(max_length=255) To describe the conceptual data model: each instance of Items, Documents, and Collaborators, can all have multiple languages, and for each instance of these relationships I specify a dialect with the Dialect model. I use get_or_create() in views.py to generate instances of Dialect, in which I define the language field and one of the item/document/collaborator fields. (Note: If you are familiar with languages/linguistics, you might point out that I could rename the Language model as … -
Weblate Permission denied. Unable to stat ... 403 Forbidden
https://docs.weblate.org/en/latest/admin/install.html#uwsgi I have been following the installation procedure to install Weblate on Ubuntu 18.04.04 LTS. I have installed all the dependencies, python 3.6, and also had to setup a system unit called `celery-weblate.service': [Unit] Description=Celery Service (Weblate) After=network.target [Service] Type=forking User=weblate Group=weblate EnvironmentFile=/etc/default/celery-weblate WorkingDirectory=/home/weblate-env RuntimeDirectory=celery RuntimeDirectoryPreserve=restart LogsDirectory=celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target I also had to setup a weblate file in /etc/default for variables that are used in the daemon: # Name of nodes to start CELERYD_NODES="celery notify memory backup translate" # Absolute or relative path to the 'celery' command: CELERY_BIN="/root/weblate-env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="weblate.utils" # Extra command-line arguments to the worker, # increase concurency if you get weblate.E019 CELERYD_OPTS="--beat:celery --queues:celery=celery --prefetch-multiplier:celery=4 \ --queues:notify=notify --prefetch-multiplier:notify=10 \ --queues:memory=memory --prefetch-multiplier:memory=10 \ --queues:translate=translate --prefetch-multiplier:translate=4 \ --concurrency:backup=1 --queues:backup=backup --prefetch-multiplier:backup=2" # Logging configuration # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # … -
how to pass the address.pk as a parameter after the form has been successfully submitted in a django form?
I created an address form in a Django project and I have also created an AddressDetailView in views.py. When a user successfully submits the address form, I want to redirect the user into the address_details.html by passing the address.pk as the parameter. But I don't know how to pass that parameter. I keep getting an error as shown belong and I don't know how to fix it. this is the models.py for the address model route_name = models.ForeignKey(Route, on_delete=models.CASCADE) name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, blank=True, null=True) location = models.CharField(max_length=30, choices=LOCATION_CHOICES, default='NULL') username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) make_initial_location = models.BooleanField() def __str__(self): return self.name def get_absolute_url(self): return reverse('address-detail', kwargs={'pk': self.pk}) this is the Address form in forms.py: class Meta: model = Address fields = ['route_name','name', 'city','area','location','make_initial_location'] def form_valid(self, form): form.instance.username = self.request.user return super().form_valid(form) this is the Address creation view in views.py, this is where i wrote the code for redirecting to address-detail, it shows me that the error is in return redirect('address-detail') : @login_required def AddressCreateVeiw(request): form = AddressCreationForm() if request.method == 'POST': form = AddressCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your address has been successfully created!') return redirect('address-detail') return render(request, 'blog/address_form.html', {'form': … -
Editing comments from a post: NoReverseMatch while trying to edit comment of a post
I am quite new to Django and I am trying to edit the comments for a specific post. However, I am getting an error while running the code. My guess is that it has to do with the url path or the post_detail html file(I tried multiple ways on fixing it, but could not get it to work). NoReverseMatch at /post/3c6f50b5-195a-4868-8704-b50c7b127813/ Reverse for 'edit_comment' with arguments '(33,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/comment/edit/$'] Models.py: class Post(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) ... class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', ) comment = RichTextField() ... urls.py: urlpatterns = [ ... path('post/<uuid:pk>/comment/', AddCommentView.as_view(), name='add_comment'), path('post/<uuid:pk>/comment/edit/', EditCommentView.as_view(), name='edit_comment'), path('post/<uuid:pk>/comment/delete/',DeleteCommentView.as_view(), name='delete_comment'), ... ] views.py: class EditCommentView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment form_class = EditCommentForm template_name='blog/edit_comment.html' login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author ==self.request.user class DeleteCommentView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/delete_comment.html' fields= '__all__' success_url = reverse_lazy('blog_home') login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author == self.request.user def form_valid(self,form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) forms.py: class EditCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) widgets = { 'comment': forms.Textarea(attrs={'class': 'form-control'}), } post_detail.html: {% if not post.comments.all … -
Remove file from S3 Bucket django-storages
I have a Django app that I am hosting on Heroku and the media files are served from AWS. I have a model that looks like this: class MyModel(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to="images/") def __str__(self): return self.name And I use a function inside views.py to delete the instance of the image from the model AND the image from the server. def delete_single_image(image): if image.image: image.image.delete() image.delete() This was working when I run it locally, but it doesn't delete the image from the S3 bucket when I host it on heroku. What can I do to remove it from there also? -
Django: dynamically append query results to context inside of view
I need to access models' data associated with one particular model (let's say model1). What is frustrating is that my database structure does not contain foreign keys or things to easily relate to model1. The underlying issue is that I can't figure away to manually replace the append method to add value:key pairs into the context dictionary. Here is what I have so far: @method_decorator(login_required, name='dispatch') class PostDetailalerte_trend2(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): queryset = trend2.objects.all().values('reference') queryset2 = {} queryset3 = {} print(queryset) for object in queryset: queryset2.append(old_year2.objects.filter(Id = object['reference']).values('Qm3', 'Qm2', 'Qm1')) queryset3.append(demand_planning2.objects.filter(Id= object['reference']).values('ltplus1')) return render(request, 'detailstocktrend2.html', {'queryset': queryset, 'queryset2': queryset2, 'queryset3':queryset3}) ##how to replace the not working APPEND method?/ I have seen several example recommanding to manuall create the keys, however this is not an option because I cannot know in advance how big the dict will be. Any help or any alternative way to do that is welcome -
Run a function in Django after loading views
I want to run a python function when the user clicks a button, but I don't wanna run it before loading the template. For example in views.py def index(request): return render(request, "some_html.html") in some_html.html <form method="post"> <input type="button" id="run-button" value="RUN" name="run-button"> </form> And then when the users clicks the button "RUN", I wanna run a function, let's say doSomethingCool, how would it be? I'm wondering if it'd be like this on views.py def index(request): return render(request, "some_html.html") def doSomethingCool(request): if request.method == "POST" and "run-button" in request.POST: print("Some cool stuff") doSometingCool(request) Any ideas?