Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Arrow up or down in django
I have a column called kpi_delta_ind. If the column is 0 or 1,the arrow should be pointing upwards and downwards if it is <0. I am trying to use hexacode in my views.py file but it prints the code.Is there any way we can use hexacode in my views.py file or do i need to write condition in html file. Here is my Views.py file. def info(request): L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): print('&#x25B2;') elif (int(row.kpi_delta_ind) < 0): print('&#x25BC;') elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'WORKER_PORTAL' and row.kpi_key == 'WP_PAP_SUB'): L_P_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' and row.kpi_key == 'RED_INIT'): L_N_I = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' … -
Django getting NoReverseMatchexception
My root urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # new ]+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) My pages app urls.py from django.contrib import admin from django.urls import path from pages import views urlpatterns = [ path('', views.home_page, name='home_page'), path('<tab>', views.home,name='home'), ] With this, I am able to access 127.0.0.1:8000/Home 127.0.0.1:8000/About 127.0.0.1:8000/Services 127.0.0.1:8000/Portfolio All the tabs with url entry. But, when I create an url entry in html template, {% url 'About' %} getting NoReverseMatch -
Im trying to split django rows by the category Ativos like the exemple below
im getting this enter image description here but i whant this enter image description here is there a way to get this result? -
Create Login View using Django simpleJWT
I'm trying to implement a login API using JWT Authentication. I used the simpleJWT in Django. my setting.py 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),} } my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('apartments.urls')), path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view()), path('api/token/refresh/', TokenRefreshView.as_view()) ] I want to use the default user model for the login.Also the login must be done only if the user is authenticated. And I need get a POST request and to return the users credentials and the two tokens in my response body. How can I adjust my loginview accordingly? def login_view(APIrequest): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = User.objects.get(username=username) if user.check_password(password): username = user.username user = authenticate(username=username, password=password) print("Login successful") login(request, user) ``` -
Django - Exception Value: Unexpected end of expression in if tag
I can't figure out what the error could be. I have checked the docs to see if there were any syntax changes but I don't find any. Unexpected end of expression in if tag. Template error: In template /home/dhruv/django-blog/blog/templates/blog/post_detail.html, error at line 5 Unexpected end of expression in if tag. 1 : {% extends 'blog/base.html' %} 2 : 3 : {% block content %} 4 : <div class="post"> 5 : {% if post.published_date %} 6 : <div class="date"> 7 : {{ post.published_date }} 8 : </div> 9 : {% elif %} 10 : <a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}"> 11 : Publish! 12 : </a> 13 : {% endif %} 14 : 15 : {% if user.is_authenticated %} -
How to write a `localStorage` sting to a django model field
I have a string which I saved it on a kind of array in localStorage using jquery and I need to save it in a field in my form. in .js file this is the variable: $("input[name=second_step-tags]").val(array.join(', ')); # its something like A, B, C... and as I am using a wizard form, I'm trying to save write this variable into a django field which is like: {{ wizard.form.tags }} which I am putting the rendered value of template to replace the jq varibale on it as: <input name="second_step-tags" id="id_second_step-tags" cols="3" rows="3" class="textarea form-control" disabled="yes"></input> But it does not work! -
python Django REST Framework CSRF Failed: CSRF cookie not set?
I have a web-application that I need to do some API level testing. I was able to make a Django Post request API call in curl command as this: curl 'https://my-server.com/blablabla/api/public/v1/profiles' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: https://my-server.com/blablabla/api/public/v1/profiles' -H 'X-CSRFToken: ...' -H 'Connection: keep-alive' -H 'Cookie: csrftoken=...; sessionid=...' -H 'Content-Type: application/json' --data-binary '{"group":"1","name":"XYZ"}' But, if I was trying to port the similar code into python3 as follows: #!/usr/bin/python3 import requests import json TOKEN = 'X-CSRFToken: ...' COOKIE = 'Cookie: ...; sessionid=...' headers = {'X-CSRFToken': TOKEN, 'Cookie': COOKIE} post_data = '{"group":"1","name":"XYZ"}' response = requests.put("https://my-server.com/blablabla/api/public/v1/profiles", data=post_data, headers=headers) print(response.json()) print(response.ok) print(response.status_code) I have got such failure in return, {'msg': ['CSRF Failed: CSRF cookie not set.']} False 403 Does anyone know what could be wrong ? -
Why user.has_perm return false although my admin panel show me it has a permission
Hey I have a little problem with my permission in Django. In my admin panel everything seems be ok, user has all needed permission but if I try to use @permission_required decorator or has_perm test return 'false' Here is my code: models.py: ... class Comments(models.Model): photos = models.ForeignKey(UserPhotos, on_delete=models.CASCADE) comment = models.CharField(max_length=200) date = models.DateTimeField(auto_now=True) class Meta: '''Change plural name''' verbose_name_plural = 'Comments' def __str__(self): return self.comment ... views.py: ... def homeView(request): # Here is my has perm test. print(request.user.has_perm('accounts.add_comments')) #Return false. context = {} user = request.user num_visit = request.session.get('num_visits', 0) request.session['num_visits'] = num_visit + 1 if not user.is_authenticated: return redirect('instagra:login') else: context['user'] = NewUser.objects.filter(pk=user.pk) context['photos'] = UserPhotos.objects.filter(user=user.pk) context['num_visits'] = num_visit return render(request, 'main/home_view.html', context) ... -
Django admin calling the ```.save()``` method when trying to log in to the admin site
The auth user model extends AbstractUser and overrides the .save() method. The model contains two mandatory and unique fields. It also calls .full_clean() in the .save() method. The problem arises when an admin tries to log in. Django throws a validation error saying those two fields can't be blank. The error goes away when .full_clean() is commented out. Why does Django admin call the .save() method while trying to log in to the admin site? -
Django, admin TabularInLine
django admin tabularInLine is there another way to do that in admin section? people still do it this way? what is wrong here? -
Django REST app returns 502 Bad Gateway on HTTP requests containing data once hosted on GAE
I created simple Django REST app and allowed all of the hosts for CORS in my settings.py using: ALLOWED_HOSTS = ['*'] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL=True I use Postman for faking requests from client-side and one of the request I am attempting is rest-auth/registration/ request. When do a registration for locally hosted Django REST app all works fine and it responses with 200 but once I deploy it to GAE the following thing happens: If I send the empty request (that is without username, password, password_confirmation) I receive normal response that the fields are mandatory, but once I add those strings to my request the response takes long time and the outcome is 502 Bad Gateway and in my GAE logs I can only see "POST /rest-auth/registration/ HTTP/1.1" 502 [CRITICAL] WORKER TIMEOUT (pid:17) What can be the issue here? What am I doing wrong? -
How to mock API request used inside function in a Django test?
I've got a little utility function built like this to grab data from another applications API: # app/utils.py import json import requests from django.conf import settings def get_future_assignments(user_id): """gets a users future assignments list from the API Arguments: user_id {int} -- user_id for a User """ headers = { "User-Agent": "Mozilla/5.0", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", } api_app = settings.ASSIGNMENTS_API_ROOT_URL # http://project.org/appname/ api_model = "futureassignments/" api_query = "?user_id=" + str(user_id) json_response = requests.get( api_app + api_model + api_query, headers=headers, verify=False ) return json.loads(json_response.content) It basically builds the API call and returns the response data - I'd like to test this. # tests/test_utils.py import mock from unittest.mock import patch, Mock from django.test import TestCase from app.utils import get_future_assignments class UtilsTest(TestCase): def setUp(self): self.futureassignments = [ { "id": 342, "user_id": 18888, "job": 361, "location": "1234", "building": "Building One", "confirmed_at": None, "returning": None, "signature": None, }, { "id": 342, "user_id": 18888, "job": 361, "location": "1235", "building": "Building Two", "confirmed_at": None, "returning": None, "signature": None, }, ] @patch("app.utils.get_future_assignments") def test_get_future_assignments_with_multi_assignments(self, mock_gfa): """ Test for getting future assignments for a user with mocked API """ mock_gfa.return_value = Mock() # set the json response to what we're expecting mock_gfa.return_value.json.return_value = self.futureassignments assignments = get_future_assignments(18888) self.assertEqual(len(assignments), 2) … -
Django not detecting date time field in model
I have this model class Moments(models.Model): content = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.PROTECT) publishing_date = models.DateTimeField(name='Date Published', default=timezone.now) def get_publishing_date(self): return self.publishing_date Another fact is that the publishing_date is present in django admin page Now on calling the get_publishing_date, its telling that AttributeError: 'Moments' object has no attribute 'publishing_date' -
urls.py icon doesn't have an image of python on it in PyCharm
urls.py without python emblem Hello. I'm working on Django project in PyCharm enviroment. I have a strange problem. In all of my Django apps urls.py files do not have an emblem of python on their icons. And, I do not have an IDLE support for code. If name of that files is changed, then the file becomes common python script. I cannot understand why this is happening. -
Access related table field value in django template
I am trying to access a Django related field value in a Django template: {% for item in order %} <tr> <td>{{ item.id }}</td> <td class="text-left">{{ item.created }}</td> <td class="text-left">{{ item.payments__charge_status }}</td> <td class="text-left">{{ item.shipping_method_name }}</td> <td class="text-right">£{{ item.total_gross_amount }}</td> </tr> {% endfor %} Actual queryset defined in views.py: orders = Order.objects.values().filter(created__range=(start_date, end_date)).filter(Q(payments__charge_status="fully-charged") | Q(payments__charge_status="not-charged")) Payment is in a different table and I can access using payments__charge_status in the view but not in the actual template. Any help is appreciated. -
Permission denied copping file using shutil.copy on python
i have a little problem during copy files between local folder on docker and a network folder who needs userPassword i tried this code but PermissionError: [Errno 13] Permission denied: '/interfaces/ifrs15/QA/Print_dashboard_1___10-15.PNG' import glob import shutil #ifrs15-img is local on docker for line in glob.glob('ifrs15-img/*.*'): print(line) shutil.copy(line, '/interfaces/ifrs15/QA') #/interfaces/ifrs15/QA its a networkfolder -
Django Admin Changelist_View - Adding extra context based on results list
I needed to add a totals row to Django Admin and used this SO answer for it. admin.py from django.contrib import admin from django.contrib.admin.views.main import ChangeList from .models import Employee_Cost class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_cost=Sum('cost')) self.total_cost = q['total_cost'] class Employee_CostAdmin(admin.ModelAdmin): def get_changelist(self,request): return MyChangeList class Meta: model = Employee_Cost fields = ['project','employee','hours','cost'] list_display = ['project','employee','hours'] Now I'm trying to add a graph following this tutorial: Adding charts to Django admin I'm stuck on the following part: Injecting chart data into admin template . admin.py class MyChangeList(ChangeList): def get_results(self, *args, **kwargs): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_cost=Sum('cost')) self.total_cost = q['total_cost'] class Employee_CostAdmin(admin.ModelAdmin): def get_changelist(self,request): return MyChangeList def changelist_view(self, request, extra_context=None): super(MyChangeList, self).get_results(*args, **kwargs) q = self.result_list.aggregate(total_planned_hours=Sum('revised_hours')) print(q) class Meta: model = Employee_Cost fields = ['project','employee','hours','cost'] list_display = ['project','employee','hours'] I want to base the extra_context on the changelist_view on the result list I got with get_changelist(). The return myChangeList seems to only return to the template and I tried but failed on passinq "q" to changelist_view. Currently, I got the following error message: super(type, obj): obj must be an instance or subtype of type Also, I tried placing changelist_view under the myChangeList class but nothing … -
How to Create SSO kind of Login from Drupal 7 to Django 3
How to Create SSO kind of Login from Drupal 7 to Django 3? Example: I have SaaS Application which is developed on Drupal 7 (Ex. www.abc.com)and I have created new Application Using Django (Ex. www.xyz.com), both Drupal and Django is using the same MySql DataBase. user will log on to www.abc.com and he will do some operation ex: click the button after clicking on the button, the user will redirect to www.xyz.com, and the user should not ask for any login again because the user already logged in to www.abc.com, Can someone help me how to achieve this? Big Thanks in advance -
DJANGO: filter queryset for foreign key
I need to filter the books associated with my serie model My models.py class Serie(models.Model): serie = models.CharField(max_length = 255) author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True) slug = AutoSlugField(populate_from = 'serie', always_update = True) class Book(models.Model): serie = models.ForeignKey(Serie, on_delete = models.CASCADE, null = True) serie_slug = AutoSlugField(populate_from = 'serie', always_update = True, null = True) book_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'book_title', always_update = True, null = True) resume = RichTextField() pub_date = models.DateTimeField(auto_now_add = True, null = True) My views.py class index(ListView): model = Serie template_name = 'serie_book_list.html' ordering = ['id'] def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) search = self.request.GET.get('buscar', None) if search: context = context.filter( Q(serie__icontains = search) | Q(author__name__icontains = search) | Q(Book.objects.filter(book_title__icontains = search)) ) return context I tried to use this code Q(Book.objects.filter(book_title__icontains = search)), but without success. Cannot filter against a non-conditional expression. -
Link between original field and translation field
I'm using modelsTranslation library, I want to add ar translation only as I'm using the default value as English. It doesn't make any sense to have name-en because name is in English too. -
Pass python list from context to JS function
I have a view that renders a dictionary of data for each country like below: def InvoicingDashboardView(request): # For reference - "c" is the context dictionary, and it's already initialized by this point for client in Client.objects.all(): fte = frame.fte(c['start_date'], c['end_date'], time = 'external', client = client.id) if fte > 0: c['countrys'][client] = { 'name': client.name, 'fte': fte, 'var_fte': fte - frame.fte(c['var_start_date'], c['var_end_date'], client = client.id), 'daily_ftes': [frame.fte(day, day) for day in c['label_days']], } return render(request, 'dashboards/invoicing.html', context = c) As you can see, for example, if i call {{countrys.client.fte}} i'll get the fte for that client. Everything good till now, but i'll need the daily_ftes for a JS function, like below: <div class="dash_countrys_ftes"> {% for country, items in countrys.items %} <div class="dash_country_block"> {% with name=items.name fte=items.fte variation=items.var_fte flag=country.flag.url %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} </div> <script> countryFteVariation("{{items.daily_ftes|escapejs}}") // HERE </script> {% endfor %} </div> The problem is that daily_ftes is a python list. What can i do here in order to javascript read it as list instead of a string? -
AttributeError running Django site on Mac 11.0.1
I'm getting an error running a django site locally that was working fine before I updated my Mac OS to 11.0.1. I'm thinking this update is the cause of the problem since nothing else was really changed between when it was working and now. 10:15:05 worker.1 | Traceback (most recent call last): 10:15:05 worker.1 | File "/usr/local/bin/celery", line 5, in <module> 10:15:05 worker.1 | from celery.__main__ import main 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/celery/__init__.py", line 133, in <module> 10:15:05 worker.1 | from celery import five # noqa 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/celery/five.py", line 20, in <module> 10:15:05 worker.1 | from kombu.five import monotonic 10:15:05 worker.1 | File "/usr/local/lib/python2.7/site-packages/kombu/five.py", line 56, in <module> 10:15:05 worker.1 | absolute_to_nanoseconds = CoreServices.AbsoluteToNanoseconds 10:15:05 worker.1 | File "/usr/local/Cellar/python@2/2.7.17_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 379, in __getattr__ 10:15:05 worker.1 | func = self.__getitem__(name) 10:15:05 worker.1 | File "/usr/local/Cellar/python@2/2.7.17_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 384, in __getitem__ 10:15:05 worker.1 | func = self._FuncPtr((name_or_ordinal, self)) 10:15:05 worker.1 | AttributeError: dlsym(RTLD_DEFAULT, AbsoluteToNanoseconds): symbol not found Here is my brew config HOMEBREW_VERSION: 2.6.0 ORIGIN: https://github.com/Homebrew/brew HEAD: 1d5e354cc2ff048bd7161d95b3fa7f91dc9dd081 Last commit: 2 days ago Core tap ORIGIN: https://github.com/Homebrew/homebrew-core Core tap HEAD: fdb83fcfb482e5ed1f1c3c442a85b99223fcabeb Core tap last commit: 27 hours ago Core tap branch: master HOMEBREW_PREFIX: /usr/local HOMEBREW_CASK_OPTS: [] HOMEBREW_DISPLAY: /private/tmp/com.apple.launchd.rZ1F30XomO/org.macosforge.xquartz:0 HOMEBREW_MAKE_JOBS: 8 … -
django use of quotes in url template tag
Why are quotes needed around users:users in the following: <a href="{% url 'users:users' %}">/users</a> is that a shortcut? in myusers.urls I have set app_name = users. Would the following work? <a href="{% url myusers.views.user %}">/users</a> -
AttributeError: 'Moments' object has no attribute 'date_published'
Well I have these models: class Expression(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date_published = models.DateTimeField(name='Date Published', default=timezone.now) class Meta: abstract = True class Moments(Expression): content = models.TextField(blank=True) And I have another function or rather view function where i try to access the 'date_published' field of a moments object like this: expression.date_published.strftime("%H:%M %p, %d %B, %Y") and I get this error: AttributeError: 'Moments' object has no attribute 'date_published' even though the date_published field is declared. Please help. -
When i click on page this error is raised Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<blog_id>[0-9]+)$']
blog.html {% block content %} <p>Blog's Title: {{ topic }}</p> <ul> {% for feed in blogs %} <li> <p>{{ feed.date_added|date:'M d,Y H:i' }}</p> <p>{{ feed.note|linebreaks }}</p> </li> {% empty %} <li>There are no Blogs Yet.</li> {% endfor %} </ul> #Here is that Delete blog link. <p>Do you want to delete this Blog?</p> <a href="{% url 'mains:delete' deletej.id %}"> Delete This Blog</a> {% endblock content %} views.py ( This is the view for delete Blog ) def delete(request, blog_id): deletej = get_object_or_404(Blog,id=blog_id) deletej.delete() return HttpResponseRedirect('home') urls.py path('delete/<int:blog_id>',views.delete,name='delete'), When i click on Blog page then this Error ( Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<blog_id>[0-9]+)$'] ) is raised. Please Help me in this. I will really appreciate your Help.