Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django orm cumulate values of count from group by function
I am new to Django and ORM, and I could not figure out ORM query for cumulate group by count value. Let's make a model simpler with columns with id, reg_dt. What I am trying to do is to get the number of registered users daily, and cumulate the counted number. id | reg_dt 1 | 2020-11-16 2 | 2020-11-16 3 | 2020-11-17 4 | 2020-11-17 5 | 2020-11-17 6 | 2020-11-18 Info.objects.values('reg_dt').annotate(tot_cnt=Count('reg_dt')).order_by('reg_dt') This orm query gives me reg_dt | tot_cnt 2020-11-16 | 2 2020-11-17 | 3 2020-11-18 | 1 And I finally want to make the result something like reg_dt | cumsum 2020-11-16 | 2 2020-11-17 | 5 2020-11-18 | 6 What would be the approach to get cumulated values? -
How to use Django ORM outside of a Django directory?
This is the file structure I want: ./overall_project_directory ./my_django_project ...django stuff ./my_gui ...gui stuff django_and_gui_meet.py Ideally, Django knows nothing about the GUI and the GUI knows nothing about Django for separation of concerns reasons. django_and_gui_meet.py is the only file that contains both Django models and GUI elements. I have read all of these questions: 1, 2, 3, 4, 5, 6. I've also looked at these templates: 7, 8. I've also looked at the Django Docs for using Django without an settings file. I still can't figure out if what I want to accomplish is possible. What I've Tried This is the current file structure I have for a test repo: django_standalone_orm/ ├── db # this is a django project made with `django-admin startproject db` │ ├── db │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── db.sqlite3 │ ├── __init__.py │ ├── manage.py │ ├── people │ │ ├── admin.py │ │ ├── apps.py │ │ ├── in_directory_ui.py # cannot load django models here │ │ ├── __init__.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── __init__.py │ │ ├── models.py │ … -
django-ckeditor: Is there a django config/setting to get <br> instead of <br />?
I'd like to have <br> elements from CKEditor instances like that, not <br />. I found this question with an answer, but I don't know where that code should go, in config.js? In my <script> element/JS file? And, actually, I want to know if I can use a config in CKEDITOR_CONFIGS to change this. Why the <br />? Also, why do I get a newline after the <br> element in the HTML? This causes me to get <br />\r\n in my model instance attributes and thus, in my database. The \r\n won't actually cause a problem, but it would be easier if I get rid of it; I think <br> should suffice. -
nginx 404 on root/homepage with Django + Gunicorn
I'm migrating my website from one host to another. The migration has been mostly 99% successful except for the fact that whenever I navigate to the home page of the site, I get nginx's 404 page. Every other page, static & media file is rendered properly. I've wracked my brain trying to find a solution but I haven't found any, let alone someone having a similar issue (instead, others have a working home page but 404 on all others). I have two different domains (one that my company owns, the other is owned by the city we're in). I've updated the DNS on the domain I own to ensure it's working with the new host and it is. When I navigate using the host (example.com) or the server's IP address, the website loads all pages correctly - except the homepage, which - again - returns nginx's 404. All other 404 errors display the 404 page I've set up via Django. Whenever this issue crops up, the gunicorn error log adds a line stating that the service is 'Booting worker with pid: ...' nginx.conf --> save for the paths and port, this conf is identical to the conf running on my … -
Django img src and variety of browsers / OS
I have html documents from django project on which pictures are displayed normally. <!DOCTYPE html> <html> <head> </head> <body> {% load static %} <img src="{% static '/img/bOGlcNacDB_Logo.png' %}"> </body> </html> This is working normally on Linux, Windows, Firefox/Chrome, but not on MacOS Safari/Chrome. Only Firefox. I found out that if I simply replace the src by a random image url, then it is working everywhere: <!DOCTYPE html> <html> <head> </head> <body> {% load static %} <img src="http://...jpg"> </body> </html> But then I am stuck and wonder if there is not something specific to django that I would not know. I tried: <img src="http://mywebsite/...png"> <img src="/...png"> <img src="../../static/img/...png"> No success. Thanks for helping to make this working on MacOS Safari/Chrome. -
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 # …