Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How optimize complex query django
I use Django 2.1. I'm trying to optimize a query that is being accused of causing slowness in the database, I tried to add as select and prefetch related but it didn't have the desired effect. My final objective emp is a tuple of ids like: ((90512,), (90523,), (125792,)....., (127012,)) creator and hiring_manager is a Fk relationship followers and conductor a M2m relationship This is django query job_ids = list(Job.objects.select_related('creator', 'hiring_manager').prefetch_related('conductors', 'followers').filter(Q(creator__in=emp) & (Q(hiring_manager=user) | Q(followers=user) | Q(conductors=user))).values_list('pk', flat=True)) -
TypeError: 'module' object is not callable Django 3 render function
I am just making a simple hello world page in my Django 3 Application I am getting error TypeError: 'module' object is not callable Here is image of the entire error It was working before but suddenly not working now. Here is my views.py from django.shortcuts import render # from django.http import HttpResponse # from django.template import RequestContext, loader # from django.template import Context def index(request): """Placeholder index view""" print('XXXX') return render(request, 'hello_world/index.html') #return HttpResponse('Hello, World!') def test(request): context = {'foo': 'bar'} return render(request, 'hello_world/index.html', context) The error is in line return render(request, 'hello_world/index.html') but when I change it to return HttpResponse('Hello, World!') it works fine. My html file is very simple index.html <h3> MY DJANGO APP</h3> The html file is also in the correct folder templates/hello_world/index.html -
Login (django project)
I'm having problems with django's user accounts/login I can't go to link 'http://127.0.0.1:8000/authenticate/login/' and this is my errors: TemplateDoesNotExist at /authenticate/login/ This is the main URL file of the project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('article.urls')), path('authenticate/', include('django.contrib.auth.urls')) ] and this is my app's url: from django.urls import path from . import views urlpatterns = [ path('Matin/', views.matin, name='Matin'), path('register/', views.register, name='register'), ] -
How can i save custom fields in registration from to my database? (Django)
I'm trying to create a school related website with django. So i created a custom user model looks like this (Sorry for the foreign field names): class ogrenciler(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ogr_adi = models.CharField(max_length=30) ogr_soyadi = models.CharField(max_length=30) sinifi = models.ForeignKey(siniflar, null=True, on_delete=models.CASCADE) numara = models.CharField(max_length=5) foto = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.ogr_adi + " " + self.ogr_soyadi + "ogrencisi" and this is my custom registiration form: class ogrenciKayit(UserCreationForm): email = forms.EmailField() numara = forms.CharField(max_length=5, required=True) class Meta: model = User fields = ['username', 'email', 'numara', 'password1', 'password2'] def save(self, commit=True): user = super(ogrenciKayit, self).save(commit=False) user.numara = self.cleaned_data['numara'] if commit: user.save() return user I created a signal.py file to whenever a user created also create a "ogrenci"(student). This is my signals.py file: @receiver(post_save, sender=User) def create_ogrenci(sender, instance, created, **kwargs): if created: ogrenciler.objects.create(user=instance) @receiver(post_save, sender=User) def save_ogrenci(sender, instance, **kwargs): instance.ogrenciler.save() Everything works fine but the "numara" field doesn't get saved. This is my views.py file if you wanna check it: def ogrenciregister(request): if request.method == 'POST': form = ogrenciKayit(request.POST) if form.is_valid(): form.save() username= form.cleaned_data.get('username') messages.success(request, f'Hesap {username} adına oluşturuldu.') return redirect('giris') else: form = ogrenciKayit() return render(request, 'kullanicilar/ogrencikayit.html', {'form': form}) -
Problems with Postgrestql and Django in Manjaro linux, after update
I'm making a blog app in Django, and I'm using Postgres as database, since I read it is the best database for django. I am developing in Manjaro linux, a rolling release distribution, and I recently updated my system, after the update I got an error with the database. postgres does not know where to find the server configuration file. You must specify the --config- file or -D invocation option or set the PGDATA environment variable. So after search for a solution I decided to reinstall Postgres, and after reinstall it, more problems happened. Now that I want to start Postgres i get the following error: postgresql.service - PostgreSQL database server Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Thu 2021-01-14 13:19:00 -05; 6s ago Process: 55976 ExecStartPre=/usr/bin/postgresql-check-db-dir ${PGROOT}/data (code=exited, status=1/FAILURE) ene 14 13:19:00 daniel-arch systemd[1]: Starting PostgreSQL database server... ene 14 13:19:00 daniel-arch postgres[55976]: "/var/lib/postgres/data" is missing or empty. Use a command like ene 14 13:19:00 daniel-arch postgres[55976]: su - postgres -c "initdb --locale en_US.UTF-8 -D '/var/lib/postgres/data'" ene 14 13:19:00 daniel-arch postgres[55976]: with relevant options, to initialize the database cluster. ene 14 13:19:00 daniel-arch systemd[1]: postgresql.service: Control process exited, code=exited, status=1/FAILURE ene 14 13:19:00 daniel-arch … -
Django PasswordChangeForm change message(or customize, translate)
Change password error message shows only in english how to change it or translate it? /form/ class PasswordChangingForm(PasswordChangeForm): old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'type':'password'})) new_password1 = forms.CharField(max_length=100, widget=forms.PasswordInput(attrs={'class': 'form-control', 'type':'password'})) new_password2 = forms.CharField(max_length=100, widget=forms.PasswordInput(attrs={'class': 'form-control', 'type':'password'})) class Meta: model = CustomUser fields = ('old_password','new_password1', 'new_password2') /views.py/ class PasswordChangeView(PasswordChangeView): form_class = PasswordChangingForm success_message = 'Everything is fine' success_url = reverse_lazy('settings_success') /template/ <form method="POST"> {% csrf_token %} {% include '../extends/_messages.html' %} <div class="form-group row"> <label for="st_pass1" class="col-sm-4 col-form-label">Нууц үг</label> <div class="col-sm-8"> {{ form.old_password }} </div> </div> <div class="form-group row"> <label for="st_pass2" class="col-sm-4 col-form-label">Шинэ нууц үг</label> <div class="col-sm-8"> {{ form.new_password1 }} </div> </div> <div class="form-group row"> <label for="st_pass3" class="col-sm-4 col-form-label">Шинэ нууц үг давтах</label> <div class="col-sm-8"> {{ form.new_password2 }} </div> </div> {{ form.errors}} <div class="text-center form-group pt-5" style="width: 100%;"> <button type="submit" class="btn btn-primary cs-btn">Хадгалах</button> </div> </form> (my first question in Stackoverflow. Please let me know if question unclear) -
How can I split a long django-modelform into accordion?
I have a single model that consist of 80+ fields, and a ModelForm made on it. So, to make it readable for user, I decided to wrap it into accordion (jquery) with 4 sections. The problem I ran into is that I don't know how to split my Form as it seems very dull to write each field manually like {{form.field}}. I wonder if its possible to make it in some kind of cycle or using some tags or whatever. Now it looks like: <div id="accordion"> <h3>Section 1</h3> <div> <p>{{form.field1}}</p> </div> <h3>Section 2</h3> <div> <p>{{form.field2}}</p> <p>{{form.field3}}</p> </div> <h3>Section 3</h3> <div> <p>{{form.field4}}</p> <p>{{form.field5}}</p> </div> </div> I really don't think it's necessary to write all 80+ field like that, but I can't come up with the idea how to deal it. Thank you for any idea! -
NameError: name 'contact_value' is not defined in serializers.py [closed]
I followed a tutorial on the Django REST framework, and I'm now trying to apply what I've learnt to my database. The last part of the stacktrace is: ... File "C:\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\jmr\projects\python\django-ref-impl\django_ref_impl\parties\urls.py", line 30, in <module> from . import views File "C:\Users\jmr\projects\python\django-ref-impl\django_ref_impl\parties\views.py", line 49, in <module> from .serializers import ( File "C:\Users\jmr\projects\python\django-ref-impl\django_ref_impl\parties\serializers.py", line 52, in <module> class ContactMethodSerializer(serializers.ModelSerializer): File "C:\Users\jmr\projects\python\django-ref-impl\django_ref_impl\parties\serializers.py", line 54, in ContactMethodSerializer class Meta: File "C:\Users\jmr\projects\python\django-ref-impl\django_ref_impl\parties\serializers.py", line 59, in Meta contact_value, NameError: name 'contact_value' is not defined The start of my serializer.py is: from rest_framework import serializers from .models import ( ContactMethod, ContactMethodType, CountryType, GenderType, Organisation, OrganisationType, Party, PartyContact, PartyContactType, PartyIdentifierType, PartyRelationship, PartyType, Person, RoleType, RoleTypeRelationship, ) # # TABLE: CONTACT_METHOD (COME) # class ContactMethodSerializer(serializers.ModelSerializer): class Meta: # the model for Serializer model = ContactMethod # field names for serialization fields = ( contact_value, effective_period_from, effective_period_to, extension_number, notes, id, contact_method_type_id, created_at, created_by, updated_at, updated_by, ) ... The … -
Is it possible to have a model reference many other models depending on the situation in django?
I honestly don't know how to even phrase my question but i think an example might help. I have mad three apps with their own models respectfully. App1, App2, App3. I want to create a new app (Reports) which will report on each of my other apps (App1,App2,App3). With my current knowledge i have the following in my Reports models.py class Reports(models.Model): name = models.CharField(max_length=150, blank=True) app1_reported = models.ForeignKey( App1, on_delete=models.CASCADE, related_name='reported_app1', blank=True) app2_reported = models.ForeignKey( App2, on_delete=models.CASCADE, related_name='reported_app2', blank=True) app3_reported = models.ForeignKey( App3, on_delete=models.CASCADE, related_name='reported_app3', blank=True) is there any way for me to create in my Reports model one reference that could reference either App1, or App2, or App3? something like: class Reports(models.Model): name = models.CharField(max_length=150, blank=True) reported = models.ForeignKey( App1 or App2 or App3, on_delete=models.CASCADE, related_name='reported_app_is', blank=True) My app works fine with the first implementation I would just like to know if there is a better way. Also please let me know if this makes sense, im struggling with the right wording. -
Login required when submitting a form inside a detail view
Is there a way to add login required when submitting a form inside a detail view? I know LoginRequiredMixin, but I want anonymous user to view the details of the post, but require them to login when adding a comment. Is there a way to do that? Thanks! views.py: class PostView(DetailView, FormMixin): model = Post form_class= CommentForm def get_success_url(self): return reverse_lazy('post-detail', kwargs={'pk': self.object.pk}) def get_post_data(self, *args, **kwargs): post_menu = Post.object.all() context = super(PostDetailView, self).get_context_data context["form"] = CommentForm() return context def post(self, request, *args, **kwargs): self.object = self.get_object() comment_form = self.get_form() if comment_form.is_valid(): return self.form_valid(comment_form) else: return self.form_invalid(comment_form) def form_valid(self, comment_form): comment_form.instance.post = self.object comment_form.instance.user = self.request.user comment_form.save() return super().form_valid(comment_form) -
How to build a private chat (one to one chat) app with Django rest framework, Django channels and React
I want to build a one to one chat application using Django channels. I've already built a public chat app using Django channels, Django rest framework and React (frontend), and now, I want to build a private chat app. Thank you for your help. -
Django - How to change the location of admin static files?
I recently discovered that it's quite easy to check if a site is running on Django as its not possible to change the location of DJANGO Admin styles located at /static/admin/css/base.css The only thing I can change at the path shown above is /static as I set : STATIC_URL = '/static/' at settings.py Is there any way that I can change the path behind /static ? Would be great If I could hide the framework that Im using for my website. Thanks in advance -
rest_framework_jwt | Return custom error message in case of token verification failure
I am using rest_framework_jwt in order to implement token based authentication within my API project based on Django Rest Framework and Python programming language. The issue I am facing right now is that I am getting a random error in response in case an expired token is passed in the header with an API request. I am wandering how I can override that error throwing function and return my own custom response from there. I am getting currently in response is : {"detail": "Signature has expired."} I went through the rest_framework_jwt documentation and found the codes responsible behind throwing that failure response. I tried to change the response object from there but it didn't work and I ran into some other random error. I tried then creating a middleware and there I succeed in returning custom response in case of token verification failure. But now I am unable to login to the system. Codes for the middleware I created are: import jwt from django.utils.encoding import smart_text from django.utils.translation import ugettext as _ from django.http import JsonResponse from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from rest_framework import exceptions from rest_framework.authentication import ( get_authorization_header ) jwt_decode_handler = api_settings.JWT_DECODE_HANDLER jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER … -
Can You do this kind of website with django
I currently learning django . What I want to know is that can I make a website like https://themoviesflix.co/ with django and how much knowledge in django I need to make it. -
Adding Collaborator functionality to my Keep notes app
I am trying to do a clone of Google's Keep Notes app using Django rest framework .I am done with half of the work. But I cant figure out how can I implement that adding collaborator functionality. Any helps ? -
Deserialize Django model with marshmallow
I have 2 models in my Django project: class Item(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=1024) price = models.PositiveIntegerField() class Review(models.Model): grade = models.PositiveSmallIntegerField() text = models.CharField(max_length=1024) item = models.ForeignKey('Item', on_delete=models.CASCADE, related_name='reviews') I want to be able to deserialize Item model with nested reviews in it (which is a queryset of reviews) I described marshmallow schemas in a following way: class ReviewSchemaID(Schema): id = fields.Int() grade = fields.Int() text = fields.Str() class ItemReviewsSchema(Schema): id = fields.Int() title = fields.Str() description = fields.Str() price = fields.Int() reviews = fields.List(fields.Nested(ReviewSchemaID())) But when try to deserialize django object to JSON: item = get_object_or_404(Item, id=item_id) item_data = ItemReviewsSchema().dump(item) I get the following error: TypeError: __call__() missing 1 required keyword-only argument: 'manager' How can I fix the error? -
Where can I find the documentation of Django-filter
There is Django little framework called Django-filter, it is used for filtering looping elements in HTML template. If you are a Django-filter master please help me. The documentation is very short and I couldn't find many things by googling. I want to know how can I set price (increasing and decreasing order), title (A-Z, Z-A). Thank you for your help. -
How Django methods are invokes?
I’m beginner in Django. And I don’t understand how build-in methods Django are invoked. Let’s say we have this view: class HomeNews(MyMixin, ListView): model = News template_name = 'news/home_news_list.html' context_object_name = 'news' paginate_by = 2 def get_queryset(self): return News.objects.filter(is_published=True).select_related('category') def my_method1(self, id): value = id + 123 return = value Will how these methods invoked in my app? I don't call these explicitly. Will these invoked automatically? For example not django code I will invoke like a.method() but here we don't invoke but these work anyway. Explain please, I didn't find any information about this. -
save context elements in database with django
hello im using API arasaac to get images and i display them on a html page, i would like to save the context elements used for each image but i dont know how do to that here it is the view code @login_required(login_url="/login") def search(request): query = request.GET.get('query') if query: picto = api_request(query) form = UserPictogramsForm() message = "voici les résultats pour la recherche %s !" % query empty_message = "Mince nous n'avons trouvé aucun résultat pour '%s'" % query context = {"picto": picto, "message": message, "empty_message": empty_message, } if request.method == 'POST': # save in db {% for image in picto %} <div class="border border-dark col-md-6"> <div> {form.id_picto} <img class="img-fluid d-flex flex-wrap" src="https://api.arasaac.org/api/pictograms/{{ image.0 }}" alt=""> </div> {% if image.2 %} <audio controls src="https://static.arasaac.org/locutions/fr/{{ image.1 }}.mp3"></audio> {% endif %} <p>{{ image.1 }}</p> <button type="submit" class="btn btn-success">Ajouter</button> </div> {% endfor %} </div> So i want that people who click on button the context's elements (image.0 etc..) to be saved in DB. -
Django Rest Framework create pdf file from html
I'm trying to create a pdf file from html content, i did it well with weasyprint pacakge from template.html as a schema to send object of data to this html file and render it as pdf, but now i'm making api endpoint, so the html template won't be in my project,i only will create the object and send it with response, is it right that backend developer create this html document only and return it with response, how about android or ios developers will handle this. -
Query JsonField Django
I have a Schedule model with JSONField: class Schedule(models.Model): shifts = JSONField( ... ) My JsonField data pattern looks like following: { 'id': {'time': ['start_time', 'end_time'], 'department_id': 'department_id'} for example { '31239': {'time': ['09:00:00, '18:00:00'], 'department_id': '8'}, {'8327': {'time': ['11:00:00', '20:00:00'], 'department_id': '1'} ... and I have timestamp variable which is always sharp i.e. 10:00:00 or 14:00:00 but not 12:32:11 Is there any way to retrieve objects which do not have timestamp inbetween their time intervals. For example if timestamp variable equals to 10:00:00 only second example ({'8327': {'time': ['11:00:00', '20:00:00'], 'department_id': '1'}) would be returned. I am doing it in python now, but looking for a way to do it on DB side. -
How to Reordering the objects from ManyToManyField in Django?
i have two models, one is Articles and second is Pool, if i try to Reorder the positioning of objects of Articles or Pool just need to change the model name into get_object_or_404(Articles, pk=int(b['pk'])). But i want to Reordering the position of Pool.articles from (ManyToManyField) inside of Pool articles. i'm confused how can i use the position Field in Pool model for change position of articles. I would be grateful for any help. models.py class Article(models.Model): title = models.CharField(max_length=200) position = models.IntegerField(default=0, blank=True) class Pool(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) views.py def SortAble(request): if request.method == 'POST': books = json.loads(request.POST.get('sort')) for b in arts: try: art = get_object_or_404(Pool.articles, pk=int(b['pk'])) art.position = b['order'] art.save() except KeyError: pass return HttpResponse('saved') -
KeyError in request.session in Django
I have a Django application and I'm trying to pass a parameter from a view to another. However, I'm getting KeyError. Here is my first view; @csrf_exempt def get_checked_values(request): selected_inputs = request.POST.get('selected_inputs') sub_features = json.loads(selected_inputs) request.session['sub_features'] = sub_features return JsonResponse({'status': 'SUCCESS'}) Here is my second view; def optimize_view(request): customer_name = str(request.user) sub_features = request.session['sub_features'] return HttpResponse('Success') I can get the selected_inputs parameter from the request and assign it to the request.session in get_checked_values view but I can't use it in optimize_view because of the KeyError. How can I fix this? -
django admin pass parameters between the save_model and save_related methods
in the save_related method i calculate a total of the prices of items entered in tabularline, this total must appear in the save_model method to save the total purchase. how could I do this ? -
Where to put partial templates for multiple models rendered into a single view?
I have a parent model, let's call it Folder, to which several children models link. All children are subclasses of a base class File. Let's call the children M_File(File) N_File(File), etc. class Folder(models.Model): name = models.CharField(...) meta_data_1 = … class File(models.Model): name = models.CharField(...) class M_File(File): custom_field_1: ... custom_field_n: ... class N_File(File): custom_field_1: ... custom_field_n: ... etc. I would like to build a FolderDetailView which renders also all related files. To render each file, I would like to use a custom template as the files are fairly different. This should be possible by passing all files to the FolderDetailView and looping over them in the template like so: {% for file in files %} {% if file.filetype == 'M_File' %} ...Markup to render M_File... {% if file.filetype == 'N_File' %} ...Markup to render N_File... etc. {% endif %} {% endfor %} Yet looking at this, I cannot help but think that this cannot be the best or pythonic way. Is there another, more elegant way of achieving this? I've been thinking whether it's possible to build something similar to what Forms do when they render themselves once added to the page like so {{ form }}.