Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch with unittest
So it's time to ask my first stupid question. There are two simple identical tests: def test_home_page_status_code(self): response = self.client.get('/en/') self.assertEquals(response.status_code, 200) def test_view_url_by_name(self): response = self.client.get(reverse('web:home')) self.assertEquals(response.status_code, 200) There are two simple urls configs: ... urlpatterns = i18n_patterns( path('', include('web.urls', namespace='web')), ) ... ... urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), ] ... And there's a part of code in the template: {% for lang_code, lang_name in languages %} {% language lang_code %} <a class="dropdown-item" href="{% url request.resolver_match.view_name %}">{{ lang_name }}</a> {% endlanguage %} {% endfor %} If I comment on the code in the template, both tests will pass; if I leave the code, the reverse test will fall. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. What am I doing wrong? Or what parameter do I have to pass in reverse to pass the test? -
How can I save image onece in media folder in django when save in models in for loop?
this query save in models 4 times. but i want to save image one time in media folder! the other question that is there any way to save in models with out for loop? img = 'mage_url' for i in [0,1,2,3]: cmp = CMP_MODEL(age=i,img=img,name='x') cmp.save() -
Why doesn't the django-admin startproject command create a .gitignore file in Django?
Why doesn't the django-admin startproject command create a .gitignore file in Django? -
django use datatable filtering
I use datatable filtering, I send the word searched to the python side with the searchText variable for gender field (Male or Female) but I keep this data integer on the db side, so Male = 1, Female = 2, so my search criterion is not the content of the searchText Male or (M- Ma - Mal - ...) In the same way 1 for Woman (F-Fe-Fem-Fema-...) must be 2. How do I convert the incoming searchText content to this structure searchText = request.GET.get('search') filters = (Q(name__icontains=searchText)|Q(surname__icontains=searchText)|Q(user__username__icontains=searchText)|Q(gender__icontains=searchText)|Q(nationality__icontains=searchText)| Q(staff_type__name__icontains=searchText)|Q(brunch__local_name__icontains=searchText)|Q(staff_status__icontains=searchText)|Q(blood_type__icontains=searchText)) Staff_List = Staff.objects.filter(filters) -
Returning Environmental Variables
I am working on Corey Schafer's blog tutorial and now setting up 'password reset email' using my gmail account as an email client. I want to store my email and password in an environmental variable but when I verify that the information was properly stored it returns none In the terminal I used (nano .bash_profie) export EMAIL_USER='email@gmail.com' export EMAIL_PASS='password' Then I verified import os user = os.environ.get('EMAIL_USER') password = os.environ.get('EMAIL_PASS') print(user) print(password) Other commenters on the tutorial suggested... -restart editor and terminal -Use .zshrc instead of .bash_profile I have tried these other recommendations but still it returns none. I am still new to programming so any suggestion is appreciated. -
Reverse for 'detail' with arguments '('accounts/<int:pk>/',)' not found. 1 pattern(s) tried: ['accounts/(?P<pk>[0-9]+)/$']
In my blog, i want when someone clicks on read more, it should direct the person to the log in page, which is working fine, then after inputting the log in credentials, it should take the person to the detail page and this where I'm getting the error above. this is the code urls.py from . import views from django.urls import path from.views import Home, Detail, CreatePost urlpatterns = [ path('', Home.as_view(), name='home'), path('register/', views.register, name='register'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('post/', CreatePost.as_view(success_url='/'), name='post'), path('accounts/<int:pk>/', Detail.as_view(), name='detail'), ] The line below is from the entry_list.html <a href="{% url 'login' %}" class="btn btn-primary btn-sm">Read More &rarr;</a> Then below is my login logic ``` def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('detail', 'accounts/<int:pk>/') else: return redirect('login') else: return render(request, 'login.html') ``` -
Heroku & Django & Celeri & Redis: "State changed from up to crashed" without any specification
I created a Django app that I deployed on Heroku. The app is processing an important background task (It takes 5-10mn to be run). It involves scraping data and creating a plotly visualisation. The background task is handled through a Celeri app. The communication between Celeri and Django is done with Redis. Everything is working well locally. Everything is working well with a small amount of data scraped (dataframe with 50 rows). But as soon as I increase the amount of data used (dataframe > 50 rows), the Heroku worker crash without any error message. 2020-05-18T12:32:11.945988+00:00 app[web.1]: 10.101.144.240 - - [18/May/2020:12:32:11 +0000] "GET /task/bef2fea5-b7f7-4c37-b32e-2a7888486925/ HTTP/1.1" 200 77 "https://community-detection-instagram.herokuapp.com/parameters/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" 2020-05-18T12:32:14.039229+00:00 heroku[worker.1]: State changed from up to crashed 2020-05-18T12:32:14.042067+00:00 heroku[worker.1]: State changed from crashed to starting It has always happened during the creation of the plot, which is the last step of my background task. Again, the visualisation is working well when I scrape only a few amounts of data (even in production). I thought it could be a memory problem, but it looks that I'm not using all of it. screen of the memory usage from heroku I'm … -
Can't get attribute 'sanitization' on <module '__main__' from 'manage.py'>
This might look like a duplicate question as there are tons of similar questions on StackOverflow but all of them are totally different and none provide the perfect solution. I have a machine learning model that checks for malicious URLs. I am trying to implement this in Django where a user can input the URL and the Django HTML page can show the output. The standalone model is working absolutely file and displaying accurate results. I have saved the model using pickle as well so that it does not require to be trained again. the only problem I am getting is when I enter the input in the input field in Django. I receive the following error. malicious_url.py which is building 2 models in a pickle file. I have added both the models in my app directory including the dataset file. import pandas as pd import numpy as np import random import pickle from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression def sanitization(web): web = web.lower() token = [] dot_token_slash = [] raw_slash = str(web).split('/') for i in raw_slash: raw1 = str(i).split('-') slash_token = [] for j in range(0,len(raw1)): raw2 = str(raw1[j]).split('.') slash_token = slash_token + … -
Django OAuth - Include Authorization Header in Middleware?
I configured django-oauth-toolkit successfully. I want to authorize third party users after receiving an access token from an OAuth Provider. I am able to access restricted websites with it using it like this after saving it in the Django Admin: curl -H "Authorization: Bearer 123456" -X GET http://localhost:8000/secret/ The architecture I imagined was to have a login page where I can store the Authorization token in the headers using Django Sessions. However when I try to set the Authorization header in the middleware it is not letting me access the site. I inspected the response when I visited the site and it does not look like I'm saving the headers at all. I tried with the code below. class OAuthDt: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): def process_request(request): request.META['Authorization'] = "Bearer 123456" return(request) request.Authorization = "Bearer 123456" request = process_request(request) response = self.get_response(request) return(response) Views.py @login_required() def secret_page(request, *args, **kwargs): return HttpResponse('Secret contents!', status=200) So my guess is that either: The authentication check in my view is done before the Middleware saves the Header. There is something preventing me from updating the request headers or overwriting my header. Maybe another middleware I am more inclined towards number … -
How to read Excel cell data in HTML format in Django
how to read below excel cell data Country: India State: Karnataka into <p>Country:<strong> India</strong><br /> State:<strong> Karnataka</strong></p> in Python Django? -
Sort a list using both alphabatically and Integer in python
I have a text file which contains timestamp and exception name. Text file looks something like this. 1573594032526 NullPointerException 1573594032527 NullPointerException 1573594032528 IllegalAgrumentsException 1573596032526 UserNotFoundException 1573597032526 NullPointerException I have converted them into hour, minute and second by: data = [] for line in resp.text.splitlines(): split_ = line.split() date = datetime.utcfromtimestamp(int(split_[1]) / 1000) data.append({ "second": date.second, "minute": date.minute, "hour": date.hour, "data": split_[-1], ------> exception name }) I have to sort them according to timestamp as well as name i.e the output should be: 21:15-21:30 IllegalAgrumentsException 1, 21:15-21:30 NullPointerException 2, 22:00-22:15 UserNotFoundException 1, 22:15-22:30 NullPointerException 1, so in this case timestamp for NullPointerException and IllegalAgrumentsException are same(in terms of hours,minutes and second) so alphatically IllegalAgrumentsException comes first. Also at end of each line the number is count of exceptions in that time range. How can I acheive this ? -
how to write variable in django template
{% for card in cards %} <tbody> <tr> <th scope="row">{{rankHash}}</th> </tr> </tbody> {% endfor %} This is my template view. cards query just like below. <QuerySet [<Card: Card object (2)>, <Card: Card object (10)>, <Card: Card object (6)>, <Card: Card object (1)>, <Card: Card object (9)>, <Card: Card object (5)>, <Card: Card object (4)>, <Card: Card object (7)>, <Card: Card object (3)>, <Card: Card object (8)>, <Card: Card object (11)>]> if I print {{card.furniture}} , output is some integer like 155 {{rankHash}} print {155: 1, 142: 2, 129: 3, 128: 4, 125: 5, 120: 6, 117: 7, 110: 8, 109: 9, 108: 10, 60: 11} So, I want to print key 1 by value 155. But if i type {{rankHash[155]}}, below error appear. Could not parse the remainder: '[155]' from 'rankHash[155]' I also already know if i type {{rankHash.155}} , output is 1. But {{rankHash.[card.furniture]}} print same error Could not parse the remainder: '[card.furniture]' from 'rankHash[card.furniture]' What is the appropriate answer what I want? -
Why wagtail doesn't recognize my templates?
I've created a doctrina app, I've been explicit to tell the model where to look for the template: template = 'doctrina/doctrina_index_page.html' Why is it saying it can't find it? doctrina/models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class DoctrinaIndexPage(Page): template = 'doctrina/doctrina_index_page.html' nivel = models.CharField(max_length=255, default='Básico') subtitle = models.CharField(max_length=255, default='Publicación reciente') body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('subtitle', classname="full"), FieldPanel('body', classname="full") ] this is the main app, where setting are, I've added explicitly the doctrina/templates in the DIRS: Wagtail Admin: -
Why my serializer code returns exception?
I am trying to create an article by taking data but i get an exception by unknown case. I already declared what is necessary and i can register users.I use another views and serializer to post data and it is fine but this one is not. Anybody knows why? Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def post(self, request, format=None): try: serializer = self.serializer_class(data=serializer_data, context=serializer_context,) serializer_context = { 'request': request } serializer_data = request.data.post('article',{}) if serializer.is_valid(): serializer.save(author=self.request.user.profile) return Response(serializer_data, status=status.HTTP_201_CREATED) else: return JsonResponse({'fail':'True'}) except Exception as e: return JsonResponse({'exception':'True'}) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleCreateSerializer() return Response(serializer.data) Serializers.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) details = serializers.CharField(required=False) author = UserSerializer(read_only=True) class Meta: model = Article fields = ('id','author','caption','details') def create(self, validated_data): article = Article.objects.create(**validated_data) return article It returns {"exception": "True"} But the django shell output is fine "POST /api/createarticle/ HTTP/1.1" 200 21 -
Django, how to fix max decimal in floatfield in annotate?
I have the following code: annotate(totale=ExpressionWrapper(Sum(F('prezzo')*0.50/12),output_field=FloatField() but in my template I have as results (for example) 145,555555555555555555555555 instead 145,55 I have added |intcomma but the result is the same. How could I fix this ?? -
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Satyan\AppData\Local\Temp\pip-install-b7a4lhpy\psycopg2\
I am trying to connect PostgreSQL and Django. Whenever I install psycopg2 in Pycharm. I am getting the following error : Command "python setup.py egg_info" failed with error code 1 in C:\Users\Satyan\AppData\Local\Temp\pip-install-b7a4lhpy\psycopg2\ Python Version - 3.8.2 Django Version - 3.0.6 Windows 10(64-bit) Tool - Pycharm -
Why can't i see my updated list of an app created with Django?
I would like to update my list after adding some inputs through a form but i cannot see my updated list. I see the existing items in my list ,but when i add a new item it does not appear on the list. I can manually add it using the admin pannel and view it in the list(a whole different path),but not with the form i created to take input and update the list. Below is my code models.py class BlogPost(models.Model): notes = models.CharField(max_length = 1000000000000000000000000000) date = models.DateTimeField(auto_now_add=True) done = models.BooleanField(default=False) def __str__(self): return self.notes form.py from blog.models import BlogPost class BlogForm(forms.ModelForm): class Meta: model = BlogPost fields = ['notes', 'done',] views.py from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect,HttpRequest from blog.models import BlogPost from blog.form import BlogForm def home(request): context = { 'welcome_text': 'Welcome to the home page. View some more stuff soon' } return render(request,'home.html', context) def blogpost(request): if request.method == "POST": form = BlogForm(request.POST) if form.is_valid(): if form.save(): message.success(request, "the task was added") return redirect('blogpost') else: all_blogs = BlogPost.objects.all return render(request, 'blog.html',{'the_blogs': all_blogs } ) blog.html {%extends 'base.html' %} {% block title%} <title> Blog </title> {% endblock title%} {%block content %} <div class="container"> <br> {%for message … -
ModuleNotFoundError when running wsgi.py
I am given this error when running the wsgi.py file. It happens with and without gunicorn. 2020-05-18T12:49:45.264850+00:00 app[web.1]: application = get_wsgi_application() 2020-05-18T12:49:45.264851+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-05-18T12:49:45.264851+00:00 app[web.1]: django.setup(set_prefix=False) 2020-05-18T12:49:45.264851+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 19, in setup 2020-05-18T12:49:45.264852+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2020-05-18T12:49:45.264852+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ 2020-05-18T12:49:45.264853+00:00 app[web.1]: self._setup(name) 2020-05-18T12:49:45.264853+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup 2020-05-18T12:49:45.264853+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2020-05-18T12:49:45.264861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ 2020-05-18T12:49:45.264862+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2020-05-18T12:49:45.264862+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module 2020-05-18T12:49:45.264862+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-05-18T12:49:45.264863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import 2020-05-18T12:49:45.264863+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load 2020-05-18T12:49:45.264864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked 2020-05-18T12:49:45.264864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-05-18T12:49:45.264864+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import 2020-05-18T12:49:45.264865+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load 2020-05-18T12:49:45.264865+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked 2020-05-18T12:49:45.264865+00:00 app[web.1]: ModuleNotFoundError: No module named 'image_editor' My structure is image_editor_proj>image_editor>wsgi.py -
can anyone explain why this is giving error django url patterns
urlpatterns= [path(r"<int:id>", ThreadView.as_view(),name="thread-view"),] why this is giving an error.If I put r"<int:id>/" It is not giving error -
Why cant I access DB data on Django Model?
Im getting issues accessing a model from Start.models import Login def CheckCredentials(request,userName,userPass): user = Login.objects.all() print(user) return HttpResponse("NotNice") this is the code i have in my views.py file, but for some reason its showing the "Login has no objects members "issue. Can someone help me understand why ? Thank you, Stan -
Accessing Crispy Form Attributes Within A Custom Template
I've created a custom template for my crispy form but do not know how to access the field attributes. The attributes I am after are the key/value for a CheckboxMultipleSelect. TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), 'ANI' would be the first value, and 'Animals' would be the first name template - {% load crispy_forms_field %} <div id='div_id_preferred_topics' class="form-group"> <label for='id_preferred_topics'>{{ field.label }}</label> <div class> {% for field in form.preferred_topics %} <div class='custom-control custom-checkbox custom-control-inline'> <input type='checkbox' class='custom-control-input' name='preferred_topics' id='{{ field.id_for_label }}' val='<!-- ???value here??? -->'> <label class='custom-control-label' for='{{ field.id_for_label }}'><!-- ???name here??? --></label> </div> {% endfor %} </div> </div> Thank you -
Django looping through queryset only once
I'm working on a project and I ran into one problem. I'm looping through a queryset and the for loop is running only once without giving any error. This problem was not happening earlier but now it came out of nowhere. below is my code. views.py ward = Student.objects.get(id = request.POST.get('ward')) request.session['student'] = request.POST.get('ward') fees = Fee.objects.get(classes = ward.classes) extras = ExtraFee.objects.filter(student = ward) ex = ExtraFee.objects.filter(student = ward).values('title').annotate(Count('title')) print(ex) for e in ex: print(e) title = e['title'] if e['title__count'] > 1: print(title) extra = ExtraFee.objects.filter(title = e['title'], student = ward) amount = 0 fine = 0 for ex in extra: amount = int(ex.amount) + amount total = amount for exs in extras: fine = int(exs.amount) + fine totalfine = fine return render(request, "dashboard/parent_fees.html", {"students": students, "parent": parent, "ward": ward, "fees": fees, "extras": extras, "totalfine": totalfine, "total": total, "title": title}) else: fine = 0 for e in extras: fine = int(e.amount) + fine totalfine = fine return render(request, "dashboard/parent_fees.html", {"students": students, "parent": parent, "ward": ward, "fees": fees, "extras": extras, "totalfine": totalfine}) Thanks in advance for your time and help. -
Django Rest Framework serialize additional fields from intermediate model
I am developing a small application that lists the customers of a store. I'm trying to retrieve the additional fields of the intermediate model because a contact can belong to several stores but depending on the store it is premium or not and if he is happy or not. Here's the JSON response I'd like to get: [ { "id": "UX", "first_name": "UX", "last_name": "UX", "email": null, "mobile": null, "happy": True, "premium": True }, { "id": "AX", "first_name": "AX", "last_name": "AX", "email": null, "mobile": null, "happy": False, "premium": True } ] here are my models: class Store(BaseModel): id = models.CharField(primary_key=True, max_length=200) name = models.CharField(max_length=100) class Contact(BaseModel): id = models.CharField(primary_key=True, max_length=200) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True, blank=True) mobile = models.CharField(max_length=100, null=True, blank=True) stores = models.ManyToManyField( Store, through="MemberShip", through_fields=("contact", "store") ) class MemberShip(BaseModel): contact = models.ForeignKey( Contact, on_delete=models.CASCADE, related_name="contact_to_store" ) store = models.ForeignKey( Store, on_delete=models.CASCADE, related_name="store_to_contact" ) happy = models.BooleanField(default=True) premium = models.BooleanField(default=False) and my serializers: class MemberShipSerializer(serializers.ModelSerializer): class Meta: model = MemberShip fields = ("contact", "store", "happy", "premium") class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = ("id", "name") class ContactSerializer(serializers.ModelSerializer): infos = MemberShipSerializer( source="contact_to_store" many=True, read_only=True ) class Meta: model = … -
Convert software version number to queryset compatible order by integers
I have an attribute "software_version" which is an charfield. Some examples: ['1.1.0', '6.4.7', '6.4.7rc1', '6.4.8', '6.4.9', '6.4.10', '10.9.8', '100.10.20', '1000.1.2'] Sometimes, when the user wants it, it needs to be sort-compatible. So when I do a filter on my model, I need to order_by on the software versions. My approach: I create a second attribute in my model 'numeric_software_version". Here I will store a numeric version of the s_v that can be used to sort using queryset. So, my approach now in short words: divide every part to 100 and paste them to each other. My code: import re component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) def create_sort_value(version): components = [x for x in component_re.split(version) if x and x != '.'] new_version = "" for i, obj in enumerate(components): try: components[i] = int(obj) new_version += str(int(obj) / 100) except ValueError: new_version += str(obj) return new_version.replace('.', '') def sort_versions(versions): v = {} for version in versions: v[create_sort_value(version)] = version print({k: v[k] for k in sorted(v)}) if __name__ == '__main__': versions = ['1.1.0', '6.4.7', '6.4.7rc1', '6.4.8', '6.4.9', '6.4.10', '10.9.8', '100.10.20', '1000.1.2'] sort_versions(versions) This gives following output: About • FAQ • Blog • Terms of Use • Contact Us • GDB Tutorial … -
Disable django-summernote resizing uploaded images
I have django_summernote integrated in my project. Upon image uplaod it appears fitted to the editor Though, I want to disable some of these buttons: Because if the image is set to its original size, it would not fit its place in the frontend. I would like to disable it for the potential user