Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerfile in Python for Playwright Chromium, installing error
I am trying to add playwright with chromium to a django project. I modify my docker to include the installation of playwright with chromium. When i use docker-compose up --build and then execute the function that use playwright i get the following error: playwright._impl._api_types.Error: Executable doesn't exist at /usr/bin/chromium-1067/chrome-linux/chrome ╔════════════════════════════════════════════════════════════╗ ║ Looks like Playwright was just installed or updated. ║ ║ Please run the following command to download new browsers: ║ ║ ║ ║ playwright install ║ ║ ║ ║ <3 Playwright Team ║ ╚════════════════════════════════════════════════════════════╝ I checked the files inside my docker and in the path /usr/bin/ i found chromium-1071 installed. I dont know how playwright is checking for the specific path chromium-1067 and i also dont know why it installed chromium-1071. I need help with the correct implementation of playwright in my django project. This is my Dockerfile FROM public.ecr.aws/docker/library/python:3.9 ARG ENVIRONMENT=default ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apt-get update && apt-get install -y supervisor curl wget gnupg unzip RUN pip install playwright ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin RUN playwright install-deps chromium RUN playwright install chromium COPY start-container.sh /usr/local/bin/start-container.sh COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf RUN chmod +x /usr/local/bin/start-container.sh COPY requirements.txt /app/ RUN pip install --upgrade pip RUN pip install "setuptools<58.0.0" RUN pip install … -
template does not recognize base and does not display content
{% load menu %} <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %} {% endblock %} </title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <nav class="max-w-4xl mx-auto py-4 px-6 flex itens-center justify-between bg-blue-400 mt-1"> <div class="logo"> <a href="/" class="text-2xl text-white">Pedido Easy</a> </div> <div class="menu flex space-x-4"> {% menu %} </div> </nav> <div class="max-w-4xl mx-auto py-4 px-6"> {% block content %} {% endblock %} </div> </body> </html> O código acima mostra o arquivo "base.html" que é usado como template padrão para que as outras páginas possam ser feitas puxando o código dessa. Já o código abaixo mostra o arquivo "vendor_detaisl" que é a página de exibição do fornecedor do produto e seus produtos, o erro acontece quando é tentado mostrar os produtos que o fornecedor cadastrou,onde é mostrado apenas o nome do forncedor (usuário que cadastrou os produtos): {% extends 'core/base.html' %} {% block title %} {% firstof user.get_full_name user.username %} {% endblock %} {% block content %} <h1 class="text-2xl"> {% firstof user.get_full_name user.username %} </h1> <div class="flex flex-wrap"> {% for product in user.products.all %} <div class="product w-1/3 p-2"> <div class="p-4 bg-gray-100"> <a href="{% url 'product_details' product.category.slug product.slug %}"> {% if product.image%} <div class="image" mb-4> <img src="{{product.image.url}}" height="400" … -
Why is my form data not saved in database?
When I fill out the form in Django 4.2.3 the data is not saved in database (sqlite3). I didn't use {{ form }} because option to hide fields based on selected options is not working. models.py: from django.db import models opciones_entrega = [ (0, "Retiro en Tienda"), (1, "Reparto a domicilio") ] opcion_retiro = [ (2, "Retiro Local"), (3, "Retiro bodega") ] class Reparto(models.Model): opcion_entrega = models.CharField(max_length=1, choices=opciones_entrega, default="0") num_venta = models.IntegerField() fecha_venta = models.DateField() nombre_cliente = models.CharField(max_length=60) direccion = models.CharField(max_length=150) telefono = models.IntegerField() articulos = models.TextField(max_length=300) fecha_entrega = models.DateField() fecha_retiro = models.DateField() opcion_retiro = models.CharField(max_length=1, choices=opcion_retiro, default="2") observacion = models.TextField(max_length=200) def __str__(self): return self.nombre_cliente forms.py: from django import forms from .models import Reparto class RepartoForm(forms.ModelForm): opciones_entrega = [ (0, "Retiro en Tienda"), (1, "Reparto a domicilio") ] opcion_retiro = [ (2, "Retiro Local"), (3, "Retiro bodega") ] opcion_entrega = forms.ChoiceField(choices=opciones_entrega, widget=forms.RadioSelect) opcion_retiro = forms.ChoiceField(choices=opcion_retiro, widget=forms.RadioSelect) class Meta: model = Reparto fields = '__all__' widgets = { 'fecha_venta': forms.DateInput(attrs={'type': 'date'}), 'fecha_entrega': forms.DateInput(attrs={'type': 'date'}), 'fecha_retiro': forms.DateInput(attrs={'type': 'date'}), } views.py: from django.shortcuts import redirect, render from .models import Reparto from .forms import RepartoForm from django.http import HttpResponse, HttpResponseRedirect def home(request): if request.method == 'POST': form = RepartoForm(request.POST) if form.is_valid(): form.save() return redirect('vista') … -
Prefetching or Selecting a single model from a ManyToMany field for use in a Serializer
We have a model with a ManyToMany through table like such class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through="Membership", through_fields=("group", "person"), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) On our Group view we would like to create a single-model access to the Membership model based on request.user so that our serializer can access fields of the pivot table like class GroupSerializer(serializers.ModelSerializer): user_name = serializer.CharField(source='memberships.user.name') I have tried a query such as Group.objects.filter(user=request.user).annotate( request_user_membership=Subquery(Membership.objects.filter(group_id=OuterRef('id'), user_id=request.user.id)) ) so that I might be able to reference the single object like class GroupSerializer(serializers.ModelSerializer): user_name = serializer.CharField(source='request_user_membership.user.name') however it does not seem that you can use subqueries like this. This seems like a common problem so I was hoping you all might have some ideas. Any help is greatly appreciate -
why am I getting TypeError: string indices must be integers, not 'str' on Django Deserialization?
I'm trying out using AJAX to implement tags for Book Blog posts. I want to use TDD to check and make sure that they filter properly but am running into issues. Mainly when I try and Deserialize the JSONResponse content, it throws an error when I try and iter through it. error message: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\python.py", line 111, in Deserializer Model = _get_model(d["model"]) ~^^^^^^^^^ TypeError: string indices must be integers, not 'str' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\04_projects\01_Python\10_book_blog\posts\tests\test_views.py", line 103, in test_returns_filtered_posts for obj in decereal: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError test case that makes the error: def test_returns_filtered_posts(self): # makes one post with a tag and one post without t1 = Tag.objects.create(tag_name='test', group_name='general') p1 = Post.objects.create(book_title='test_book') p2 = Post.objects.create(book_title='test_book2') p1.tags.add(t1) # simulates clicking the 'test' tag response = self.client.post(reverse('ajax_post'), {'tag[]': ['test', 'general']}) # decerealizes the data decereal = deserialize('json', response.content) # print for debugging for obj in decereal: print(obj) # bad test case but not getting this far self.assertNotIn(p2, decereal) The view that is called: def ajax_call(request): data = serializers.serialize('json', Post.objects.all()) # … -
Django: how select items that do not have referencies from other items?
Assume, we have a model: class Critters(models.Model): name = models.CharField() parent = models.ForeignKey(Critters, blank=True, null=True, on_delete=models.CASCADE) In begin was some critters: id Name Parent == ======== ======== 0 Critter1 1 Critter2 2 Critter3 And then, some critters made a children: id Name Parent == ======== ====== 0 Critter1 1 Critter2 2 Critter3 3 Child1 0 4 Child2 1 I wand make a request for select all parents without childrens (i.e. no creatures with parents, and no parents with existing childrens): id Name Parent == ======== ====== 2 Critter3 I think it can be done with annotate and exact django's directives, but i'm dubt in stick how exactly i can make this... UPDATE1 Ofcourse, critter and child in field Name just for example, we can't filter table by Name. -
Image file not being uploaded to media file
I'm trying to display an input type="file" that accepts image files. When i upload the file through Django Admin, everything works (its uploaded to my media folder, and its successfully displayed on html) but when i do it through my html page, it doesnt go to media, and i can't display it. So i'm assuming the problem isnt with django but my settings.py or something with my html HELP create.html (to upload image) <label for="imgpreview" class="imglabel">Choose Image</label> <input accept="image/*" type='file' id="imgpreview" name="imgpreview" class="image-form" onchange="previewImage(event);"/> index.html (to display image) <div class="banner-image"><img id="model-img-display" src="{{item.image.url}}"></div> views.py (to save model) def create(request): if request.method == 'POST': title = request.POST['title'] image = request.POST['imgpreview'] category = request.POST['category'] brand = request.POST['brand'] color = request.POST['color'] clothes = Clothes(title=title, image=image, category=category, brand=brand, color=color) clothes.save() return render(request, "wardrobe/create.html") models.py class Clothes(models.Model): title = models.CharField(max_length=50) image = models.ImageField(default='', upload_to='wardrobe/') #wardrobe= media subfolder category = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) color = models.CharField(max_length=200, null=True, blank=True) deleted = models.BooleanField(default=False) settings.py MEDIA_URL='/media/' MEDIA_ROOT= BASE_DIR/'project5'/'wardrobe'/'media' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('wardrobe.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) EDIT: i changed my views.py following https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html instructions and now everything works! -
No reverse match with comments
I want to display my comment form in my page. However, every time i enter the page i get no reverse match error. Maybe there is something to do with form action, but honestly I have no idea what to do. Please help! views.py def single_blog(request, pk): news = News.objects.filter(pk=pk) comment_form = CommentForm() context = { 'title': 'Новость', 'news': news, 'comment_form': comment_form } return render(request, 'blog/single-blog.html', context) def save_comment(request, pk, new_pk): form = CommentForm(request.POST) if form.is_valid(): form.instance.new_id = new_pk comment = form.save() return redirect('single-blog', pk) models.py class Comments(models.Model): post = models.ForeignKey(News, on_delete=models.CASCADE) author = models.CharField(max_length=255, verbose_name='Автор') text = models.TextField(max_length=255, verbose_name='Текст') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') urls.py path('single-blog/<int:pk>', single_blog, name='single-blog'), path('save_comment/<int:pk>', save_comment, name='save_comment') html Leave a Reply <form class="form-contact comment_form" action="{% url 'save_comment' new_pk %}" id="commentForm"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ comment_form.author }} </div> </div> <div class="col-12"> <div class="form-group"> {{ comment_form.text }} </div> </div> </div> -
VSCode debugpy with dockerized django app
I'm trying to use debugpy with a dockerized django app - it connects momentarily then disconnects - I'm not sure why docker-compose.backend.yml: (the uplifty service below is the django server I want to attach to from vscode) version: '3' services: db: image: postgres platform: linux/amd64 container_name: uplifty-db environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" uplifty: build: context: . dockerfile: ./docker/Docker.server/Dockerfile image: uplifty env_file: .env container_name: uplifty volumes: - .:/code ports: - "8000:8000" - "5678:5678" depends_on: - db links: - db:postgres Dockerfile: FROM python:3.11.3 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ sudo && apt-get install -y \ git \ nginx \ postgresql-client \ supervisor RUN mkdir /code ADD docker /code RUN rm /etc/supervisor/supervisord.conf && \ ln -s /code/docker/Docker.server/supervisord.conf /etc/supervisor/supervisord.conf && \ rm /etc/nginx/nginx.conf && \ ln -s /code/docker/Docker.server/nginx.conf /etc/nginx/nginx.conf && \ mkdir -p /var/log/supervisor && \ mkdir -p /var/log/gunicorn && \ mkdir -p /code/logs/supervisord RUN groupadd -r app -g 1000 && \ useradd -u 1000 -r -g app -d /code -s /bin/bash -c "Docker image user" app RUN chown -R app:app /code && \ chown -R app:app /var/run && \ chown -R app:app /var/log/gunicorn RUN pip install psycopg2 RUN pip install poetry RUN pip install gunicorn ADD server/pyproject.toml … -
Django 4 Running some python codes/files outside views for specific request and returning the parameters as context before rendering template
I am relatively new to Django, while I am fine with loading static pages etc, I have an issue with complex dynamic content. I am designing a quiz, when a user answers a question, I would like to log some parameters into the database (correct or wrong, time taken for the response, etc). When the user clicks next, I want to analyse the data from the answer to the previous question, apply an algorithm and select the question and its parameters as context to the template so that the next question is loaded. So far, I have created a config.py that lets me take the parameters (context) from quiz.py and use them in views.py. Both config.py and quiz.py are in the main folder of the Quiz App. The problem I have is how to read and analyse the user session and data in my quiz.py so that I could apply the algorithm based on the user's previous answers and performance on the database. I have looked at many forums, videos, etc but not even sure if I am on the right path. I have looked at Middleware, Threading, using Celery, etc and I cannot get the user data from "request" … -
Django Define serializer for Model in relation using Foreign Key
I am having 3 models, Site which basically contains Site Details, Comments which contains the the comments and replies to a particular site and Files which contains all the attachments. I wanted to get all the necessary fields from Comments and Files Model, for which I am trying to use a Serializer in Site Details Models. Below is my models.py - **Site:** site = models.CharField(max_length=30, blank=False, null=False) approver = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_approver", blank=True, null=True) submitter = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_submitter", blank=True, null=True) **Files** site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name') **Comment** user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_name_comment') timestamp = models.DateTimeField(default=datetime.datetime.now) remarks = models.TextField(null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies') site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name_comment') My Serializer.py file are: **Comment** class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' **Files** class FileSerializer(serializers.ModelSerializer): class Meta: model = Files fields = '__all__' **Site** class SiteSerializer(serializers.ModelSerializer): remarks = CommentSerializer(many=True,read_only=True) attachment = FileSerializer(many=True,read_only=True) class Meta: model = Site fileds = '__all__' I am unable to get the Values of Files and Comment object, but I am not getting any error as well. What is the solution for this -
How to move django models from one app to another
So we have a django backend already in production with a reasonable amount of data.During the initial stages, we had a small team of two and we were also working with deadlines. I would also admit we were beginners and didn't follow best practices.Because of this,all our models were defined in one app.Now the project is messy and I also learnt it is not a good practice to have many models in one app.Now my question is,how can we move some of this models to new different apps in our project without running into migration issues or worse loosing the data? Our models also have a lot of relationships.Just for reference,we are using postgres databases. I have reasearched the internet for solution but haven't found a comprehensive approach to doing it.Most of the answers here also seems outdated.Some people also recommend to use south which is deprecated. -
I cannot get a list of CSV files and their headers at the same time
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from .models import CSVFile from .serializers import CSVFileSerializer import csv ... class CSVFileListView(APIView): def get(self, request, format=None): files = CSVFile.objects.all() file_data = [] for file in files: columns = self.extract_columns(file) # Извлекаем информацию о колонках file_data.append({ 'id': file.id, 'filename': file.file.name, 'uploaded_at': file.uploaded_at, 'columns': columns # Добавляем информацию о колонках в список файлов }) return Response(file_data, status=status.HTTP_200_OK) def extract_columns(self, file): with open(file.file.path, 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file) columns = next(csv_reader, []) # Извлекаем первую строку, содержащую заголовки колонок return columns class CSVFileDetailView(APIView): def get(self, request, file_id, format=None): try: file = CSVFile.objects.get(id=file_id) with open(file.file.path, 'r', encoding='utf-8') as csv_file: dialect = csv.Sniffer().sniff(csv_file.read(1024)) csv_file.seek(0) csv_data = list(csv.reader(csv_file, dialect=dialect)) columns = csv_data[0] data = csv_data[1:] response_data = { 'columns': columns, 'data': data } return Response(response_data, status=status.HTTP_200_OK) except CSVFile.DoesNotExist: return Response({'error': 'File not found'}, status=status.HTTP_404_NOT_FOUND) Error occurred while getting the list of all files using GET: UnicodeDecodeError at /api/v1/csv/files/ 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/csv/files/ Django Version: 4.1.5 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Exception Location: , line 322, … -
form element is not valid
I'm trying to make a form (without using django's template forms) but for some reason my forms are never valid when I try them. Here is my code: forms.py: class AddressForm(forms.Form): address_long = forms.CharField(max_length=500) class Meta: model = Address fields = ['address_long'] def save(self, commit=True): address = Address.objects.create() address.address_long = self.cleaned_data['address_long'] if commit: address.save() return address views.py: @login_required def add_address_view(request): if request.method == 'POST': form = AddressForm(request.POST) print(request.POST) if form.is_valid(): print("Valid") address = form.save() user_profile = request.user.userprofile user_profile.addresses.add(address) # Add to many to many field user_profile.save() return redirect('core:profile') # Redirect to the user's profile page else: form = AddressForm() return render(request, 'Test_site/add-address.html', {'form': form, 'countries': COUNTRIES}) And my html looks like this: ... <form method="POST" class="col-md-5 border-right"> {% csrf_token %} ... <div class="col-md-12"> <label class="labels">Address Long</label> <input name="{{ form.address_long.name }}" id="{{ form.address_long.auto_id }}" type="text" class="input-field form-control" placeholder="enter address line" value=""> </div> ... </form> When I try this on my local host I get this output from the print statements in the view function: <QueryDict: {'csrfmiddlewaretoken': ['my_generated_token'], 'address_long': ['Long address try']}> But no matter what I do it just doesn't pass the '.is_valid()' check. Also I can't look up on what 'form' holds, like trying to do form.cleaned_data['address_long'] causes a 'form … -
django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
I'm trying to get a queryset of unique values. Here is my model class Data_agent_account(models. Model): data_agent = models.ForeignKey(Data_agent, null=False, on_delete=models.PROTECT) date_entered = models.DateTimeField(db_index=True) type = models.BooleanField(null=False) # debit=False & credit=True amount = models.DecimalField(max_digits=12, decimal_places=2, null=True) desc = models.CharField(max_length=255) paid_on = models.DateTimeField(db_index=True, null=True, blank=True) class Meta: ordering = ['date_entered', ] In my view, I'm trying for da_list = Data_agent_account.objects.filter(paid_on__isnull=True).order_by('data_agent').distinct('data_agent') for da in da_list: print(da) The error I get is : django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("data_agent_data_agent_account"."data_ag... The SQL that works is: SELECT DISTINCT(data_agent_id) FROM data_agent_data_agent_account WHERE paid_on is null; -
How to use form data to render a certain view.py function in Django
I am working on this harvardCS50 project where I have to redirect the user to the article page if their search query meets the dictionary key. I have stored the articles as 'text' and headings as 'head in the dictionary. data = { "textone": {"head": "Title one", "text": "This will be text ONE."}, "texttwo": {"head": "Title two", "text": "This will be text TWO."} } I was able to make article links that render the requested data, but I have not been able to do it through the form data. If the user input meets the key in my dictionary, the html should render the data based on that. I have been stuck on it for 2 days, kindly help. <head> <title>{% block title %} {% endblock %}</title> </head> <body> <nav> <form action="" method="GET"> <input type="text" name="q"> <input type="submit"> </form> <ul> {% for key, value in data.items %} <a href="{% url 'wikiApp:entry' key %}"><li> {{ value.head }} </li></a> {% endfor %} </ul> </nav> {% block body %} {% endblock %} </body> Following is my views.py: def intro(request): context={"data": data} return render(request, 'wiki/layout.html', context=context) def title(request, entry): for name in data: if name == entry: return render(request, 'wiki/content.html', { "head": data[name]['head'], "text": … -
I'm Tetando shows some fields in my template plus I come across this error in Forms [closed]
django.core.exceptions.FieldError:Unknown field(s)(produtos) specified for Product e aqui esta o codigo: class SelecaoProdutoForm(forms.ModelForm): class Meta: model = Product fields = ('produtos',) widgets = { 'produtos':forms.CheckboxSelectMultiple } estou querendo mostra os produtos que tenho e junto deles vim um checkbox para mim selecionar -
How to add a Bootstrap modal to edit the item selected?
I'm a beginner Django programmer and I have this project that is about creating timelines in which you can add events, and these events will show up in their timelines along with either a countdown to when it will start, a counter of how long ago it ended, or a countdown of how much time it has until it ends if it's an ongoing event. Here's the project's repository: https://github.com/high-rolls/timely So far I was able to handle timeline creation, edit and deletion, as well as event creation and displaying timelines and events within a timeline. But I started having trouble when trying to allow the user to edit an event on the list, what I wanted to do was display a Bootstrap modal, like the one I already display when adding a new event but for editing one, and I wanted to have only a single edit modal element at the bottom of the page (instead of adding a modal after each event's div). Should I do this with JavaScript to dynamically pass the ID of the selected event and fetch the data of that event to fill up the modal's form? I am also confused whether I should use … -
How to cache a TensorFlow model in Django
In Django, I have this TensorFlow model: model = predict.load_model('path\model.h5') After the model is loaded, I want to keep it in memory such that I can use it multiple times without constantly reloading it. I tried using the cache like this: model = predict.load_model('path\model.h5') cache.set('model', model) when I try to retrieve it by: cache.get('model') I get this error: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://cf101767-7409-47ba-8f98-0921cc47a20a/variables/variables You may be trying to load on a different device from the computational device. Consider setting the experimental_io_device option in tf.saved_model.LoadOptions to the io_device such as '/job:localhost'. Is there a different approach to keeping the model loaded ? -
Poetry and Django project 'HTTPResponse' object has no attribute 'strict' [closed]
Education case: on Windows 10 system in VSCode after successful poetry init I have problem with this error, while adding dependencies I know I need later on. Any ideas to fix? -
Can IIS read an exe file of my dynamic web application?
If I convert my django code into an executable file and host it on IIS, will IIS be able to read and execute the code and keep running my dynamic web application (which is accessible to the internet) If yes, I want to know how to achieve such scenario? Please help me out Thanks in advance I want IIS to be able to read obfuscated code or code which is converted to executable file. I want step by step process to achieve this -
Django simple_history query : type object has no attribute 'history'
First of all sorry for my English, I will try my best. I've 2 model; Post and PostComment. And I want show history of comments or history of post on the frontend. When I try to this I'm getting the error : type object has no attribute 'history' Here is my models: models. py from django.db import modelsfrom autoslug import AutoSlugField from simple_history.models import HistoricalRecords from ckeditor.fields import RichTextField class Post(models.Model): Date = ... EditedDate = ... Published = models.BooleanField(default=False) Sender = models.ForeignKey(User, on_delete=models.CASCADE) Title = models.CharField(max_length=200) Text = RichTextField() def __str__(self): return self.Title class PostComment(models.Model): Date = ... EditedDate = ... Comment_Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='yorum') Post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='yorumlar') Comment = models.TextField() Published = models.BooleanField(default=False) History = HistoricalRecords() # new line def __str__(self): return self.YorumGonderen.pers_fullName def save(self, *args, **kwargs): if self.Published == False: self._change_reason = 'Comment is not Approved' else: self._change_reason = 'Comment is Approved' return super().save(*args, **kwargs) and my admin.py from simple_history.admin import SimpleHistoryAdminclass CommentHistoryAdmin(SimpleHistoryAdmin): list_display = ['CommentSender','Comment','Post','Published', 'EditedDate','id'] history_list_display = ['status']search_fields = ['CommentSender'] admin.site.register(Post, CommentHistoryAdmin) I can get all the history records I want but I need to show those records on the page Here is what I am try: def viewPostDetail(request, Slug): Post = … -
Django - OGP Image url preview works inconsistently
I've been struggling with this issue for the past few days now and I still can't find the root cause of it so here it goes: I have a Django blog for which I would like to be able to share links in social media apps such as Whatsapp, Telegram and Signal and I would like these links to have previews containing images of the blog post that the user is sharing. Following the OGP standard I added these meta tags to my page: <meta property="og:image:url" content="{% block meta_img_url_preview %}{% endblock %}"/> <meta property="og:image" content="{% block meta_img_preview %}{% endblock %}"/> <meta property="og:image:secure_url" content="{% block meta_img_secure_preview %}{% endblock %}"/> <meta property="og:image:width" content="1200"/> <meta property="og:image:height" content="630"/> <meta property="og:type" content="article"/> <meta property="og:locale" content="ro_RO"/> After setting up those meta tags, it seems that sharing links via the Whatsapp Web app or the Signal desktop app the image preview shows up just fine. However when using the mobile app and sharing links, only the title and description show up and the image is not being displayed. After checking my server's logs I can see that the requests for the image preview are served just fine with a status of 200: Example of request made using … -
Python django manytomanyfield не получается получить категории
views.py enter image description here models.py enter image description here html enter image description here сайн enter image description here Такая вот тема: я создал две модели ArticlesCategory и Articles, где они связанный полем ManyToManyField. По идее я должен был в файле views передавать все объекты Articles, в html пройтись по нему циклом (что уже работает) а также извлекать список категорий, что приписаны статьям и выводить их через запятую после TAG. Но у меня не выходит. Кто поможет -
"Definition of service not found" error when using pg_service.conf file with Django and PostgreSQL
I'm trying to use a pg_service.conf file to manage database connections in my Django application, but I'm running into an error when trying to connect to the database using the named service. Here's what my DATABASES setting in Django looks like: python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'my_service' } } } And here's what my pg_service.conf file looks like (located at /etc/postgresql-common/pg_service.conf): ini [my_service] host=localhost port=5432 user=my_user password=my_password dbname=my_database However, when I try to run my Django application, I get the following error: psycopg2.OperationalError: service file "/etc/postgresql-common/pg_service.conf" not found The above exception was the direct cause of the following exception: django.db.utils.OperationalError: definition of service "my_service" not found I've checked that the pg_service.conf file exists in the correct location and has the correct permissions, and I've also verified that the service name in my DATABASES setting matches the service name in pg_service.conf. What else could be causing this error? Any help would be greatly appreciated! What I've tried: Verified that the pg_service.conf file exists in /etc/postgresql-common/ and has the correct permissions (owned by postgres user with 0640 permissions). Verified that the service name in my DATABASES setting matches the service name in pg_service.conf. Restarted my Django …