Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why show "django.core.management.base.SystemCheckError" in Django App & can't run the server
I got "django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:" in my Django App. Here is My settings.py code 'rangefilter', 'csp', 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sales', And here is my admin.py code. from django.contrib import admin from .models import Sale_Data from import_export.admin import ExportActionMixin from rangefilter.filters import DateRangeFilter, DateTimeRangeFilter class Sale_Record(ExportActionMixin, admin.ModelAdmin): list_display =("CustomerName","CustomerPhone","Date", "Item", "Qty_Memory", "Qty_HDD", "Total_Qty", "Prices", "SalePerson") search_fields =("CustomerName", "CustomerPhone") list_filter = ('Date', DateRangeFilter) admin.site.register(Sale_Data, Sale_Record) Error show like this Error -
Django with Https CSRF verification failed. Request aborted
I use Django+nginx+uwsgi to build my website. Before I've already followed this https://docs.djangoproject.com/en/3.2/ref/csrf/ to set up CSRF. And when my website was Http, it worked well. But after I change my website to Https, when I wanna POST something from one page to another, it shows Forbidden (403) CSRF verification failed. Request aborted. ... Reason given for failure: Referer checking failed - no Referer. How can I solve this? -
How to prevente empty logging line in console
Im new to django and I used django logging in my settings.py and also have one subprocess which contains another basicConfig. I dont know why do I have empty lines in my logger although once I added logfile and there was no empty line there. The settings.py logging comes in the following: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(name)s - %(levelname)s - %(message)s', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple' }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', } } and this is logger example 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - DEBUG - 123 play 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - INFO - Starte subprocess fuer 2021-08-24 11:30:58+0200 [-] 2021-08-24 11:30:58+0200 [-] Player.Protocol - DEBUG - Closing Stdin 2021-08-24 11:30:58+0200 [-] the basicConfig for subprocess in python is : logging.basicConfig( level=logging.DEBUG, format="%(name)s - %(levelname)s - %(message)s" ,stream=sys.stderr) logging.getLogger("Player").setLevel(logging.DEBUG) -
python- Django : Where does Django "Append a Slash"?
If I have an application called magazine, and its urlpatterns inside urls.py is like this : from django.urls import path from . import views path("articles/<int:pk>", views.get_article, name="article") .. without a trailer slash, then Django should "append a slash", right? Where is this slash appended? I mean is it added only when I handwrite the url in the browser? I mean if there was an anchor tag in a template like this : <a href="{% url 'magazine:article' 5 %}"> Article 5 </a> .. Wouldn't it go and get the path above without a trailer slash, and then an error with Not Found? -
Django - Concat two fields in a Many to Many Relation to search for a string
I'm using Django 3.2.6 and Mysql. I have two models class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Book(models.Model): ... author = models.ManyToManyField(Author, related_name="authors") A Book can have multiple authors and an author can have multiple books. Now I want to write a simple search where users should be able to search using the Author name. Since I will be using this search in different parts of the App, I created a Custom Manager added the following function. def search(self, keyword): return ( self .filter( Q(title__icontains=keyword) | Q(description__icontains=keyword) | Q(isbn__icontains=keyword) | Q(category__name__icontains=keyword) | Q(author__first_name__icontains=keyword) | Q(author__last_name__icontains=keyword) ) .annotate(book_count=Count("id")) .order_by("-id") ) Please note that annotate(book_count=Count("id")) this part is important otherwise it will return duplicate rows if a book has multiple Authors. This works if I'm searching only using first_name or last_name. For example, it will return results if I search "John" or "Smith". But if I Search full name like "John Smith" this will not return any result. So after searching, I modified the function as follows def search(self, keyword): return ( self .annotate( full_name=Concat( "author__first_name", Value(" "), "author__last_name", output_filed=CharField() )) .filter( Q(title__icontains=keyword) | Q(description__icontains=keyword) | Q(isbn__icontains=keyword) | Q(category__name__icontains=keyword) | Q(author__first_name__icontains=keyword) | Q(author__last_name__icontains=keyword) | Q(full_name__icontains=keyword) ) .annotate(book_count=Count("id")) .order_by("-id") ) But … -
Django reverse for 'password_change_done' not found
I have a small application that I'm writing, but I have came into some trouble with the password changing elements used with the Django authentication framework. But I always get the error after changing a password that: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Here is my code below: #account urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] This is my directory structure for the login system: Directory Structure Here's the password_change.html file: <h3 style="text-align: center;">Change your password</h3> <div class="login-form" style="text-align: center; "> <form method="post"> {{ form.as_p }} <p><input type="submit" value="Change"></p> {% csrf_token %} </form> </div> Any help would be greatly appreciated! -
How do I add a default value to a variable and store in the database in django?
I'm very new to the Django framework. I've started working with models and forms in django. I'm facing a problem in storing values to a database. I want to get something like this. from django.db import models class attempt(models.Model): name = models.TextField(max_length=200) department = "Software Development" Now I want to store the variable department in the database. Where for every entry of object of attempt name will be entered by the user but department remains the same. And is stored something like the below-given format in the database id: 1 name: "John Shelby" department: "Software Development" -
How would I implement a PyGame Frontend with Flask Backend for user management? [closed]
In my Pygame application I plan on having a login form. I would like this login form to be connected to a Flask Database in the cloud to allow users to be able to log in to their account from any device with the application. When a user creates an account in my game, I would like a new record to be created in the Flask Database, with their details. This database is checked every time when a user tries to log in. I am not concerned about multiplayer functionality in my game at the moment (i.e. real time interactions with others). I found this post which suggested using Django or Flask as a database management tool but I am unsure of how to implement this practically. -
getting the current user with Django drf and simple jwt
I was trying to get the current user with rest framework and simple jwt I'm new to Django and I wrote a simple view that does(ish) the job class UserDetail(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [JWTAuthentication,] permission_classes = [IsAuthenticated,] but for some reason when I post the user credentials to the endpoint in postman it says { "detail": "Authentication credentials were not provided." } but when I remove the ==> authentication_classes = [JWTAuthentication,] and permission_classes = [IsAuthenticated,] it works and gite the current user, my question is is this the right way of doing it, and are there any risks in doing it this way and if their is a better and more secure way of doing it. thanks in advance!! -
Change BooleanField whenever object is updated
I have a model with an property called changed which I'd like to change to True when the model is changed. But ofcourse I don't want to set it to True on the creation of an object. class SomeModel(models.Model): changed = models.BooleanField(default=False, blank=True, null=True) -
How to edit or delete data in one page in django
I am using Django and I am outputting data to a Table . Modification and deletion of each row implemented the function by passing the argument as the url parameter of the detail page of each row. I want to edit and edit the table itself, which outputs the entire row without going into the detail page. (The detail page is redirected by the table-link function implemented when each row is clicked.) <table id="waitinglist-list-table" class="table table-compact"> <thead> <tr> <th>name</th> <th>age</th> <th>weight</th> <th>register_date</th> <th>Edit</th> <th>Remove</th> </tr> </thead> <tbody> {% for register in register_list %} <tr class="tr-hover table-link" data-link="/register/detail/{{ register.id}}/"> <td>{{ register.name}}</td> <td>{{ register.age }}</td> <td>{{ register.weight}}</td> <td>{{ register.register_date }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit_register">Edit </button> </td> <td> <button data-toggle="modal" data-target="#remove_register" type="button" id="register-remove-button" register-id="{{ register.id }}" class="btn btn-inverse-danger">Remove </button> </td> </tr> {% endfor %} </tbody> </table> In the past, when editing and deleting, the id was requested in the url parameter. def edit_register(request, id): register = Register.objects.get(pk=id) edited_register, errors = Register.register_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) register.name = edited_register.name register.age = edited_register.age register.weight = edited_register.weight register.register_date = edited_register.register_date register.save() return JsonResponse({'code': 'success'}) def delete_register(request, id): register= Register.objects.get(pk=id) register.is_deleted = True register.save() return HttpResponseRedirect(f'/register/') Do you need a way … -
I'm making a like and dislike button function for a blog project Django.(I'm a beginner)
I'm trying to make a like button which also functions as dislike if clicked again by the same user. one user can like multiple posts but only one time, the next click dislikes it. What I've done: I made a Like model in my app. class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timeStamp = models.DateTimeField(auto_now_add=True) Next I made a post_detail view to check if user already have liked it or not. def post_detail(request, id): post = get_object_or_404(Post, pk=id) user_likes_this = post.like_set.filter(user=request.user) and True or False To increase the likes I made a this in view. def like(request, post_id): new_like, created = Like.objects.get_or_create(user=request.user, post_id=post_id) if not created: messages.error(request, "Alread liked the post.") else: messages.success(request, "Liked successfully") What I don't understand is how to call the function and use it on the like button. Please help me in such a way that a newcomer can understand and implement. -
SyntaxError: Unexpected token < in JSON at position 0 when trying to update reaction emojis
I've designed an emoji pane like facebook which is working fine. However, when I wanted to update the emoji "SyntaxError: Unexpected token < in JSON at position 0" is showing. There are also many related files, so don't know what can play an important role to understand the problem. So I'm uploading the GitHub link. This is the GitHub link for the project: project So I tried to find the reason from inspecting in my chrome browser and in the console it was like this>>> Uncaught TypeError: Cannot read property 'classList' of null at uppost_func.js:21 at dispatch (jquery-3.5.1.slim.min.js:2) at v.handle (jquery-3.5.1.slim.min.js:2) post_func.js:49 POST http://127.0.0.1:8000/react/post/2 500 (Internal Server Error) My uppost_func.js is like this. I've highlighted line number 21 in the code with #### marks>>> function getCookie(name) { var cookieVal = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieVal = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieVal; } function dropdownSettings(node) { let dropdownElem = node.querySelector(".delete-edit-panel > .dropdown"); $(window).on("resize", () => { if (window.innerWidth < 800) { dropdownElem.classList.add("dropleft"); } else { … -
Django include with variable doesn´t give expected results
So I am currently working on a rather Django Project. Since I didn´t start the project and am basically just extending the existing code I am not quite sure if my inputs are blocked through some sort of other configuration but my quite basic task doesnt give me the expected result. So my Main Screen consists of three different templates which are the HomeView and the RootView (which includes the "menu_main" & the "menu_topbar). My goal is to pass context to the menu_main but since it doesn´t have its own view I can´t seem to make it work. The RootView is quite basic and looks like this: class RootView(StrongholdPublicMixin, SimpleView): extra_context = {'home_view': setting_home_view.value} template_name = 'appearance/root.html' def get_extra_context(self): context = super().get_extra_context() context.update( { 'tree_data': Cabinet.objects.all(), }) return context While the context is added to the RootView I cannot seem to pass it to the menu_main (I need the List which is assigned to "tree_data"). I also tried changing my include of the menu_main to "% include 'appearance/menu_main.html' with sample="WORKING" %}" simply adding the "with ...etc." to it but I am not able to access the sample variable in menu_main. In the RootView HTML-File the menu_main include would look like … -
How to restrict options of a select when refreshing the page (dependent selects)?
I'm building a project using Django. I have a form in my project that has two dependent selects (dropdown list). The child select relies on a previously selected option of the parent select, so the child select displays a list of filtered options. They work well, except when I refresh the page the child select loads the entire list of options (not the options related to the parent select option). So I would like to know how can I limit the options of the child select to the selected option of its parent. Thank you in advance. -
How to create form controlling section?
I have a form. I am splitting the form to sections. I created a step form structure. User should move step by step in this structure. I want to create another section where user can check user's answers before submitting the form. But I do not know how can I get and display the answers without saving form. How can I do it? template <form id="msform" method="POST"> {% csrf_token %} .... <fieldset> <h3>D Section</h3> <div class="row"> <div class="col-2"></div> <div class="col-8"> {{ form.answer1|as_crispy_field }} {{ form.answer2|as_crispy_field }} {{ form.answer3|as_crispy_field }} </div> <div class="col-2"></div> </div> <input type="button" name="previous" class="previous btn btn-outline-dark" value="Geri" /> <input type="button" name="make_payment" class="next btn btn-outline-primary" value="Kontrol" /> </fieldset> .... <fieldset> <h1>CONTROL SECTION</h1> <input type="button" name="previous" class="previous btn btn-outline-dark" value="Previous" /> <input type="button" name="make_payment" class="next btn btn-outline-primary" value="Gönder" /> </fieldset> </form> To be clear: -
How to filter by tags with custom Tag model
i'm trying to filter objects by tags names but get an exception. models.py: class Etiqueta(CommonGenericTaggedItemBase, TaggedItemBase): object_id = models.CharField(max_length=50, verbose_name=_('Object id'), db_index=True, null=True) class Lugar(Entidad): etiquetas = TaggableManager(verbose_name=_("Etiquetas"), through=Etiqueta) lugares = cms_models.Lugar.objects.filter(etiquetas__name__in=['pueb']) Throws an error: HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Anybody could help me please ? Thanks in advance. -
Need help on NGINX DJANGO for Oversized Response data
we have one endpoint where it is downloading 50 MB of data and recently data size went up to 60 MB, so application is not able to download this data, but it is fine working with 50 MB. Do we need to change any Nginx configuration to handle such kind of requests ? apiVersion: v1 kind: ConfigMap metadata: name: nginx-conf data: nginx.conf: | upstream app { server 127.0.0.1:9000 max_fails=0; } server { listen 80; server_name ___MY_DOMAIN_NAME___; charset utf-8; gzip on; gzip_disable "msie6"; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; client_max_body_size 100M; client_body_buffer_size 100M; client_body_temp_path /tmp/client_body_temp/ 1 2; proxy_ignore_client_abort on; include uwsgi_params; location / { uwsgi_pass app; uwsgi_read_timeout 600; } } -
JsonResponse Error is not showing as messages
I am building a BlogApp and I am trying to show JsonResponse errors as messages in browser to user ( like a popup ). But Json Response error is not showing, No error are showing in terminal and no errors in browser console. When user dislike the post and tries to like then the error will show. views.py def post_like(request, post_id): post = get_object_or_404(Post, pk=post_id) post_id = request.GET.get('post_id') data['message'] = "You cannote Like" if request.GET.get('submit') == 'like': if request.user in post.likes.all(): return JsonResponse({'action': 'dislike'}) else: return JsonResponse(data) else: return redirect('app1:home') post_detail.html <div class="message-container"> </div> <script> // Function only for showing errors. function show_error_message(question_id) { $.ajax({ url: "{% url 'post_like' data.id %}", datatype: 'json', data: { post_id: post_id }, success: function(json) { $('.message-container').html('') $('.message-container').html( 'You Cannot Vote' ); } }) } </script> <script> // Function for Like post document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('.Likeblogpost').submit(function (e) { e.preventDefault(); let thisElement = $(this) $.ajax({ url: "{% url 'post_like' data.id %}", data: { 'submit': 'like', }, dataType: 'json', method: 'get', async: false, success: function (response) { if (response.action == 'dislike') { html(`<button name='submit' type='submit' value="accept">Unliked</button>`) } } }) }) }) }) </script> Json Response error message is still not showing. Any … -
The partition key must be defined on delete queries in django-cassandra-engine
from django.utils import timezone from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class RequestResponse(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4) sel_no = columns.Text(index=True) transaction_type = columns.Text() created_at = columns.DateTime(default=timezone.now()) updated_at = columns.DateTime(default=timezone.now()) I am using django-cassandra-engine==1.6.1. When I am trying to delete my all data from this model then these errors occurred. My command line: RequestResponse.objects.all().count() >> 10123 RequestResponse.objects.all().delete() Then these errors occurred. 996 partition_keys = set(x.db_field_name for x in self.model._partition_keys.values()) 997 if partition_keys - set(c.field for c in self._where): --> 998 raise QueryException("The partition key must be defined on delete queries") 999 1000 dq = DeleteStatement( QueryException: The partition key must be defined on delete queries -
Control access to a page in UpdateView
Hello!! I want to control that only the superuser and for example the teacher, can access a page inherited from UpdateView and redirect others to the /404 page. My class in views.py : class Edit_news(UpdateView): model = News form_class = edit_NewsForm template_name = "profile/Edit_news.html" URL of class in urls.py : from django.urls import path from .views import Edit_news urlpatterns = [ path("edit-news/<pk>", Edit_news.as_view()), ] Thanks for your help... -
Add an eye icon on the password_change_form.html Django admin
I want to override the password_change_form.html Django admin form, most specifically by adding an eye icon on the password section. The eye icon hides and shows the password. My steps were to first extend the template by creating this file templates/registration/password_change_form.html , but I don't exactly know how to override the inputs. Below is how my form looks : The form looks different than the default django one because I changed it's boostraping. How can I go about this? -
Django : KeyError: "Got KeyError when attempting to get a value for field `channel` on serializer ``
model class Metric(models.Model): date = models.DateField() channel = models.CharField(max_length=50) country = models.CharField(max_length=10) os = models.CharField(max_length=10) impressions = models.IntegerField() clicks = models.IntegerField() def __str__(self): return "{} - {}".format(self.date, self.channel) My view class MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter My serializer class MetricSerializer(serializers.ModelSerializer): class Meta: model = Metric fields = '__all__' I need to group by one or more columns: date, channel, country, operating system and serialize it. Can someone help me with how I can do it? select channel, country, sum(impressions) as impressions, sum(clicks) as clicks from sample dataset where date < '2017-06-01' group by channel, country order by clicks desc; channel | country | impressions | clicks ------------------+---------+-------------+-------- adcolony | US | 532608 | 13089 apple_search_ads | US | 369993 | 11457 vungle | GB | 266470 | 9430 vungle | US | 266976 | 7937 My view lass MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter def get_queryset(self): sort_by_dict = {'asc': '', 'desc': '-'} queryset = Metric.objects.all() group_by = self.request.query_params.get('group_by', None) # grouping the queryset if group_by is not None: queryset = queryset.values(group_by).annotate(dcount=Count(group_by))#.order_by() return queryset I am getting the following error KeyError: "Got KeyError when attempting to … -
Django Crispy Forms does not display the border of a certain field
I am using bootstrap and crispy forms to style my website. But a border around all my username fields dont get displayed. Like shown here (I cut off some parts). It is confusing to me, as all other fields get displayed properly: My Code (Form / HTML / View) looks like: class LWRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = LWUser fields = ['username', 'email', 'password1', 'password2'] . ... <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-dark" type="submit">{% trans "Register" %}</button> </div> </form> . ... def get(self, request): form = LWRegisterForm() context = {'form': form} return render(request, 'users/register.html', context) In order to fix it I tried in the HTML to use {% crispy update_form %} and {{ update_form.username|as_crispy_field }} instead of my code. Both still displayed it without a border. I also tried swapping around the order of things that get displayed with {{ update_form.email|as_crispy_field }} {{ update_form.username|as_crispy_field }} but still the username field was without a border. I tried reinstalling django-crispy-forms via pip unistall. Did not work. Now I am out of ideas. What could it be? -
How mass update data on django db table?
I need often parse big xml file and insert and update data to db table. How I can do it fast without delete data from database. Now I delete all data before parse and insert all data after. But it way broke all foreign keys. for category in self.root.findall('.//categories/category'): try: cat_id = category.get('id') cat = CategoryModel( id=cat_id, name=category.text, picture=category.get('picture') ) categories[cat_id] = cat CategoryModel.objects.all().delete() CategoryModel.objects.bulk_create(categories.values(), batch_size=50000) Next my code generation. I use bulk_update: all_categories = CategoryModel.objects.all() created_categories = [str(cat[0]) for cat in all_categories.values_list('id')] new_cats = [] update_cats = [] for category in self.root.findall('.//categories/category'): try: cat_id = category.get('id') cat = CategoryModel( id=cat_id, name=category.text, picture=category.get('picture') ) categories[cat_id] = cat if cat_id in created_categories: update_cats.append(cat) else: new_cats.append(cat) CategoryModel.objects.bulk_create(new_cats, batch_size=50000) all_categories.bulk_update(update_cats, fields=['name', 'picture'], batch_size=1000) It code work. But may be you know better way?