Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom field in Django ArrayField throws an error
PROBLEM I have CustomField nested in ArrayField. CustomField itself works well, also migrations throw no error. When I try to save MyModel(code=[StandardCode(...), ...]), why I get the following error: TypeError: asdict() should be called on dataclass instances I know that for some reason django tries to call my DataClassField get_prep_value() with value=[StandardCode(...), ...] Why that happens? How could this behaviour got fixed? FIELD DEFINITION class DataClassField(models.CharField): description = "Map python dataclasses to model." def __init__(self, dataClass, *args, **kwargs): self.dataClass = dataClass kwargs['max_length'] = 1024 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['dataClass'] = self.dataClass return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def to_python(self, value): if isinstance(value, self.dataClass): return value if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def get_prep_value(self, value): try: if value is None: return value return json.dumps(asdict(value)) except Exception as e: print(value) raise e DATACLASS DEFINITION: @dataclass class StandardCode: code: str codeSystem: str displayName: str MODEL DEFINITION from django.contrib.postgres.fields import ArrayField class MyModel code = ArrayField(DataClassField(dataClass=StandardCode, null=True), size=2, default=list) -
How to send csrf token in xmlHttpRequest?
Using Ajax or xmlHttpRequest I want to download excel file from django backend. Backend creates file in memory and returns it to user. According to this answer I should use for this xmlHttpRequest, but there is no info how to set csrf middleware token in post request. I tried: To set request.setRequestHeader like this: request.setRequestHeader('x-csrf-token, window.CSRF_TOKEN) - token is missing and in data: request.send({'csrfmiddlewaretoken': window.CSRF_TOKEN, 'req': 'ExportAllMessages'}); I can't find any working solution with Ajax. -
How to have different expiry times for Web and Mobile Apps in Django simple jwt?
I am currently using Django Rest Framework to serve a React JS application, but recently, we are adding support for a React Native application as well. Now, as I use Django Simple jwt, here's the code for the expiry of the refresh and access tokens: settings.py ACCESS_TOKEN_LIFETIME = datetime.timedelta(hours=2) REFRESH_TOKEN_LIFETIME = datetime.timedelta(days=3) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': ACCESS_TOKEN_LIFETIME, 'REFRESH_TOKEN_LIFETIME': REFRESH_TOKEN_LIFETIME, ... } While this works really well on web, I do not want the phone app users to have to get logged out automatically every 3 days. Is there a way to alter the refresh token lifetime based on the device that is asking for the tokens? If yes, how? -
Django Signals: How To Create Objects On Object Creation
I am trying to create an object on another model's object creation but i dont know what to put in the function save_collection_list_item to make this work. I am getting the error: 'Collection' object has no attribute 'collection_list_item' so what should i replace it with? models: class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: #collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author) Collection_List_Item.objects.create(collection=instance, user=instance.author) @receiver(post_save, sender=Collection) def save_collection_list_item(sender, instance, **kwargs): instance.collection_list_item.save() # What should i change this to? -
Django how to get model values inside another model?
I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username. i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'. Also if I could it during the registration form filling that would be great. models.py class User_data(models.Model): username = models.CharField(max_length=256, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) four_digit_pass = models.CharField(max_length=256, null=True, blank=True) private_key = models.CharField(max_length=256, null=True, blank=True) profile_pic = models.ImageField(upload_to='static/profilepic', null=True) def getUsername(self): return self.username def __str__(self): return str(self.username) class AuthImages(models.Model): owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE) uname=owner. def save_auth_image(self): uname = self.username self.auth_image_file = models.ImageField( upload_to='static/auth_image/%s' % uname, null=True) forms.py class RegistrationForm(forms.ModelForm): four_digit_pass = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User_data fields = ['username', 'email', 'four_digit_pass', 'profile_pic', 'private_key'] register.html {% extends "storage_app/base.html" %} {% block body_block %} <div class="jumbotron"> <h1>Register Page</h1> </div> <div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <p>Private Key should not be changed or shared with anyone</p> <button type="submit">Upload</button> </form> </div> {% endblock body_block %} here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible This is my first question also I am new to Django so … -
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field. -
search data using ajax and django and redirect to related pages
I am building a website and I want to implement searching. I want the user to enter some text and want to show suggestions using ajax. when the user click on specific product or category I want to redirect the user to related page. Here is what I have done so far: $(function () { $("#search").autocomplete({ source: "{% url 'ajax-search' %}", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 5, }); }); <div class="search"> <label for="search"></label> <input type="text" oninput="" style="height: 36px" class="searchTerm" placeholder="What are you looking for?" name="searchtext" id="search"> <button type="submit" class="searchButton"> <i class="fa fa-search"></i> </button> </div> path('ajax/search', views.autocompleteModel, name='ajax-search'), def autocompleteModel(request): if request.is_ajax(): q = request.GET.get('term', '') lookups = Q(name__icontains=q) | Q(category__name__icontains=q) products = Product.objects.filter(lookups).distinct() results = [] for product in products: place_json = {} place_json = product.name product_url = 'prodcuts/product/' + str(product.id) results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Django REST Framework internal value
I have a simple serializer with a date field (not ModelSerializer). class MySerializer(Serializer): some_date = DateField() I'm trying to access the date object after deserialization. slz = MySerializer(data={"some_date": "2020-05-03"}) # I surely have a better error handling in my actual code assert slz.is_valid() some_extracted_date = slz.data["some_date"] I would like my variable some_extracted_date to be a datetime.date instance. But the value in the MySerializer.data dict is a string. Is there a way to get this datetime.date instance ? -
How to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm
I'm trying to dynamically set the limit_value of the build-in MinValueValidator inside a Django 3.1 ModelForm. The below code works for a fixed limit_value of 10 (see line 21 in views.py). models.py from django.contrib.auth.models import AbstractUser from django.db import models class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") bid = models.DecimalField(decimal_places=2, max_digits=9) views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django import forms from .models import User, Listing, Category, Bid from django.db.models import Max from decimal import Decimal, DecimalException from django.core.validators import MaxValueValidator, MinValueValidator from django.core.exceptions import ValidationError class NewBidForm(forms.ModelForm): class Meta: model = Bid fields = '__all__' widgets = { 'user': forms.HiddenInput(), 'listing': forms.HiddenInput(), } def __init__(self, *args, **kwargs): super(NewBidForm, self).__init__(*args, **kwargs) self.fields['user'].show_hidden_initial=True self.fields['listing'].show_hidden_initial=True self.fields['bid'].validators=[MinValueValidator(10)] def clean(self): if 'user' in self.changed_data or 'listing' in self.changed_data: raise forms.ValidationError('Non editable field have changed!') return self.cleaned_data def index(request): listings = Listing.objects.all() return render(request, "auctions/index.html", { "listings" : listings, }) def listing(request, listing_id): if request.method == 'POST': data = request.POST form = NewBidForm(data) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: listing = Listing.objects.get(pk=listing_id) bids = Bid.objects.filter(listing=listing) if bids: highest_bid = bids.aggregate(Max('bid'))['bid__max'] else: highest_bid … -
How to access form field in html class
I am building a BlogApp and I am trying to customize the FileUpload button. What i am trying to do I am trying to customize the File Upload button using CSS button , I am unable to access it with my model instance ( {{ form.file}} ) CSS .btn-upload { position: relative; overflow: hidden; display: inline-block; } .btn-upload input[type=file] { position: absolute; opacity: 0; z-index: 0; max-width: 100%; height: 100%; display: block; } .btn-upload .btn{ padding: 8px 20px; background: #337ab7; border: 1px solid #2e6da4; color: #fff; border: 0; } .btn-upload:hover .btn{ padding: 8px 20px; background: #2e6da4; color: #fff; border: 0; } #This is my image field by {{ form.image }} in template HTML {{ form.file}} What have i tried I tried using this <input type="file" name="file" class="btn-upload"> BUT it didn't worked for me. Any help would be really Appreciated. Thank You in Advance. I tried many time by adding classes and ids but none of them worked for me. I don't how can i -
Regarding Django runserver issue [closed]
My Django runserver does not start while start to create project and does not show any error messages also while I am using pyrated windows 10.Please help me resolve my problem. -
Dynamic Command for Kubernetes Jobs
So hopefully this makes sense to the non-Djangoers of the k8s community. I will try my best to explain the setup / reasoning. With Django, we have LOTS of what are called management commands that we can run within the scope and environment of our Django app that can really help development and deployment. I'm sure most other frameworks have similar, if not identical, concepts. An example would be the "python manage.py migrate" command that ensures our codebase (migration scripts) are applied to and reflect in the associated database. There are approx. 30 - 50 core commands we can run, we can also create our own, as well as apply those from any installed third party applications. Anyways. The most important takeaway is that there are a lot of commands we can and do run. Now, I have the following k8s Job to run the "migrate" command: apiVersion: batch/v1 kind: Job metadata: name: asencis-web-migrate-job spec: template: spec: containers: - name: asencis-web-migrate-job image: asencis/asencis-base:latest imagePullPolicy: Always command: ['python', 'manage.py', 'migrate'] envFrom: - configMapRef: name: asencis-config - secretRef: name: asencis-secret restartPolicy: Never backoffLimit: 5 This job essentially runs the python manage.py migrate command within the application scope/environment. It works like a charm: … -
Best way to re/use redis connections for prometheus django exporter
I am getting an error redis.exceptions.ConnectionError: Error 24 connecting to redis-service:6379. Too many open files. ... OSError: [Errno 24] Too many open files I know this can be fixed by increasing the ulimit but I don't think that's the issue here and also this is a service running on a container. The application starts up correctly works for 48 hours correctly and then I get the above error. Which implies that the connections are growing over time exponentially. What my application is basically doing background_task (ran using celery) -> collects data from postgres and sets it on redis prometheus reaches the app at '/metrics' which is a django view -> collects data from redis and serves the data using django prometheus exporter The code looks something like this views.py from prometheus_client.core import GaugeMetricFamily, REGISTRY from my_awesome_app.taskbroker.celery import app class SomeMetricCollector: def get_sample_metrics(self): with app.connection_or_acquire() as conn: client = conn.channel().client result = client.get('some_metric_key') return {'some_metric_key': result} def collect(self): sample_metrics = self.get_sample_metrics() for key, value in sample_metrics.items(): yield GaugeMetricFamily(key, 'This is a custom metric', value=value) REGISTRY.register(SomeMetricCollector()) tasks.py # This is my boilerplate taskbroker app from my_awesome_app.taskbroker.celery import app # How it's collecting data from postgres is trivial to this issue. from my_awesome_app.utility_app.utility … -
my code keeps showing me this error 404: the current path,get, didn't match any of these
this is my code I don't know where the error is coming from. It is telling me that Using the URLconf defined in ehiz.urls, Django tried these URL patterns, in this order: admin/ [name='home'] add/ [name='add'] The current path, get, didn't match any of these. Views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'base.html',{'name':'Gael'}) def add(request): val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) res = val1 + val2 return render(request, 'result.html',{'result':res}) base.html {% extends 'main.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="get"> <input type="text" name="num1" placeholder="Enter first number"><br> <input type="text" name="num2" placeholder="enter second number"><br> <input type="submit"> </form> {% endblock %} result.html {% extends 'main.html' %} {% block content %} the result is : {{result}} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('add/',views.add,name='add') ] -
How can I solve the error "page not found(404)" in my 1st django project?
I'm very new to django and I stuck in my first project the error says Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about using the URLconf defined in emuhay.urls, Django tried these URL patterns, in this order: admin/ The current path, about, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'm expecting "Contat page" but page not found displayed every time my code is below #Url code from django.contrib import admin from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('Home Page') def contact(request): return HttpResponse('Contact Page') urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('about/',contact), ] #setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'yra+iwr3x_)@ssxj)e%h^7=m(te0mh!_4xx61g7j2j4y)o9z&$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hihi', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = … -
django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F() + F()): is an aggregate
I have a code: k = company.departments.all().annotate( net_pay_amount_sum=Sum('employees__payments__net_pay_amount'), earnings_sum=Sum('employees__payments__earnings__amount'), taxes_sum=Sum('employees__payments__taxes__amount'), ).annotate( total_sum=Coalesce(ExpressionWrapper( Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), output_field=fields.DecimalField()), 0) ).values_list('name', 'total_sum') and when I run it I got exeption: django.core.exceptions.FieldError: Cannot compute Sum('<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>'): '<CombinedExpression: F(net_pay_amount_sum) + F(earnings_sum) + F(taxes_sum)>' is an aggregate Can someone tell me how can I sum this withot exeptions Sum(F('net_pay_amount_sum') + F('earnings_sum') + F('taxes_sum')), -
Django textarea form
i need to set rows and cols for a textarea in my HTML page from Django but it doesnt work. I already put rows and cols in mine form Views.py class EditForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'name':'title'})) body = forms.CharField(widget=forms.Textarea(attrs={'name':'body', 'rows':3, 'cols':5})) def new(request): return render(request,"encyclopedia/handlepage.html", { "title": "CREATE NEW PAGE", "edit": False, "editpage": EditForm() }) handlepage.html {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>{{title}}</h1> <a href="https://guides.github.com/features/mastering-markdown/">Markdown guides</a> {% if edit %} //Useless right now {% else %} <form method="POST" action="{% url 'save' %}"> <input type="submit" value="SAVE ENTRY"><br> {% csrf_token %} {{ editpage }} </form> {% endif %} {% endblock %} Then my page should have a small text area but it have the same size independent by its row and cols like this -
Object of type 'RecursionError' is not JSON serializable
Comparing length of two files and if not equal insert def compare(length, initial_val) i = initial_val if i == length: return 1 else: tags_extracted_from_template = re.findall(r'<[^>]+>', str(file1_list[i])) tags_extracted_from_user_form = re.findall(r'<[^>]+>', str(file2_list[i])) if "".join(tags_extracted_from_template) != "".join(tags_extracted_from_user_form): file2_list.insert(i, "".join(tags_extracted_from_template)) return compare(len(file2_list),0) print(file2_list) return compare(len(file2_list), i + 1) if len(file1_list) != len(file2_list): compare(len(file2_list), 0) print("Final Length", len(file2_list)) -
lauching pipenv shell creates a subshell in the wrong directory
MacBook-Pro-van-Ferry:voorbeeld ferryholzhaus$ pipenv shell Launching subshell in virtual environment... . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate Restored session: vr 19 mrt 2021 11:52:49 CET ferryholzhaus@MacBook-Pro-van-Ferry ~ % . /Users/ferryholzhaus/.local/share/virtualenvs/ferryholzhaus-AnfvKXxr/bin/activate (ferryholzhaus) ferryholzhaus@MacBook-Pro-van-Ferry ~ % -
django-taggit only allow current tags for users
I have not been able to find any related questions on this. I have a create-post page where i want users to only be able to pick between current tags(could be done using scroll-down button) and not be able to create their own tags when creating a post. my approach so far has been trying to set the tag field with values of the link im pressing in the scroll down button. Image 4 shows the tag options where i want to display the tag name on the tag model field when that specific tag name is pressed on the scroll down button. images of my code: [models.py][1] [form.py][2] [views.py][3] [my create post page][4] [1]: https://i.stack.imgur.com/YafQ3.png [2]: https://i.stack.imgur.com/OnQF9.png [3]: https://i.stack.imgur.com/K3M6Z.png [4]: https://i.stack.imgur.com/yA2I4.png -
Django project deploy on Heroku failed
After I successfully deployed my Django project to Heroku, the page didn't show anything but the application error. It suggest me use the command to find the problem: heroku logs --tail and it shows lines of error, and here's part of them: 2021-03-19T10:06:26.966003+00:00 app[web.1]: Traceback (most recent call last): 2021-03-19T10:06:26.966003+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-03-19T10:06:26.966004+00:00 app[web.1]: worker.init_process() 2021-03-19T10:06:26.966004+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.load_wsgi() 2021-03-19T10:06:26.966005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-03-19T10:06:26.966005+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-03-19T10:06:26.966006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-03-19T10:06:26.966006+00:00 app[web.1]: self.callable = self.load() 2021-03-19T10:06:26.966007+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2021-03-19T10:06:26.966007+00:00 app[web.1]: return self.load_wsgiapp() 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2021-03-19T10:06:26.966008+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-03-19T10:06:26.966008+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2021-03-19T10:06:26.966009+00:00 app[web.1]: mod = importlib.import_module(module) 2021-03-19T10:06:26.966009+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-03-19T10:06:26.966009+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-03-19T10:06:26.966010+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-03-19T10:06:26.966011+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in exec_module 2021-03-19T10:06:26.966012+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, … -
exclude content field from crispy forms
forms.py from django import forms from tinymce import TinyMCE from .models import Article class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = Article fields = ('title', 'major', 'semester', 'book', 'unit', 'content') article_form.html {% extends "base.html" %} {% load static %} {% load tailwind_filters %} {% block title %}Create{% endblock title %} {% block content %} {{ form.media }} <div class="row form-error"> <div class="column" id="content"> <form method="post" action='' enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input class="button" type="submit" value="Save"> </form> </div> </div> {% endblock %} I using TinyMCE to implement a rich text editor. when I reload the page it gives me this: AttributeError at /article/new/ 'CSSContainer' object has no attribute 'tinymce' I just want to use crispy forms on all fields and exclude the content field from crispy forms. -
Can't refer to Django templates
Below is my directories created by using Django isap/users needs to get templates from isap/isap/templates/users/login.html isap/ L isap L templates L users L login.html L .... L .... L ..... L ... L users L views.py L urls.py So, I added TEMPLATE = [{..., "DIRS": [os.path.join(BASEDIR2, "templates/")],APP_DIRS=True,....}]in settings.py and BASEDIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '\\isap' Also, I already added the apps PROJECT_APPS = [isap.apps.IsapConfig, users.apps.UsersConfig, ...] But, the 404(Page not found) error is generated. below is my users/views.py import os import requests from django.utils import translation from django.http import HttpResponse from django.contrib.auth.views import PasswordChangeView from django.views.generic import FormView, DetailView, UpdateView from django.urls import reverse_lazy from django.shortcuts import redirect, reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.core.files.base import ContentFile from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from . import forms, models, mixins class LoginView(mixins.LoggedOutOnlyView, FormView): template_name = "users/login.html" form_class = forms.LoginForm def form_valid(self, form): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(self.request, username=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) def get_success_url(self): next_arg = self.request.GET.get("next") if next_arg is not None: return next_arg else: return reverse("core:home") How can I link the templates to isap/users/views.py? -
adding python dicts to django JsonResponse
the time data in my MySQL database is in ISO time and i'd like to create two bar charts that show taxi rides by day of the week/ by hour. after querying the iso time from the database, i have the week of day count and hourly count saved in two dictionaries, and was wondering how i can render these dictionaries to JsonResponse (if JsonReponse takes in dicts) to render a chart.js bar chart. i have the following code written in my views.py and have no idea what it prints (or whether count is iterating through the dictionary correctly), so if there are any pointers as to how i can visualise this dictionary before charting that'd also be great. def charts(request): dow_queryset = Member.objects.order_by('member_created_time').values( 'member_created_time') hkt = timezone('Asia/Shanghai') dt_obj = hkt.localize(datetime.datetime.fromtimestamp(dow_queryset)) # naive datetime obj w/o tz info """ data - rides by the hour """ hour_count = {} for obj in dt_obj: if obj.hour == 0: hour_count['midnight'] += 1 elif obj.hour < 6: hour_count['early_morning'] += 1 elif obj.hour < 12: hour_count['morning'] += 1 elif obj.hour < 19: hour_count['afternoon'] += 1 else: hour_count['night'] += 1 """ data - rides by weekday (bar chart) """ weekday_count = {} for obj in … -
How can I relate two models in Django, where for each insertion in model1, model2 will automatically insert some fields from model1?
I have the model User which is inserted with data each time a user connects. And I have the model Client which is related to the User model. My goal is simple I want Client to be extended from User where for each row created in User Client should also create that row. I did the following code but still not the results that I want. class Client(User): # on_delete is for what operation we execute for the Client if the User got deleted # default option gives a default date before the user choose the date birthDate = models.DateField(null=True, default=django.utils.timezone.now) phone_number = models.CharField(null=True, max_length=30) id_card_number = models.IntegerField(null=True) address = models.CharField(null=True, max_length=300) # Below are optional entries in case the client chose a certaine type of an insurence # ( than it become required when the client want to sign a contract of that type ) children_number = models.IntegerField(null=True) entry_date = models.DateField(null=True) numberplate = models.IntegerField(null=True) marital_status = models.CharField(choices=Marital, max_length=20, null=True) def __str__(self): return self.username def create_client(sender, instance, created, **kwargs): if created: Client.objects.create(user_ptr=instance) post_save.connect(create_client, sender=User)