Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detecting Django/Python None value inside JS code
Actually, it is a question of best practice and elegance. Imagine I have JS code like this: my_js_func() { let var_coming_from_backend = {{ some_var || '' }} if (...) { } } What is the most proper way to check some_var is None? Currently, I am doing that this way: let var_coming_from_backend = {{ some_var|default:'' }} if (var_coming_from_backend == '') { } But it seems like junk code to me. -
Django: Insert image to PostgreSQL (PgAdmin4)
Im currently working an e-shop. So my idea is to store images with Django models in PgAdmin4. As i saw in older posts methods like bytea('D:\image.jpg') and so on just converts the string constant to its binary representation. So my question is if there is a newer method to store the actual image, or if it is possible to grab the image via a path? models.py image = models.ImageField(null=True, blank=True) PgAdmin4 INSERT INTO product_images( id, image) VALUES (SERIAL, ?);// how to insert image? -
exclude option in selectField (ForeignKey)
i have a field in my model: myuser = models.ForeignKey(MyUsers, on_delete=models.SET_NULL, blank=True, null=True) in database table "MyUsers" - 10 users. How to exclude some of this 10 users from choise option in form (by id or name)? -
Django order by postgresql range type
Which would be the best way to use django ORM 2.2 to apply this PosgreSQL query? SELECT * FROM my_table ORDER BY lower(range_column); Thanks a lot -
Django Rest Framework JWT: How to change token expiration message
When the JWT token that I'm sending is expired, I'm getting this message... { "detail": "Signature has expired." } Now, I want to change the response with my custom message, like... { "message": "token has expired.", "data": null, "status": 401 } I tried it to do within APIView, but It's not working. -
How to return single object from queryset in Django Rest Framework?
I want to retrieve the title_picture of a Story. When i retrieve the Story I get the the result as a list. However as there is only a single title picture per Story, I want the object directly and not stored as part of a list. // Current Output "title_picture": [ { "id": 9, "isTitlePicture": true, "file": "/media/story_media/1_Bm1qVip.jpeg" } ] // Target Output "title_picture": { "id": 9, "isTitlePicture": true, "file": "/media/story_media/1_Bm1qVip.jpeg" } class StoryRetrieveSerializer (serializers.ModelSerializer): story_media = serializers.SerializerMethodField('get_story_media') class Meta: model = Story fields = ('title', 'story_media') def get_title_picture (self, story): qs = Story_Media.objects.filter(story=story.id, isTitlePicture=True) serializer = Story_Media_Serializer(qs, many=True) return serializer.data My first attempt was to take out the many=True. However than the title picture is not fetched any more and all the data is null. I'am happy for any hint. -
Websocket/REST API - which of them for a large request scenario?
I know that they are two different things and technical approaches, but consider this scenario: i have a third party application that will interface with my own application and every 5 minutes has to push to my services a large JSON (about 3/4MB). My application consists in a Python-Django web application with Gunicorn serving WSGI requests and DAPHNE serving ASGI connections, in front of that i've placed a NGINX as reverse proxy. In the web application i've created basically two endpoints: REST Insert API endpoint Websocket endpoint that exposes a receiver (in order to insert data In my test environment, i've seen that when i try to push the JSON to the websocket endpoint, many times the websockets will get closed with this error message: "HTTP_UPDATE_FAILED Error (-104): Wrong HTTP Code" The WS endpoint in NGINX is configured as below: location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_connect_timeout 15s; proxy_send_timeout 3600s; # ws will open for 1 hour proxy_read_timeout 3600s; proxy_buffers 512 256M; proxy_buffer_size 256M; proxy_pass http://daphne_server; #DNS resolved by internal docker dns server } In order to circumvent the problem, i've tried to reduce the websocket message payload many times up to … -
flake8 ignoring configuration files
Steps I installed flake8: pip install flake8 Created a tox.ini file: [flake8] exclude = */migrations/* Then I ran flake8: flake8 Expected results Only get errors outside migration directories. Actual results I still get errors inside migration directories. When I run the command manually, it works: flake8 --exclude=*/migrations/* I get other errors, but not inside migration folders. Any idea what I could be doing wrong? As far as I can tell I'm simply following the documentation word by word. I'm surprised I didn't find many other threads about this problem. -
how to limit user access to url? [closed]
hello guys so i have this problem i want to ask so i have this django project that inside of it have 2 apps one is the website that only network admin have access and one is a call back server that handle the request of user (because i need the data of user to used in website admin), and because i am still confused to restrict people to get inside the admin login page url other people that's not admin still can access the admin login page, so i want to ask how to restrict people to access this login page? thanks :) -
Display sub menu with django cms
I try to display sub menu with the tag "show_sub_menu". I have many sub menus : Menu1 sub menu1 sub menu2 Menu2 sub menu3 sub menu4 ... If I am on a page contained in menu1 or its sub-menus, I want to display a list with : sub menu1 sub menu2 If I am on a page contained in menu2 or its sub-menus, I want to display a list with : sub menu3 sub menu4 So, I created a new template : {% extends "base.html" %} {% load cms_tags menu_tags sekizai_tags %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} <div class="row"> <div class="col-8"> {% placeholder "content" %} </div> <div class="col-4"> {% show_sub_menu 1 %} </div> </div> {% endblock content %} It's works when I open in the page Menu1 or Menu2 but not when I open the pages "sub menu*". I try with : {% show_sub_menu 0 %} or {% show_sub_menu -1 %} but it doesn't work, nothing is displayed. -
Error in migrations after removing image field and upload_to_path method
I had a field called image in my model. image = models.ImageField(upload_to=get_profile_pic_upload_path) I created the migration for the same and applied it. After a few more migrations and changes, I decided to remove the field. I was able to do that and apply the migration as well. Now I realized I missed deleting the extra upload_to method. When I remove the method from my codebase, I am getting the following error from my initial migration. AttributeError: module 'users.models' has no attribute 'get_profile_pic_upload_path' I see that there a reference to my upload_to method, which is failing. Now as the field has been removed all together this should not happen. What is the best way to handle this? -
Django/Mezzanine - admin: Add "Save and add another to current parent" button
What would be the best way to add the functionaliy to "Save and add another file to current parent" to the admin in Django (/Mezzanine)? So far I've found the template to add the button, but am unsure of how to add a function to do this - while I've reviewed django.contrib.admin.ModelAdmin, as an amateur developer I'm unsure of the best practice for making the tag. I currently think that the basic principles should be to make/import a custom tag that does the below: save() on the item that's currently being created reload the page with the addition of "?parent={{original.pk}}" to the URL. ...but I am unsure on the best way to do this. Any advice would be greatly appreciated! Rich -
Fitler DateTimeField with DateFilter in django-filter
I have a model which has create_date, update_date, release_date DateTimeField. I wish to have the filter to filter these DateTimeField with DateFilter. Here is one way I can do that: class ProductFilter(django_filters.FilterSet): create_date = DateFilter(field_name='create_date', lookup_expr='date') create_date__gt = DateFilter(field_name='create_date', lookup_expr='date__gt') create_date__lt = DateFilter(field_name='create_date', lookup_expr='date__lt') create_date__gte = DateFilter(field_name='create_date', lookup_expr='date__gte') create_date__lte = DateFilter(field_name='create_date', lookup_expr='date__lte') update_date = DateFilter(field_name='update_date', lookup_expr='date') update_date__gt = DateFilter(field_name='update_date', lookup_expr='date__gt') update_date__lt = DateFilter(field_name='update_date', lookup_expr='date__lt') update_date__gte = DateFilter(field_name='update_date', lookup_expr='date__gte') update_date__lte = DateFilter(field_name='update_date', lookup_expr='date__lte') release_date = DateFilter(field_name='release_date', lookup_expr='date') release_date__gt = DateFilter(field_name='release_date', lookup_expr='date__gt') release_date__lt = DateFilter(field_name='release_date', lookup_expr='date__lt') release_date__gte = DateFilter(field_name='release_date', lookup_expr='date__gte') release_date__lte = DateFilter(field_name='release_date', lookup_expr='date__lte') You may see that things get repetitive. Is there any way to encapsulate the logic? P.S. I know I can use Meta.fields like: class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = { 'create_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], 'update_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], 'release_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], } but the filter name will become create_date__date instead of create_date. -
what are the configuration in settings.py to send e-mail using Django from business outlook email (eg .. - office@test.com )
i have been trying to send email using this configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 25 EMAIL_HOST_USER = 'office@test.com' EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = 'office@test.com' but I am getting error saying that OSError at /product_detail/test/ [Errno 101] Network is unreachable -
dynamically viewing and downloading pdf in django
i want to view and download pdf of some invoices in my ecommerce web.i gave my view function here.unfortunatly i couldnt display any data which i viewd dynamically. def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('reportpdf.html') return HttpResponse(pdf, content_type='application/pdf') class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf=render_to_pdf('reportpdf.html') response=HttpResponse(pdf, content_type='application/pdf') filename="report%s.pdf"%("12341231") content="attachment; filename='%s'" %(filename) response['Content-Disposition']=content return response -
I Want to access the variable of a if statement in the function .Python
def Home(request):#django if request.method == 'POST': city = request.POST.get('search') print(city) URL = f'http://api.openweathermap.org/data/2.5/weather?q={city} -
DJANGO - How to JSON response a dict?
After a lot of process, I got a result of a number _price = 45000. I want to response in a format like this: [{"_price": "45000.0"}] I did this result = {"_price":_price} return json.dumps(result) I got this AttributeError: 'str' object has no attribute 'get' result = list({"_price":_price}) return JsonResponse(result, safe = False) Got this [ "_price" ] result = list({"_price":_price}) return HttpResponse(result) Got this _price -
Django - Why cannot loop through the retrieved model objects?
I'm new to Django, I wanted to loop through all the objects stored in database, but I'm not able to. I don't really understand the problem, I searched the web for problems related, but I still couldn't find any solution, could anyone please help me? The problem encountered is : 'Resume' object has no attribute 'seek' Here is some of the code, I believe the problem is in the first 3 lines: resumes = Resume.objects.all() for i in range(len(resumes)): file = docx2txt.process(resumes[i]) text = [file, jobdesc] cv = CountVectorizer() count_matrix = cv.fit_transform(text) percentage = cosine_similarity(count_matrix)[0][1] * 100 percentage = round(percentage, 2) If I used for i in resumes.iterator(), the problem encountered would be: QuerySet indices must be integers or slices, not Resume. Resume model: class Resume(models.Model): resume = models.FileField('Upload Resumes', upload_to='resumes/', blank=True, null=True) name = models.CharField('Name', max_length=1000, null=True, blank=True) email = models.CharField('Email', max_length=1000, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=10000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=10000, null=True, blank=True) college_name = models.CharField('College Name', max_length=10000, null=True, blank=True) designation = models.CharField('Designation', max_length=10000, null=True, blank=True) experience = models.CharField('Experience', max_length=10000, null=True, blank=True) uploaded_on = models.DateTimeField('Uploaded On', auto_now_add=True) def __str__(self): return self.name -
405 error while generating a pdf in Django3
I followed this coadingforentrepreneurs tutorial to generate pdfs and it works fine. The issue is when i use a post request to generate a pdf it shows me a 405 error. I am using post method to access customer-id to generate a invoice. Here is my GeneratePDF class class GeneratePDF(View): def get(self, request, *args, **kwargs): if request.method == 'POST': template = get_template('head/invoice.html') context = { "customer":"aaaa" } html = template.render(context) pdf = render_to_pdf('head/invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response template = get_template('head/invoice.html') context = { "customer":"aaaa" } html = template.render(context) pdf = render_to_pdf('head/invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response I have not edited any other files Here is the response from the server Method Not Allowed (POST): /employee/customer_printbill/ Method Not Allowed: /employee/customer_printbill/ I am a beginner in django and i am unable to resolve this issue. Please help me out. -
Can I add 2 or more different forms in the same template?
I am new to Django and was working on a page where I need to allow the user to place a bid on an item, leave a comment or add/remove this item from his watchlist so I thought I would need to have a form for each of these tasks, but all I found about multiple forms was formsets and that's not what I need. So my question is how can I have more than 1 form in a template or what are the alternative ways to do this? Thanks in advance -
NoReverseMatch at /update/
I'm using the author name for posts in the url. I get this error after clicking on the submit button when updating the post or creating a new post: Reverse for 'post-detail' with keyword arguments '{'id': 2, 'author': 'john'}' not found. 1 pattern(s) tried: ['(?P<author>[^/]+)\\/(?P<pk>[0-9]+)\\/$'] models.py class Post(models.Model): title = models.CharField(max_length=100, blank="true") content =models.TextField(default="Enter details", verbose_name="Content") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'id' : self.pk, 'author': self.author.username}) Views.py class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py urlpatterns = [ path('<str:author>/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('<str:author>/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), ] -
DetailView is missing a QuerySet Error. shouldnt it work with the primary key?
Quite new to this super nice django thing. Trying my best... trying http://127.0.0.1:8000/angebot/1/ in my browser is supposed to show me the queryset with the primary key 1 from model Testkunde do i need to define a queryset in the detailview ?? normally with model = Testkunde this should be done ?? would really appreciate any help ! thanks in advance! views.py class TestkundeDetailView(DetailView): model = Testkunde template_name = 'angebot/detail.html' context_object_name = 'testkunde_list' urls.py urlpatterns = [ #path('', angebot_views.testkunde_list, name='testkunde_list'), path('', angebot_views.TestkundeListView.as_view(), name='angebot-list'), path('<int:pk>/', angebot_views.DetailView.as_view(), name='angebot-detail'), ] models.py class Testkunde(models.Model): auswahl = ( ('Ausw1', 'Ausw2'), ('Ausw2', 'ausw2'), ('Ausw3', 'ausw3'), ) vname = models.CharField(max_length=250,default='vname') nname = models.TextField(default='default') tel = models.CharField(max_length=250,default='0664') ausw = models.CharField(max_length=10,choices=auswahl,default="Ausw1") datum = models.DateTimeField(default=timezone.now) def __str__(self): return self.vname def get_absolute_url(self): return reverse('angebot:testkunde_list',) Error: ImproperlyConfigured at /angebot/1/ DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/angebot/1/ Django Version: 3.0.8 Exception Type: ImproperlyConfigured Exception Value: DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Exception Location: C:\Users\berni\PycharmProjects\django_project\venv\lib\site-packages\django\views\generic\detail.py in get_queryset, line 73 Python Executable: C:\Users\berni\PycharmProjects\django_project\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\berni\PycharmProjects\django_project\django_project', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\berni\AppData\Local\Programs\Python\Python37', 'C:\Users\berni\PycharmProjects\django_project\venv', 'C:\Users\berni\PycharmProjects\django_project\venv\lib\site-packages'] Server time: Fri, 27 Nov 2020 08:19:51 +0000 I've been searching but can't find the … -
How to customize form (html) with fixed heading title and fixed footer with validation forms buttons?
I develop Django apps and need to customize standard form for data entry that fit the structure in attached image bellow. You can also see my current code that "do the job" but would like to know if it is the good way to do that or if there is better practices. I have define css classes for my fixed heading-title, fixed footer-bottom and for my 2 buttons "Save" and "Cancel" html <nav class="navbar navbar-expand-md navbar-dark bg-info fixed-top" style="padding-top: 50px;">...</nav> <!-- content form for field data entry --> <div class="box row-full" id="heading-title"> <h3>Nouveau projet</h3> </div> <div class='container' style="margin-top:200px;margin-bottom:200px"> <form id="projecteditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <button id="ajouter_projet" class="btn btn-info .fixed-save" type="submit" style="width: 100px; z-index:2">Valider</button> <a data-modal data-target="" class="btn btn-dark .fixed-cancel" href="{% url 'project:index_projet' %}" style="width: 100px; z-index:2">Annuler</a> </form> </div> <div class="box row-full" id="footer-buttons"></div> <!-- end content form for field data entry --> <footer class="page-footer font-small blue fixed-bottom" style="background-color:white; z-index:1">...</footer> css .box { width: 100px; max-height: 60px; color: white; } #heading-title { position: fixed; padding-top: 20px; top: 100px; color:black; background: white; } #footer-buttons { position: fixed; bottom: 50px; background: white; } .row-full{ width: 100vw; position: relative; margin-left: -50vw; text-align: center; height: 100px; left: 50%; } .fixed-save{ position: fixed; … -
Django does not use index on ordering
I'm trying to optimize a query in Django (version 1.11) that I use in a prefetch. So I have a StaffProfile model that has a relation to Wages like this: class Wages(Model): # ... staff = models.ForeignKey('StaffProfile', on_delete=models.CASCADE, null=True) title = models.CharField(_('Title'), max_length=50) class StaffProfile(Model): # ... objects = StaffProfileManager.from_queryset(StaffQuerySet)() The StaffQuerySet has a dedicated method: class StaffQuerySet(QuerySet): def my_prefetch( ) -> QuerySet: return self.prefetch_related( Prefetch( 'wages_set', queryset=Wages.objects.filter( # ... ).order_by( Upper('title') ), to_attr='prefetched_wages' ), ) What I noticed is that When I run this query: Wages.objects.all().order_by(Upper('title')) my database (PostgreSQL) obviously sorts the results (below is the output from the EXPLAIN run on the generated SQL): Sort (cost=21.31..21.86 rows=220 width=166) Sort Key: (upper((title)::text)) -> Seq Scan on staff_wages (cost=0.00..12.75 rows=220 width=166) So I've tried to set an index on the title field. In order to achieve this I've created a migration: class Migration(migrations.Migration): dependencies = [ ('staff', '0020_merge_20201116_0929'), ] operations = [ migrations.RunSQL( sql='CREATE INDEX "staff_wages_title_upper_idx" ON "staff_wages" (UPPER("title"));', reverse_sql='DROP INDEX "staff_wages_title_upper_idx";' ) ] I've run it and I see it was created in the database. However, when I now run my query, the EXPLAIN gives exactly the same output, whereas I expected it to use my index. What am … -
Is there any inbuilt function in django to clean the data in a request.POST dictionary key?
All the inbuilt cleaning methods seem to be only for the Django Forms. I find editing the style of those forms complex and that's why I just prefer create traditional HTML forms and later supply the data from request.POST to the required Django Model. Is there any inbuilt workaround for cleaning such data in Django or I'll have to write a function myself?