Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying in production gunicorn + nginx with domain
I'm new to development and my trying to deploy my django app with gunicorn and nginx. I've followed this tuto and tried to understand every step. https://www.agiliq.com/blog/2013/08/minimal-nginx-and-gunicorn-configuration-for-djang/ I bought a domain at namecheap. I think a missed a step, I don't know where. When I try to access the adress I'can't. I have 2 files inside /etc/nginx/sites-enabled/ | mjc and mjcpublic Here the content MJC server { listen localhost:8000; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { autoindex on; alias /home/webserver01/ProjetE2I/TableauDeBordMjc/src/static/; }} mjc public listen 80; server_name mjc-internal-stcham.me www.mjc-internal-stcham.me; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { alias /home/webserver01/ProjetE2I/TableauDeBordMjc/src/static; } Thank you for your help. -
Graphene/Django mutations return null
I created the following model in my django app: class Post(models.Model): title = models.CharField(max_length=125, unique=True) slug_title = models.SlugField(max_length=255, unique=True) body = models.TextField() published_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) class Meta: ordering = ['-published_date'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug_title = slugify(self.title) super(Post, self).save(*args, **kwargs) I want to be able to use an API to do POST/GET requests later on, so I decided to use graphene-django. Everything is installed properly and working. As per the tutorials, I created my schema.py file as follow: # define schema class PostType(DjangoObjectType): class Meta: model = Post fields = ('title', 'body', 'author', 'published_date', 'status', 'slug_title') class UserType(DjangoObjectType): class Meta: model = get_user_model() class PostInput(graphene.InputObjectType): title = graphene.String() slug_title = graphene.String() body = graphene.String() author = graphene.Int() published_date = graphene.DateTime() status=graphene.Boolean() class CreatePost(graphene.Mutation): class Arguments: input = PostInput(required=True) post = graphene.Field(PostType) @classmethod def mutate(cls, root, info, input): post = Post() post.title = input.title post.slug_title = input.slug_title post.body = input.body post.author = input.author post.published_date = input.published_date post.status = input.status post.save() return CreatePost(post=post) class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(UserType, username=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_by_slug = graphene.List(PostType, slug=graphene.String()) def resolve_all_posts(root, info): return Post.objects.all() def resolve_author_by_username(root, info, username): return User.objects.get(username=username) … -
How to get email address of all users in Django
I am learning django and I am stuck with this problem. How do I get the email address of all the users in Django. The user can be of any type like superuser, general user etc. I tried the following but I am not getting email address of all the users. user = User.objects.get(id=2) user_email = user. Email print(user_email) I want something like a list of all the email addresses. Can someone please help me with it? -
Django reset model fields to their default value?
On refresh I want this to reset to default from_date = models.DateField(default='2000-01-01') Status = models.CharField(choices=A_K, max_length=100, default='no Status') to_date = models.DateField(default='2000-01-01') right now I have default when something new is created, while it is fine, I need it to be set to default if page is refreshed. I read here: Django - How to reset model fields to their default value? that it is possible with none like with null=true and blank=true, but that didnt worked. Do I really need a whole function for that ? -
how to create a sharable link for a card in django template
I am learning to create a blogging website in Django web framework where i am displaying my blog header and small body content in a card for every blog in blog list page, And i am trying to create a sharable link for every card so that if somebody share that link to another website it display the whole card itself. -
Plausible analytics on a server with a webapp
I have Django hosted with Nginx on DigitalOcean. Now I want to install Plausible Analytics. How do I do this? How do I change the Nginx config to get to the Plausible dashboard with mydomain/plausible for example? -
get_absolute_url is not working--gives this error NoReverseMatch error
I get this error when trying to user get_absolute_url--what i am doing wrong? NoReverseMatch at /mega_archive/books/ Reverse for 'book' with arguments '('',)' not found. 1 pattern(s) tried: ['mega_archive/book/(?P<book>[-a-zA-Z0-9_]+)/\\Z'] views.py def books(request): books = Book.objects.all() return render(request, 'mega_archive/books.html',{ 'books':books }) def book(request, book): book = get_object_or_404(Book, slug=book) return render(request, 'mega_archive/book_details.html', { 'book':book }) urls.py path('books/', views.books, name='books'), path('book/<slug:book>/', views.book, name='book'), models.py def get_absolute_url(self): return reverse('mega_archive:book', args=[self.slug]) def __str__(self): return self.title html {% for book in books %} <a href="{{book.get_absolute_url}}">{{book}}</a><br> {% endfor %} can anyone point to what I did wrong? -
Deploy a DJANGO application on HEROKU without migrate
I want to deploy my django application on heroku But heroku runs manage.py migrate I would like heroku not to launch any command, how can I do? -
why my Django debug tool bar is not showing in the browser?
I perfectly followed all the steps in this documentation : https://django-debug-toolbar.readthedocs.io/en/latest/installation.html and tried these solutions I found online adding to the settings module: if DEBUG: import mimetypes mimetypes.add_type("application/javascript", ".js", True) def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': show_toolbar, } if DEBUG: import socket # only if you haven't already imported this hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] but no luck any suggestions? -
Using both Django template and React
Hi guys I’m trying to bulid a website which django works as an rest-api and react works as a front side. I manage to do the whole thing just fine and about to deploy it using aws. But there is one thing I couldn’t really get. Inside my django project I have an app that uses only django template to render things to front. And other apps are working only as apis to get and post things via react. Is it possible to deploy this kind of structure without any special options? I searched internet for a while but I couldn’t really find an example that fits my situation. Thanks! -
How can I resize my video in Django using MoviePy and Dropzone?
I want to limit the length of the uploaded videos to one minute, I have tried to use MoviePy but so far I have not been able to do it. Can you help me please ? models.py enter image description here views.py enter image description here My error enter image description here -
Django JSON field - query id field
I am trying to filter a Django JSONfield (MariaDB backend, Django 4.0) target_360 is the JSON field, every query I've tried brings back an empty queryset, even though the debug statement clearly shows the matching id in the first row of the 'parent' query field in models.py using django.models.JSONField target_360 = models.JSONField(_('360 target'),default=None, null=True) Query Code surveys_with_target = Survey_Instance.objects.filter(pulse_id=pulse_id, survey_id=survey_id, target_360__isnull=False) logger.debug('First row target_360') logger.debug(surveys_with_target[0].target_360) logger.debug('target_id in filter') logger.debug(target_id) survey_test = surveys_with_target.filter(target_360__contains=target_id) logger.debug("SURVEY TEST:") logger.debug(survey_test) survey_test = surveys_with_target.filter(target_360__id__contains=target_id) logger.debug("SURVEY TEST 2:") logger.debug(survey_test) survey_test = surveys_with_target.filter(target_360__id=target_id) logger.debug("SURVEY TEST 3:") logger.debug(survey_test) debug output: First row target_360 {"id": "189f5422-f522-4860-8794-a3375f84a086", "target_type": "Individual"} target_id in filter 189f5422-f522-4860-8794-a3375f84a086 SURVEY TEST: <QuerySet []> SURVEY TEST 2: <QuerySet []> SURVEY TEST 3: <QuerySet []> It's probably something really simple, what at I am doing wrong? -
problem setting my python/django project up in docker
I am having a problem setting my python/django project up in docker. I ran docker build . and it ran OK to the end with no errors. My source code is in my Z: drive is /ISICSFLSYN01/ISICSFLSYN01 which is my synology NAS. When I run the docker-compose.yml, I get the following message "mount path must be absolute". How do I get docker-compose to see the code in my NAS? docker-compose.yml version: "3.9" services: web: build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code" running Z:\Django Projects\code>docker-compose up [+] Running 0/0 Container 7bc5f2ff15b2_7bc5f2ff15b2_7bc5f2ff15b2_code-web-1 Recreate 0.1s Error response from daemon: invalid volume specification: '/run/desktop/mnt/host/uC/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code:"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code":rw': invalid mount config for type "bind": invalid mount path: '"/ISICSFLSYN01/ISICSFLSYN01/Django Projects/code"' mount path must be absolute Z:\Django Projects\code> My directories are set up: Z:\Django Projects\code> .venv .vs django_project pages .dockerignore db.sqlite3 docker-compose.yml dockerfile manage.py requirements.txt -
Heroku application error whentrying to deploy django project
i'm trying to deploy my django project on heroku. The deployment is successful but then if I try to go to my project page I get the following error: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail This is my deployment log: -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.10.7 -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 130 static files copied to '/tmp/build_fe9a8caa/staticfiles', 384 post-processed. -----> Discovering process types Procfile declares types -> realease, web -----> Compressing... Done: 29.5M -----> Launching... Released v4 https://appname.herokuapp.com/ deployed to Heroku -
Django DISTINCT and get all the objects from the distinct value
Can someone here help me with this problems ? struggling so long and can't get it right. Suppose I have this database: id Referall Code User Email Date of Using ______________________________________________________________________ 1 ABCD John john@email.com 13-06-2022 2 EFGH Marry marry@email.com 17-06-2022 3 IJKL Bryan bryan@email.com 21-06-2022 4 ABCD Luke luke@email.com 05-07-2022 5 EFGH Tom tom@email.com 11-08-2022 What I want the result will be like this: Referall Code User Email Date of Using _______________________________________________________________ ABCD John john@email.com 13-06-2022 Luke luke@email.com 05-07-2022 EFGH Marry marry@email.com 17-06-2022 Tom tom@email.com 11-08-2022 IJKL Bryan bryan@email.com 21-06-2022 I am using sqLite as a database, and can't find a way to get it done in django. Thanks in advanced -
How to make it so that when saving data in the database, the data generated by the function is automatically inserted into the field Django ORM
I'm writing a site on Django and ran into a problem I have a title field in the database, which stores the title of the book, but I want to add a chunk_title field, which will store the title of the book, divided into chunks of 3 characters, I wrote a method that does this, but I need that when inserted into the database, it was automatically applied and its result was inserted into chunk_title This is my DB model,where the last field is the field I want to auto-generate the value into: class Book(models.Model): """ Клас,який зберігає всі книги на сайті """ title = models.CharField(max_length=120, default=' ', verbose_name='Назва') description = models.TextField(verbose_name='Опис') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категорія') date_at = models.DateField(auto_now_add=True, verbose_name='Дата створення') image = models.ImageField(upload_to='photos/%Y/%m/%d/') authors = models.ManyToManyField(Author, verbose_name='Автори') content = models.FileField(upload_to='contents/%Y/%m/%d/', blank=True) price = models.IntegerField(verbose_name='Ціна', default='0') chunk_title_book = models.TextField(default=' ') And this is my method, the result of which I want to insert into that field (it is in the same class, i.e. Book): def chunk_title(self, string: str) -> str: """ Розбиває назву книги на чанки по 3 символи макисмум для подальшого пошуку по цих чанках """ chunk_string = ' '.join(textwrap.wrap(string, 3)) return chunk_string + ' ' + ' … -
Django channels - disconnect WebSocket from server side when token expires or gets invalid
I searched about this topic, specifically for Django, but i did not find any applicable solution. Namely, when i use a JWT as a query parameter to authenticate the user while opening a socket connection, the problem i'm thinking of is that the connection can be open for a long time which can exceed the validity of the token. The token can expire or even get invalid if some data changes. If someone steals the token which is expired, he can't really do anything with it because he cannot establish a new socket connection, so i assume this is not a big deal (maybe i'm wrong). The validity of the token on the data side is a bit different. If i used a data part to define the channel name, and then exactly that information changes, the old socket connection will receive the old data even when it should not. For example, if i used users company name for the channel name, and then the admin changes users company, while the old socket connection is still open, the user will still receive data from the old company until the old connection is disconnected and new one established. So i would … -
Django template priority operator
I have a condition {% if AAA or BBB and CCC %} do something {% endif %} Is it possible to do the OR first ? I try {% if (AAA or BBB) and CCC %} do something {% endif %} But it doesn't work Could not parse some characters: ( -
log messages from django application not uploaded in aws watch
I have added log messages in my django application and it was successfully logging log messages to the log file. Now, I tried to add log messages to aws cloud watch. When I run the application it creates log group in aws cloud watch but log stream is not created and log messages also not uploaded. I have also manually created log stream in aws cloud watch but still log messages were not uploaded. I have the following logging configuration in my django application. logger_boto3_client = boto3.client( "logs", aws_access_key_id=CLOUDWATCH_AWS_ID, aws_secret_access_key=CLOUDWATCH_AWS_KEY, region_name=AWS_DEFAULT_REGION, ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': "[cid: %(cid)s] [%(asctime)s.%(msecs)03d] %(levelname)s [%(name)s:%(lineno)s] [%(funcName)s] %(message)s", 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'logger': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': str(BASE_DIR) + '/logs/test.log', 'formatter': 'simple', 'filters': ['correlation'], }, 'watchtower': { "level": "DEBUG", "class": "watchtower.CloudWatchLogHandler", "boto3_client": logger_boto3_client, "log_group": "DemoLogs2", # Different stream for each environment "stream_name": "logs", "formatter": "simple", 'filters': ['correlation'], } }, 'filters': { 'correlation': { '()': 'cid.log.CidContextFilter' }, }, 'loggers': { 'root': { 'handlers': ['logger', 'watchtower'], 'level': 'DEBUG', 'filters': ['correlation'], 'propagate': True, } } } In my application I'm using logger like this, import logging logger = logging.getLogger(__name__) logger.info("log message.") My aws cloudwatch console. -
pass an ID to serializers.RelatedField djagno rest framework (DRF)
i have this code here : class TradePartsSerializer(serializers.ModelSerializer): class Meta: model = TradePart fields = '__all__' class TradeSerializer(serializers.ModelSerializer): tradepart = serializers.RelatedField(many=True, queryset=TradePart.objects.filter(TRADE ID)) class Meta: model = Trade fields = ['user', 'partsNum', 'tradepart'] how i can pass the trade ID from TradeSerializer to queryset=TradePart.objects.filter(TRADE ID HERE!) so i can return trade parts for each trade my views.py: if 'user' in request.query_params: userId = request.query_params['user'] user = User.objects.get(id=userId) trades = Trade.objects.filter(user=user) serializer = TradeSerializer(trades, many=True) return Response({'trades': serializer.data}, status=200) -
Utilizar "range" en filterset_fields de django-filters en DRF
estoy intentando traer un rango de un valor y no encuentro ejemplos de como usarlo en la consulta por postman. Por otro lado para probar que el campo funciona para la búsqueda hice una consulta con "exact" y tampoco me esta tomando el campo, por lo que pienso que en realidad el inconveniente está en el campo que llamo. Si bien este campo esta en el modelo, el valor del mismo lo obtengo des un método en el serializer. Como podría yo filtrar por este campo si el valor lo obtengo recién en la respuesta? paso el filtro en la view y el serializer ** filtrar por este campo** filterset_fields = { 'ppv': ['range'] } **campo en el serializer** ppv = serializers.SerializerMethodField(read_only=True) -
customize url on django
I would like to set up a url path that takes into account any string consisting of ASCII letters or numbers, the hyphen or character and also a period. For example: localhost:8000/mysite/toto-25b.ko How to set this up with re_path ? -
can i stop repetition of tags after each post?
The same tags are being repeated and displayed in the dropdown list. It is looping over the tags used in each post but it is not checking if the tags are repated or not. So is there any way that I can avoid this repetition? my dropdown list is as below: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for post in posts %} {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}"> {{ tag.name }} </a> {% endfor %} {% endfor %} </div> </div> views.py def home(request, tag_slug=None): posts = Post.objects.all() #tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) return render(request, 'blog/home.html', {'posts':posts}) models has class Post(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) tags = TaggableManager() def __str__(self): return self.title urls.py has path('tag/<slug:tag_slug>/',views.home, name='post_tag'), I wanna use the same tag in different posts. Like when blogs are posted where it may use the same tag I am using Django-taggit -
Using filters through the django-filter module
Please tell me what am I missing. It is necessary to implement a table search in several columns as in the screenshot.[enter image description here][1] [1]: https://i.stack.imgur.com/1Zzw1.png. There is a video on YouTube with the implementation, but through the functions. <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{tableFilter.form}} <button class="btn btn-primary" type="submit"> Поиск </button> </form> </div> </div> </div> views.py class Home(ListView): model = Reports template_name = 'gaz_app/index.html' context_object_name = 'Reports' paginate_by = 20 def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'ИС' return context def seacrh_filter(request): customer = Reports.objects.all() orders = Reports.order_set.all() context = {'orders': orders} tableFilter = OrderFilter(queryset=orders) orders = tableFilter.qs return render(request, 'gaz_app/index.html', context) filters.py class OrderFilter(django_filters.FilterSet): # минимум 2 атрибута class Meta: model = Reports # Модель для которой мы создаем фильтр fields = ['facility', 'structural_unit'] # Указываем какие поля мы хотим разрешить urls.py urlpatterns = [ path('', Home.as_view(), name='home'), path('structural_unit/<str:pk>/', ReportByStructuralUnit.as_view(), name='structural_unit'), path('report/<str:pk>/', GetReport.as_view(), name='report'), ] models.py class Reports(models.Model): """Отчеты""" short_title = models.CharField(max_length=150, verbose_name='Краткое название') comment = models.TextField(blank=True, verbose_name='Комментарий') facility = models.ForeignKey('Facility', on_delete=models.PROTECT, verbose_name='Объект') structural_unit = models.ForeignKey('StructuralUnit', on_delete=models.PROTECT, verbose_name='Структурное подразделение') executor = models.ForeignKey('Executor', on_delete=models.PROTECT, verbose_name='Исполнитель') surveys = models.ForeignKey('Surveys', on_delete=models.PROTECT, verbose_name='Вид исследования') file = models.FileField(upload_to='Отчеты объектов', verbose_name='Отчет для загрузки') year_of_work = models.DateField(verbose_name='Отчетный период') … -
User input error 405 Method Not Allowed (POST)
I'm stuck with Django form. I would like to have an input field on my DetailView page, that takes player score. Then I want to process this score in pythton function, but every time i get error 405 Method Not Allowed (POST) html: <h7><img style="width:2rem; height:2rem" src="{{ player.avatar.url }}"> {{player}}</h7> <form method="POST"> {% csrf_token %} <input style = "width:2rem" type="text" id="{{player}}" name="score"> <input type="submit" name="score" value="OK"> </form> {{ val }} Form: class GetScoreForm(Form): score = CharField() views def get_score(request): if request.method == 'POST': form = GetScoreForm(request.POST) if form.is_valid(): val = form.cleaned_data.get("score") # HERE I WANT TO PROCESS MY SCORE else: form = GetScoreForm() return render(request, 'tournamentdetailview.html', {'form': form}) ```