Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the field values as a dictionary
I have create a model Role as shown below. class Role(models.Model): role_name = models.CharField(max_length=255, unique=True, blank=False) I am trying to get the role_name of the record which has primary_key=2. So, far I have tried to do it like this - Role.objects.get(pk=2) But the problem with this is it returns the id of the instance i.e 2 which doesn't make sense as I already have it. So, I tried again using values and filter like this - Role.objects.values('role_name').filter(pk=2) Now, in this case it does return me the role_name but as an array of objects. As, the database table Role will always have one record I am expecting it to return a dictionary or just the value of it. -
how to check if Django is installed in anaconda?
C:\Users\JShaikh>py -m django --version 'py' is not recognized as an internal or external command, operable program or batch file. -
Angle Brackets in JSON
I am following the solution posted on: Sum database on location and time However, when I do a print(locations.values()) this is returned: ('Liberty City', <Location: 07:00 116 Liberty City 08:00 120 Liberty City ...>)]) What does the angle brackets (<>) means? And how can I access the values? -
Modified urlpatterns in django
I modified url in django, i can use tag {% url 'student-register' %} in template but when i call {% url 'student-reg' %} it return error reverse-not found, anyone can describe what happened ? this is my code : from django.urls import path, include from .views.home import * from .views.teacher import * urlpatterns = [ path('', ViewHomePage.as_view(), name='home'), path('logout', LogoutAccount.as_view(), name='logout'), path('teacher/', include(([ path('', ViewTeacherHome.as_view(), name='teacher'), path('student-register', ViewStudentRegister.as_view(), name='student-register'), ], 'exam'), namespace='teacher')), path('student/', include(([ path('', ViewTeacherHome.as_view(), name='student'), path('student-reg', ViewStudentRegister.as_view(), name='student-reg'), ], 'exam'), namespace='student')) ] -
Href not working when im logged in Django
I did the authentication system and when i'm logged in the Hyperlinks are not working anymore and when i put the cursor on it , it shows the correct path that it will be rendered to . When i change the URL from browser's URL bar it goes to the page i want... -
Django ClearableFileInput not rendering Properly
I am using cripsy forms Model class CadreAck(models.Model): cadre = models.ForeignKey('common.Cadre',on_delete=models.CASCADE,null=True,blank=True) dtg = models.DateTimeField(verbose_name='Datetime',null=True,blank=True) comments = models.TextField(null=True,blank=True) attachment = models.FileField(upload_to=cadre_ack_path,blank=True) Form class CadreAckForm(forms.ModelForm): class Meta: model = common_models.CadreAck exclude = ['dtg'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) self.helper.form_method = 'POST' Template {% extends "cadreportal/base.html" %} {% load crispy_forms_tags %} {% load render_table from django_tables2 %} {% load querystring from django_tables2 %} {% load bootstrap4 %} {% block content %} <h1> {{ header }} </h1><hr> {% if sub_header %} <h3>{{ sub_header }}</h3><hr> {% endif %} {% if sub_sub_header %} <h3>{{ sub_sub_header }}</h3><hr> {% endif %} {% if form%} <h3> {{ form_header }} </h3> {% crispy form %} {% endif %} {% endblock content %} The Choose file box is covering up the attachment upload and clear checkbox (See Snip) Output -
Django Celery worker received task but does not execute the task
I am trying to use Celery for background working of a website. Celery worker receives tasks from celery beat or python manage.py shell. But it does not proceed after Received task process. My code is as follows. task.py from __future__ import absolute_import, unicode_literals from celery import Celery, shared_task @shared_task def check(): print("I am checking execution") celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoSample.settings') app = Celery('DjangoSample') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Celery worker log is like this. (venv) C:\Users\doo56\PycharmProjects\untitled1\DjangoSample>celery -A DjangoSample worker -l info -------------- celery@LAPTOP-ONN7RQ0R v4.4.2 (cliffs) --- ***** ----- -- ******* ---- Windows-10-10.0.17134-SP0 2020-04-14 22:11:33 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: DjangoSample:0x1a6600d6b48 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . catalog.tasks.check [2020-04-14 22:11:34,101: INFO/MainProcess] Connected to redis://localhost:6379/0 [2020-04-14 22:11:34,134: INFO/MainProcess] mingle: searching for neighbors [2020-04-14 22:11:35,240: INFO/MainProcess] mingle: all alone [2020-04-14 22:11:35,322: WARNING/MainProcess] c:\users\doo56\pycharmprojects\untitled1\venv\lib\site-packages\celery\fixups\django.py:203: UserWarning: Us ing settings.DEBUG leads to a memory leak, never use this setting in … -
How effectively extracts value from function (python) and pass to context (Django)
I have function in seperate django file function.py. My function consists of lenthy calculations whiuch i then pass to views. there are functions inside the main function a(). This is how to pass value ( this is shortest version to pass you idea os what i am trying to say). def a(): x=3 y=4 z=6 def b(): x1=x+1 return x1 def c(): y1=y+1 return y1 def d(): z1=z+1 return b(), c(), d() def home(request): abc=a() context={'value1':abc[0],'value2':abc[1],'value3':abc[2],} print(value1) This how i pass value. Is this efefctive way or there are more efficient ways to pass values form the function as as so far i manually have to pass to the context in views through indexing as i did. What is your recomendation to ease my work? -
I want to use inline for loop in the following way
anyone please correct me in writing for loop in Django template , see below code to understand what im trying to do {% for item in items and for quantity in quantities %} -
How to remove "No Password set" on my Django template for editing a profile
On my Django template when a user logs in and edits there profile I have this weird-looking message that reads "No password set. Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form." How can I prevent this from displaying on my template? below is my code forms.py class EditProfileForm(UserChangeForm): member_id = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Member Id'})) first_name = forms.CharField(label='Firstname', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Firstname'})) last_name = forms.CharField(label='Lastname', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Lastname'})) email = forms.CharField(label='Email*', widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'})) phone1 = forms.CharField(label='Phone Number 1*', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number 1'})) phone2 = forms.CharField(label='Phone Number 2', required=False, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number 2'})) class Meta(): model = User fields = ('member_id', 'first_name', 'last_name', 'email', 'phone1', 'phone2') -
Use custom model method in custom django queryset
A custom Model queryset takes one of the model's field to make some calculations, but now I need to get that field through a custom model method where I make some adjustment's according to the request.user's timezone. The function takes user as a parameter. Here are some code snippets: queryset: break_time_start = F("machine_break_time__break_time_start") model function: def break_time_start_user(self, user) -> datetime.time: utc_time = self.break_time_start_utc.replace(tzinfo=self.timezone) date = datetime.datetime.combine(datetime.date.today(), utc_time) return localtime(date, user.timezone).time() How can I use this custom method in my custom queryset? -
Convert a python script which based on Paramiko into Django
I`ve put a place a python script that take as input: IP Address txt file (First Name Last Name MAC_Address) Boolean yes or no (would like to assign the main number to a receptionist or just to a static phone) Is it possible if someone can guide me how i can have this integrated into Django (ive already started a Django project but im not finding a way to model my python script into django ...do i just copy and paste into views.py or models.py ....) Thanks ! -
Is there a way to fix this issue? [closed]
I'm developing a website for an online store with Django and I want to show users a review of their cart while they are filling their billing addresses and stuff. I have my cart on another directory, so how do I bring that cart in my html form for checkout? I tried to do the same thing that I did with my cart.html but it is not working. Can anyone please help me out? My checkout.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yno" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- Custom styles for this template --> <link href="./css/form-validation.css" rel="stylesheet" /> </head> <div class="container"> <div class="row"> <body class="bg-white"> <div class="container"> <div class="py-5 text-center"> <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="" height="" /> <h2>Checkout</h2> <p>Enter your billing address</p> </div> <div class="row"> <div class="col-md-4 order-md-2"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your cart</span> <span class="badge badge-secondary badge-pill">{{ request.session.items_total }}</span> </h4> <ul class="list-group mb-3"> {% for item in cart.cartitem_set.all %} <li class="list-group-item d-flex justify-content-between lh-condensed" > <div> <h6 class="my-0">{{ item.product.name }}</h6> <small class="text-muted">Brief description</small> </div> <span … -
Django -Page not found (404) Request Method: GET Method
I am very new to Django ,I am trying to run a URL ,however I get this error of page not found.I went through almost 90% of the posts here but nothing worked for me. Here are three .py files views.py..... from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello world....') **products\urls.py**** from django.urls import path from . import views #.means current folder ,we are importing a module urlpatterns=[ path(' ', views.index), ] pyshop\urls.py....... from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('products/',include('products.urls')) ] Error I get..... Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/ Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ The current path, products/, didn't match any of these. -
Django JsonResponse lose precision
I have a big int such as 6222600820001059483 in python int type. When I send to browser use JsonResponse I found that the value was changed to 6222600820001060000. I think this caused by the precison lose when JsonResponse send it to browser. So how to prevent this precision lose? I'm using django 2.2.12. -
Why i am getting error while running Django manage.py migrate command
When running python manage.py migrate getting error (MyDjangoEnv) srijan@srijan:~/Desktop/django/first_project$ python manage.py syncdb --migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/core/management/init.py", line 337, in execute django.setup() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/srijan/anaconda3/envs/MyDjangoEnv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 985, in _gcd_import File "", line 968, in _find_and_load File "", line 957, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 693, in exec_module File "", line 799, in get_code File "", line 759, in source_to_code File "", line 222, in _call_with_frames_removed File "/home/srijan/Desktop/django/first_project/first_app/models.py", line 24 return (str)self.date ^ SyntaxError: invalid syntax -
Can't forward or skip video on Django website
I am trying to create a website for myself. It is kind of a Youtube on a local network. I am using video.js (have also tried Plyr.io) to play the video, but i can not fast forward the video. Or go back in the video. I can only play it from begining to the end. If i try to skip forward it only resets. What am I doing wrong? Thanks in advance! -
Django Redirect to a view with ajax call
I have a Django application. Inside it, I use some Ajax calls to a function when I would like to manipulate backend, without affecting the front end. In one function I would like to redirect the user to a home page. I have: def some_function(request, param_one): other_function(request.user, param_one) return redirect('mypage:home') and in JS I have: $.ajax({ type : "GET", url : '/url to my function/', error: function(){ console.log('Error complete'); } }); I see that I get the right page in chrome developer tools But nothing happened... So js get the HTML page but didn't render it. -
Django REST framework: how to combine the same type of model
How to combine many models in one query set so that it would be possible to use HyperlinkedModelSerializer using pagination? I need to connect many models with the same fields. That's what I did, but it doesn’t suit me.: **"models.py"** class Merketing(models.Model): question = models.CharField(max_length=500, unique=True) answer = models.CharField(max_length=500) class Management(models.Model): question = models.CharField(max_length=500, unique=True) answer = models.CharField(max_length=500) **"serializers.py"** class MerketingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Merketing fields = ['id','question', 'answer'] class ManagementSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Management fields = ['id','question', 'answer'] class FiltersSerializers(serializers.Serializer): model_1 = MerketingSerializer(read_only=True,many=True) model_2 = ManagementSerializer(read_only=True,many=True) **"viesw.py"** class MerketingViewSet(viewsets.ModelViewSet): queryset = Merketing.objects.all().order_by('question') serializer_class = MerketingSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['question'] class ManagementViewSet(viewsets.ModelViewSet): queryset = Management.objects.all().order_by('question') serializer_class = ManagementSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['question'] class FiltersView(APIView): def get(self, request, *args, **kwargs): filters = {} filters['model_1'] = Merketing.objects.all().order_by('question') filters['model_2'] = Management.objects.all().order_by('question') serializer = FiltersSerializers(filters) return Response (serializer.data, status=HTTP_200_OK) -
django rest framework and redis
I'm working on a project where there are like 30 to 40 gps trackers, I want to give the client the ability to select any tracker and then track its location. I was able to get the trackers to communicate using a django rest framework, being a real time application I'm using channels. The database is divided such that the one table is for the trackers, and another table for tracking their current location. Using the seconds table I'm able to server the requested trackers location to the user. I wanted to know if there is a way for me to implement django rest framework with redis, such that the post request from the tracker is directly cached, instead of inserting or updating in the database. The historical location of the trackers is not important to me, just their current location. -
How to return Django project's error messages when I use nginx in production mode
I have developed the Django project and deployed it to the Amazon's free tier EC2 services. Everything is fine except errors message that are not returning back. I am using the project in production mode. Here is my nginx.conf upstream app { server web:8000; } server { listen 80; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = GET) { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } if ($request_method = POST) { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PATCH, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range, Authorization'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } ... } location /static/ { alias /home/user/web/staticfiles/; } location /media/ { alias /home/user/web/media/; } } Explanation for above image [Console Log]: Successful request and response - it was … -
Django multiple formsets and form with CreateView - form_valid()
I am Django beginner and trying to modify https://dev.to/zxenia/django-inline-formsets-with-class-based-views-and-crispy-forms-14o6 to support multiple formsets of the same type using prefix. The form is displayed fine but clicking "Save" a POST is initiated but nothing happens. The POST is larger than the GET (which reflects my added data) but nothing is saved/created. class BudgetCreate(CreateView): model = Budget template_name = 'budget/budget_create.html' form_class = BudgetForm success_url = '/location' def get_context_data(self, **kwargs): data = super(BudgetCreate, self).get_context_data(**kwargs) if self.request.POST: data['cat1'] = LineItemFormSet(self.request.POST, prefix='cat1') data['cat2'] = LineItemFormSet(self.request.POST, prefix='cat2') data['cat3'] = LineItemFormSet(self.request.POST, prefix='cat3') data['cat4'] = LineItemFormSet(self.request.POST, prefix='cat4') data['cat5'] = LineItemFormSet(self.request.POST, prefix='cat5') data['cat6'] = LineItemFormSet(self.request.POST, prefix='cat6') data['cat7'] = LineItemFormSet(self.request.POST, prefix='cat7') else: data['cat1'] = LineItemFormSet(prefix='cat1') data['cat2'] = LineItemFormSet(prefix='cat2') data['cat3'] = LineItemFormSet(prefix='cat3') data['cat4'] = LineItemFormSet(prefix='cat4') data['cat5'] = LineItemFormSet(prefix='cat5') data['cat6'] = LineItemFormSet(prefix='cat6') data['cat7'] = LineItemFormSet(prefix='cat7') return data def form_valid(self, form): context = self.get_context_data() cat1 = context['cat1'] cat2 = context['cat2'] cat3 = context['cat3'] cat4 = context['cat4'] cat5 = context['cat5'] cat6 = context['cat6'] cat7 = context['cat6'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if cat1.is_valid() and cat2.is_valid() and cat3.is_valid() and cat4.is_valid() and \ cat5.is_valid() and cat6.is_valid() and cat7.is_valid(): cat1.instance = self.object cat1.save() cat2.instance = self.object cat2.save() cat3.instance = self.object cat3.save() cat4.instance = self.object cat4.save() cat5.instance = self.object cat5.save() cat6.instance = self.object cat6.save() cat7.instance … -
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' in django save function
I have these model: class Event(models.Model): """ Event Model """ day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True) start_time = models.TimeField( u'Starting time', help_text=u'Starting time', null=True) end_time = models.TimeField( u'Final time', help_text=u'Final time', null=True) end_day = models.DateField( u'End Day of the event', help_text=u'End Day of the event', null=True) total_minutes = models.DecimalField(default=0.00, max_digits=19, decimal_places=2) I want to calculate diffrence between the minutes of two TimeFields So I have done the following: from datetime import date, datetime, timedelta def save(self, *args, **kwargs): start = datetime.combine(self.day, self.start_time) end = datetime.combine(self.end_day, self.end_time) diffrence = end - start self.total_minutes = diffrence.total_seconds() / 60 super(Event, self).save(*args, **kwargs) but getting the error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time. Can anyone tell me why I am getting the error? -
How to use update_fields in Django signals
I'm trying to use an the 'update_fields' argument passed to signals in Django. I've got something very simple for now, namely: @receiver(pre_save, sender=models.UserAdmin) @receiver(pre_save, sender=models.UserGroupAdmin) def update_timestamps(sender, instance, update_fields, **kwargs): print(f'Update fields: {update_fields}') update_fields shows as None no matter what is being updated, which indicates I've not understood something. What am I missing? -
Django path not working and it direct me to wrong websites
I'm build my first website and i got stuck because paths to siedes are wrong. I will show you at a example: I have a website: '' When i click "Search" on the nav bar i want to go "/search" (search is added as a block in base.html) But when im in "/search"and i click "register" on nav bar i want to go "/register" (register is a block either) The problem is that when i click "register" when i am on "/search" its direct me to "/search/register" and such a site doesnt exist. Going to home ('') from every site is working. My urls: from django.contrib import admin from django.urls import path, include from users import views as users_views from polls import views as polls_views urlpatterns = [ #path('', include('polls.urls')), path('', polls_views.home, name='home'), path('ListSearch/', polls_views.ListSearch, name='ListSearch'), path('register/', users_views.register, name='register'), path('admin/', admin.site.urls), ] My nav bar: <nav> <div class="nav-wrapper" style="background-color:#174c9c;"> <div class="container"> <a href="/" class="brand-logo">ShoppingList</a> <ul class="right hide-on-med-and-down"> <li><a href="ListSearch">Search for list </a></li> <li><a href="/">Log in</a></li> <li><a href="register">Register</a></li> </ul> </div> </div> </nav> With "setup" is showed you above it is working as i described it, if i change "register/" to "register" adn do the same with "ListSearch" it gives me 404: …