Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to assemble the variable name to use data from JSONField inside the Template in django?
I'm trying to build a website for tv series using Django framework, I put in the models.py all kinds of details about that show and a JSONField (named 'episodes') to define the number seasons and episodes in each season. Example: { "1" : 15 , "2" : 25 , "3" : 23} where season 1 contains 15 episodes, 2 contains 25 and so on the problem starts when I tried making a dropdown in the template where the series is playing so the user can select the episode to watch: This Code is working: Season 1 {% with ''|center:show.episodes.1 as range %} {% for episode in range %} Episode {{forloop.counter}} {% endfor %} {% endwhile %} Season 2 {% with ''|center:show.episodes.2 as range %} {% for episode in range %} Episode {{forloop.counter}} {% endfor %} {% endwhile %} Season 3 {% with ''|center:show.episodes.3 as range %} {% for episode in range %} Episode {{forloop.counter}} {% endfor %} {% endwhile %} But surely this can be much cleaner if I could use 2 for loops inside each others one for the seasons and one for the episodes which sounds easy but for some reason I couldn't do it. I tried: {% … -
Djoser- override perform_create method of class UserViewSet
Need to override the Djoser class UserViewSet method perform_create. I don't know how to do that can anyone help me out. Method from UserViewSet def perform_update(self, serializer): super().perform_update(serializer) user = serializer.instance signals.user_updated.send( sender=self.__class__, user=user, request=self.request ) # should we send activation email after update? if settings.SEND_ACTIVATION_EMAIL and not user.is_active: context = {"user": user} to = [get_user_email(user)] settings.EMAIL.activation(self.request, context).send(to) My URL Patterns from django.urls import URLPattern, path, re_path, include from . import views from .views import MyTokenObtainPairView, GetUser, ReviewsView, GetReviewsByUser from rest_framework_simplejwt.views import ( TokenRefreshView, ) urlpatterns = [ path('', views.getRoutes), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/auth/', include('djoser.urls')), path('api/user/', GetUser), path('api/user/<int:pk>/', GetReviewsByUser), path('api/reviews/', ReviewsView), ] -
How to integrate Python/React projects via workflow tools?
We have a business that sells products and our sales process has several steps. Our microservices are with DRF(Django Rest Framework) and our front_end is with react. We want to dynamic(low_code) our process with workflow tools under the .bpmn standard. We searched the internet but no explanation was found satisfying. This is the last StackOverflow post that we found. No complete examples of these tools (spiffworkflow or camunda) were found. We want to keep our process logic separate from the workflow engine. (just call our microservices) Can anyone introduce a powerful resource or best practice for our purpose? -
How do i get my likes count on my facebook's page using Django?
i want to be able to login to my web application through facebook and also get the user's amount of likes from the user's facebook page. I have tried Integrating the facebook library in Django but, i was unable to get the user's page likes. -
NameError: name 'users' is not defined in python django
Hi I'm sorry if this question has been repeatedly asked but I hope that you kindly help me to figure out what is the problem here. I'm following a python crash course book that uses old versions of Django. I've set up a app called 'users' in my setting so users can make accounts of their own. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps 'learning_logs', 'users', ] and I've included the path in my urls file: from django.contrib import admin from django.urls import path, include app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('users/', users.urls), path('', include('learning_logs.urls')), ] and this is the error that I get: NameError: name 'users' is not defined and if I do it like this from django.contrib import admin from django.urls import path, include app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] I get the following error message: ModuleNotFoundError: No module named 'users.urls' thank you so much for your time and response! -
Comment wont Submit in Django Class Based View method
class PostDetailView(HitCountDetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context.update({ 'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3], }) liked = False likes_connected = get_object_or_404(Post, slug=self.kwargs['slug']) if likes_connected.likes.filter(id=self.request.user.id).exists(): liked = True context['number_of_likes'] = likes_connected.number_of_likes() context['post_is_liked'] = liked post = get_object_or_404(Post,slug=self.kwargs['slug']) comments = post.comments.filter(active=True) new_comment = None if self.request.method == 'POST': comment_form = CommentForm(data=self.request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() context['comment_form'] = comment_form context['post'] = post context['comments'] = comments context['new_comment'] = new_comment return context {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.name }} <span class=" text-muted font-weight-normal"> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} <div class="card-body"> {% if new_comment %} <div class="alert alert-success" role="alert"> Your comment is awaiting moderation </div> {% else %} <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} {{ comment_form|crispy }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> {% endif %} </div> -
Django - fetching only related foreign key in UpdateView and View
Please take a look at this setup below. The Product form shows name field and category dropdown. However, the dropdown show all the categories from all users but I need to show user's own categories only e.g. filter(user=request.user) but I don't know where to place this check (in the form or model or in view) and how. # models.py class Product(models.Model): name = models.CharField(max_length=200, null=False) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Category(models.Model): name = models.CharField(max_length=200, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE) # forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'category'] # views.py class ProductsView(View): model = Product form_class = ProductForm initial = {} template_name = "products_list.html" def get(self, request, *args, **kwargs): category_id = kwargs['category_id'] #### I need to do this check in 4 other models, could you recommend a beter way? try: # Check if user is allowed to view this category category_obj = Category.objects.filter( user=self.request.user).get(pk=category_id) except Category.DoesNotExist: return redirect('homepage') # To add a new product form form = self.form_class(initial=self.initial) # There's another form on this page to add a category form_category = ProductCategoryForm return render(request, self.template_name, {'form': form, 'form_category': form_category, 'category': category_obj}) class ProductEditView(UpdateView): model = Product form_class = ProductForm template_name … -
How to merge dictonary values with the duplicates
In Django, I have two annotated results from two different models and combined them using itertools which I got these results. Initially I was successfully manage to get all the duplicates and add their value using values().annotate(), my problem now is, from this list of dictionary, how can I achieve the result below. Basically I just want to get all the same setting_type and add their values. Example: all 'bazel' should add the carat, quantity and salary except for the rate same with 'pave'. Thanks in advance. source_dict = [ {'setting_type': 'bazel', 'rate': 45, 'carat': 10.30, 'quantity': 10, 'salary': 450}, {'setting_type': 'pave', 'rate': 30, 'carat': 10.43, 'quantity': 10, 'salary': 300}, {'setting_type': 'center', 'rate': 10, 'carat': 3.35, 'quantity': 45, 'salary': 450}, {'setting_type': 'pave','rate': 30, 'carat': 4.10, 'quantity': 23, 'salary': 690}, {'setting_type': 'bazel', 'rate': 45, 'carat': 31.10, 'quantity': 50, 'salary': 2250} ] Derired Result: desired_result[ {'setting_type': 'bazel', 'rate': 45, 'carat': 41.40, 'quantity': 60, 'salary': 2700}, {'setting_type': 'pave', 'rate': 30, 'carat': 14.53, 'quantity': 33, 'salary': 990}, {'setting_type': 'center', 'rate': 10, 'carat': 3.35, 'quantity': 45, 'salary': 450} ] -
Query list index with django
i have a problem with django when i use these two arrays: institution_ids [(2,), (16,)] project_ids [(3,), (1,)] in this query: queryset = Patient.active.filter(tss_id__in=institution_ids, project_id__in = project_ids) it gives me back all the combinations, but I need this kind of result: queryset = Patient.active.filter(tss_id=institution_ids[0], project_id = project_ids[0]) queryset += Patient.active.filter(tss_id=institution_ids[1], project_id = project_ids[1]) how can i do? Thanks Giuseppe -
One big model vs small models with Foreign key relation - Django
Sorry for asking a silly question but I'm not able to figure out what should I use here. Also, I'm a noob into this. The database is a sort of profile page something like Wikipedia of a sports player in-general. Fields type 1 like name, team, DOB, role, country, total winnings, player of the match (times), and all these basic Char and Int fields. Fields type 2: Early Life, Career history, net worth, match history, and all these fields that requires Text-field (each one in a separate field of its own for re-usability in other places). And there are tens of fields including char and text for 1 person. And some of these fields like Career history, etc are going to have their own separate page. Approach 1: Keep all fields in one model (looking at admin page, it's very hard to manage and painful to even look at, performance good for a single profile page but am I wasting any resources when a page need only a set of fields in a page like name and career history. Also, on archive pages where only 10-20 people are going to display with just name and image). Approach 2: Create small … -
Data visualisation Platfrom
Good day, I'm very new to data visualisation and I was wondering If I can get guidance with what back-end and front-end languages will be best to achieve the following: We have data stored in Amazon S3 and we want to visualise this data with graphs on a web platform, we want to use Python as the main language. What I understand from researching are the following: Data in AWS-S3 will be transferred via Athena and Boto3 to the backend of Django, and then from the Django Database (Backend) it will be pulled into the website interface via React.js and displayed as graphs with help from JS Libraries such as react.vis, fusioncharts, reaviz. Are there any other languages that I should look into or I'm I on the right path? Thanks I've did research on Python and Django -
How to set base URL in Django 3.2.5
I would like to run Django from location https://www.example.com/abc/ so that I have the admin interface at https://www.example.com/abc/admin/. And web app login interface at https://www.example.com/abc/ Where can I set the base URL of Django to https://www.example.com/abc/? Django Version=3.2.5 Tried path('abc/', views.getLogin, name="Login Page"), path('abc/login', views.handeLogin, name="handleLogin"), But these are not working, while b below admin path is working fine. path('abc/admin/', admin.site.urls), -
Why dont I see the Comment form on my page
View Method: if self.request.method == 'POST': comment_form = CommentForm(data=self.request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() comment_form = CommentForm() context['comment_form'] = comment_form context['post'] = post context['comments'] = comments context['new_comment'] = new_comment return context Template: {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.name }} <span class=" text-muted font-weight-normal"> {{ comment.created_on }} </span> </p> {{ comment.body | linebreaks }} </div> {% endfor %} <div class="card-body"> {% if new_comment %} <div class="alert alert-success" role="alert"> Your comment is awaiting moderation </div> {% else %} <h3>Leave a comment</h3> <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> {% endif %} </div> -
Problem while profiling queries with django query profiler
question regarding django query profiler, https://github.com/django-query-profiler, When I add logs as shown, the duplicate query count is increased as shown below: While if I remove my logs, the duplicate count is decreased. I am not sure why is this happening as the log should have no effect on query count. question regarding django query profiler, https://github.com/django-query-profiler, When I add logs as shown, the duplicate query count is increased as shown below: While if I remove my logs, the duplicate count is decreased. I am not sure why is this happening as the log should have no effect on query count. -
Copying code using Dockerfile or mounting volume using docker-compose
I am following the official tutorial on the Docker website The docker file is FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ The docker-compose is: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code I do not understand why in the Dockerfile they are copying the code COPY . /code/ , but then again mounting it in the docker-compose - .:/code ? Is it not enough if I either copy or mount? -
How to pass a value from ajax to views
I have a selection box in my template and every time i change the value i have to press a button to submit the value. I know that ajax can solve it but and thats what im trying as follows: Views.py def check_state(request,n): if request.method=='POST': state= request.POST.get('thestate') dict1 = {'name':name} print(dict1) return JsonResponse(dict1, safe=False) template.html <select id="select_state" name="updated_state"> <option disabled="true" selected>{{current_state}}</option> {% for state in States %} <option>{{state}}</option> {% endfor %} <script> var state = document.getElementById( "select_state" ); var x=state.addEventListener( "change", output, true ); function output() { console.log ( state.value ); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ url:'/req-3', # it will call check_state function in views.py method:'POST', data: {thestate:state.value}, dataType: "json", processData:false, csrfmiddlewaretoken:'{{ csrf_token }}', … -
nginx not loading my project from other server
I have three servers 10.77.12.54,10.77.12.55,10.77.12.56 my application on 54, Postgres on 55, and Nginx on 56 servers I created gunicorn.shock file and gunicorn.server file and I added app IP to Nginx config file and also create sites-available, sites-enabled but Nginx not fetching my application is there anything I have to do? server { listen 80; server_name 10.77.12.54; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options nosniff always; add_header X-XSS-Protection "1; mode=block" always; proxy_cookie_path / "/; Secure"; access_log /var/log/nginx/access_rkvy.log main buffer=32k; location / { access_log /var/log/nginx/app54log.log main; proxy_pass http://loadblncer; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_buffering off; proxy_buffer_size 128k; proxy_buffers 100 128k; proxy_set_header X-Forwarded-For $http_x_forwarded_for; } -
def get_absolute_urls(self): not working ,Django
when I click the post title it is supposed to go to the post detail(detail.html) but it's not working, how do i fix this? Here is Model.py class Post(models.Model): ....... def get_absolute_urls(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) Urls.py urlpatterns= [ path('',views.post_list,name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), ] Views.py def post_detail(request,year,month,day,post): post= get_object_or_404(Post,slug=post,status='published',publish_year= year,publish_month= month, publish_day= day) return render(request,'blog/detail.html',{'post':post}) list.html {% extends "blog/base.html" %} {% block title %} My Blog {% endblock title %} {% block content %} <h1>My Blog</h1> <p>this is working in list.html</p> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published{{ post.publish }} by {{ post.author }} </p> {{ post.body| truncatewords:30|linebreaks }} {% endfor %} {% endblock content %} detail.html {% extends "blog/base.html" %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} {% endblock content %} -
How to override get_object in DetailView Django
how can I override get_object in my situation? I've tried different variations but they weren't successful. For example if I try: return self.get_object(). There is RecursionError: maximum recursion depth exceeded model: class Shop(models.Model): name = models.CharField(max_length=100, verbose_name='Название магазина') description = models.TextField(blank=True, verbose_name='Описание магазина') def __str__(self): return self.name view: class ShopDetailView(DetailView): model = Shop template_name = 'shop/shop_detail.html' context_object_name = 'shop' def get_object(self, queryset=None): pass url: urlpatterns = [ path('shop/<str:name>', ShopDetailView.as_view(), name='shop') ] -
django formset, for each form a different data than a select
I have a formset and I would like the first data inside the select to be already selected one every formset, in my case I have two data so in the first formset there will be the first data and in the second the second data and if possible I would like to display them in text and not with a select or in any case no input to modify them. views.py def crea_gruppi(request): tot_gruppi = Gruppo.objects.all() gruppiFormSet = formset_factory(GruppiForm, extra = tot_gruppi.count()) # POST if request.method == 'POST': gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') # GET else: gruppi_formset = gruppiFormSet(prefix='gruppi') context = { 'gruppi_formset': gruppi_formset, 'tot_gruppi': tot_gruppi } return render(request, 'crea_gruppi.html', context) html <section class="mt-5"> <div class="container"> <div class="d-flex align-items-center justify-content-between"> <h2 class="m-0 text-light">crea gruppi</h2> </div> <hr class="bg-light"> <form method="post" autocomplete="off"> {% csrf_token %} {{ gruppi_formset.management_form }} <div class="raccoglitore-gruppi"> {% for gruppo in gruppi_formset %} <div class="gruppo mb-3" style="border: 2px solid red; padding: 20px; border-radius: 5px;"> <div style="color: #fff;"> <h6 class="m-0">test</h6> <hr> {{ gruppo.dati_gruppo|add_class:"form-control" }} <hr> {{ gruppo.giorni_settimana }} </div> </div> {% endfor %} </div> <div class="text-end"> <input type="submit" class="btn btn-warning" value="salva"> </div> </form> </div> </section> form class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] -
Import environ could not be resolved
im working in a django project but i cant import environ. I have tried reinstaling envirion, django-environ , tried select again my virtual enviroment import environ from store.settings.base import * env = environ.Env() DEBUG = env.bool("DEUBG", False) SECRET_KEY = env("SECRET_KEY") ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") DATABASES = { "default": env.db(), } -
How can I filter out date created task in my task list
I'm trying to show the date-created tasks in my list in HTML. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(max_length=1000, blank=True, null=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) And this is my HTML in Django <div class="task-items wrapper"> {% for task in tasks %} <div class="task-wrapper"> {% if task.complete %} <div class="task-title"> <div class="task-complete-icon"></div> <i><s><a class="task" href="{% url 'update-task' task.id %}">{{task}}</a></s></i> <br></br> </div> <a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a> {% else %} <div class="task-title"> <div class="task-incomplete-icon"></div> <a href="{% url 'update-task' task.id %}">{{task}}</a> </div> <a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a> {% endif %} </div> <div class="emptylist"> {% empty %} <h3 style="text-align: center; line-height: 3;">No task in list! Let's create your task</h3> </div> {% endfor %} </div> For example, for each task I create, it must show the title with the date created, and doesn't matter if it is completeđ or incomplete. I just can show the title and how do I do that show the date? -
Django migrations - how to apply newly applied rules to previously saved model instances?
Let's say I have the following model and I have already some instances of the model saved in the database - class Comment(models.Model): comment_text = models.CharField(max_length=255) Now, if I want to change the max_length argument to 127 instead of 255 and apply the migrations, the older instances will still be in the database where some might have the length more than 127 which is not obeying the new migrations. What is the best approach to migrate all previous data along with the new migration rules? -
the pgAdmin4 save null value
I want to save the data of the textfiled that take the location name and other filed from the html and save it in pgadmin4 by using the def in my view when I enter the value in html it is add but it shows me null in pgAdmin this is my view def location(request): if request.method == 'POST': form = request.POST location_id = form.get(' location_id') location_name = form.get('location_name') location_address = form.get('location_address') lat = form.get('lat') lag_y = form.get('lag_y') user_id = request.session['user_id'] print(form) data_insert = MapModel.objects.create(location_id=location_id, location_name=location_name, location_address=location_address, lat_x=lat, lag_y=lag_y,) if data_insert: json_data = {'msg': " data added succssfully", 'id': data_insert.location_id } return JsonResponse(json_data) else: json_data = {'msg': " try agine", 'id': '', } return JsonResponse(json_data) else: return render(request, 'new_file.html') -
Bypass gunicorn worker timeout for specific endpoint
I have Django (3.2.4) app running on Gunicorn (20.1.0) and that app have one heavy endpoint. This endpoint returns csv report which may be very big: def _stream_serialized_data(): paginator = Paginator(MyModel.objects.filter(**filter), 5000) for page in paginator.page_range: yield from MySerializer(paginator.page(page).object_list, many=True).data renderer = CSVStreamingRenderer() return StreamingHttpResponse( renderer.render(_stream_serialized_data(), renderer_context={"header": MySerializer.Meta.fields}), content_type="text/csv", headers={"Content-Disposition": 'attachment; filename="report.csv"'}, ) The problem is that report loading may be aborted by gunicorn worker timeout despite loading starts immediately and there is very small delay between chunks. Is there a way to inform gunicorn that this worker is fine? May be call some function from _stream_serialized_data loop to reset timeout. I already found suggestions to increase timeout and to use gevent, but I don't want to do anything than affects other endpoints.