Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting a 404 Error when I've clearly defined my urlpatterns?
My project is storefront and when I run the server I get the error message "Page not found". I have my urls.py file in the storefront folder for you to look at. I've looked around on the internet and have had no luck yet. urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] I thik the problem is in my urls.py specifically with "include" but not sure. -
Django Haystack select which fields to search
Suppose I have a Person model looking like this: class Person(models.Model): title = models.CharField(max_length=300, blank=True, null=True) first_name = models.CharField(max_length=300, blank=True, null=True) last_name = models.CharField(max_length=300, blank=False, null=False) And a Haystack search index like this: class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') first_name = indexes.CharField(model_attr='first_name') last_name = indexes.CharField(model_attr='last_name') Say the template includes all three fields(firstname, lastname and title). If users should be able to choose in which fields to search for, do I need to build seperate indices for all possible permutations? Or can I narrow down the search to one or two of the three fields? If so how? I know that I am able to filter SearchQuerySets using .filter(). SearchQuerySet().filter(first_name='foo') But this filters the set for exact values. Even __icontains is limited to one field filtering. -
How to make django not render html?
I have model: class NewsItem(models.Model): meta_title = models.CharField(_('Meta title'), max_length=255, blank=True, null=True, help_text=mark_safe('Tag <title>')) But on the page I have: <div class="form-row field-meta_title"> <div> <label for="id_meta_title">Meta title:</label> <input type="text" name="meta_title" class="vTextField" maxlength="255" id="id_meta_title"> <div class="help">Tag <title></div> </div> </div> How to tell django not render html? -
Python Flask - Errors after creating a new project
After creating a new project and trying to run it, I get something like this: * Environment: development * Debug mode: off Traceback (most recent call last): File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\__main__.py", line 3, in <module> main() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 994, in main cli.main(args=sys.argv[1:]) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 600, in main return super().main(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1053, in main rv = self.invoke(ctx) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 853, in run_command run_simple( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 1010, in run_simple inner() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 950, in inner srv = make_server( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 782, in make_server return ThreadedWSGIServer( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 688, in __init__ super().__init__(server_address, handler) # type: ignore File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe6 in … -
Getting error while using migrate after inspectdb using sqlite
I need to make an API from an existing sqlite db. I used inspectdb for creating models from the database. Do I need to manually add the primary keys(id) for all tables after inspect in my models.py? After that what should I do, migrate? Makemigrations? I am getting error related to one of the tables in the databases after doing migrate,(issue with one table referencing other). Is there an issue with the db? Here is my settings.py """ Django settings for IMS project. Generated by 'django-admin startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u@yr4&95+m=v*6o53in2*82xn@292n(6-#ixj38-^8l8e3(4$h' # 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', "Api.apps.ApiConfig", "rest_framework", ] 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 = 'IMS.urls' TEMPLATES … -
Truncated or oversized response headers received from daemon process error with PiCamera library
I am hosting a simple Django website using Apache2 and WSGI. The website works fine but when I attempt to instantiate a PiCamera() object I get this error. All I am trying to do is initiate a photo capture and update the image on the website every time the website is refreshed. I feel like it should not be this difficult. I have searched all over and cannot find a solution. I have attempted to add WSGIApplicationGroup %{GLOBAL} to my sites-available/000-default.conf as well as my apache2.conf. I have also attempted to increase the head buffer size and neither solution work. Any help would be appreciated. Views.py from django.shortcuts import render from django.http import HttpResponse from .models import RelayList from .forms import RelayControl from .gpio import Update_Relays from django.contrib.auth.decorators import login_required from picamera import PiCamera from time import sleep def Snapshot(): camera = PiCamera() #<---THIS IS WHAT CAUSES THE TRUNCATED ERROR # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # camera.stop_preview() # Create your views here. @login_required def index(response): curList = RelayList.objects.get(id=1) #retrieves the database object and places it into a variable Snapshot() #takes a photo and saves it to images directory # camera = PiCamera() # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # … -
AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage'
Am getting the above error when try to run the server. Below is the full error. AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' File"C:\Users\admin\Desktop\InstitutionFinderWebsite\ InstitutionFin derWebsite\urls.py", line 26, in <module>path('HomePage/', views.HomePage), AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' I had imported all the views from the three apps as below from django.conf.urls import include from django.contrib import admin from django.urls.conf import path from HomePage import views from PublicSchools import views from PrivateSchools import views On the urls.py have tried the 2 methods below but the are not all working. Method one here i used views. to map the urls. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage), path('PublicSchools/', views.PublicSchools), path('PrivateSchools/', views.PrivateSchools), ] This is Method two in trying to solve it by trying to give the names. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage, name='PrivateSchools'), path('PublicSchools/', views.PublicSchools, name='PublicSchools'), path('PrivateSchools/', views.PrivateSchools, name='PrivateSchools'), ] Kindly help out. Am stuck. -
AttributeError: 'Post' object has no attribute 'post_image'
I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request. I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request. Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'Post' object has no attribute 'post_image'. Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it? #models.py class Post(Authorable, Model): created_at = models.DateTimeField(default=timezone.now) caption = TextField(max_length=350) class Images(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.FileField(upload_to="images/") class Videos(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) videos = models.FileField(upload_to="videos/") #behaviours.py class Authorable(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: abstract = True def get_user(self): return self.user.id #serializers.py class ImageViewSerializer(serializers.ModelSerializer): class Meta: model = Images … -
Understanding Model.from_db() in Django
I was reading Django Official Doc for Model, it reads: classmethod Model.from_db(db, field_names, values)¶ The from_db() method can be used to customize model instance creation when loading from the database. The db argument contains the database alias for the database the model is loaded from, field_names contains the names of all loaded fields, and values contains the loaded values for each field in field_names. The field_names are in the same order as the values. If all of the model’s fields are present, then values are guaranteed to be in the order __init__() expects them. That is, the instance can be created by cls(*values). If any fields are deferred, they won’t appear in field_names. In that case, assign a value of django.db.models.DEFERRED to each of the missing fields. I am completely lost when reading above. 1st perception: "when loading from the database": for me, loading means reading / retrieving data from database, which means the model instance already exists or is created and stored in DB. 2nd perception: "be used to customize model instance creation", as well as the 2nd paragraph all makes me feel that this from_db() is for model instance creation, which conflicts with my 1st perception. Q: Can … -
How can I return the refresh token using python-social-auth and django-graphql-auth?
How can I return the refresh token when using social auth? I tried this solution here I don't know how to make this compatible with graphql. Here is my attempt: import graphql_social_auth from graphql_jwt.shortcuts import get_token class SocialAuth(graphql_social_auth.SocialAuthJWT): refresh_token = graphene.String() token = graphene.String() @classmethod def resolve(cls, root, info, social, **kwargs): return cls( user=social.user, token=get_token(social.user), refresh_token=social.extra_data['refresh_token'] ) The user and token fields are alright when I comment out the refresh token. I just don't know where to get the refresh token, it seems to be not in the extra_data. I am already dealing with this problem for hours and all the search results are no help. Please, any guidance is really appreciated. -
How to Add a comment section in Django using model form
I m New in Django I started a project of blog I wanted to add A comment section feature in my Project I Am Having a error Mode form is not defined in class view.py from Blog.models import Comment from Blog.forms import CommentForm def post_detail_view(request,year,month,day,post): post=get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments=Comment.objects.filter(active=True) csubmit=False if request.method=='POST': form=CommentForm(data=request.POST) if form.is_valid(): new_comment=form.save(commit=False) new_comment.post=post new_comment.save() csubmit=True else: form=CommentForm() return render(request,'blog/detail.html',{'post':post,'comments':comments,'csubmit':csubmit,'form':form}) if I tried to run this function I want to display a form in detail page and if end user submit the form then display same page detail.html <!doctype html> {% extends "blog/base.html" %} {% block title_block %} detail Page {% endblock%} {% block body_block %} <h1>This Is Your Content</h1> <div> <h2>{{post.title|title}}</h2> </div> <div> {{post.body|title|linebreaks}} <p>Publised of {{post.publish|title}} Published By {{post.author|title}}</p> <div> {% with comments.count as comments_count %} <h2>{{comments_count}} Comment{{comments_count|pluralize}}</h2> {% endwith%} <div> {%if comments %} {%for comment in comments %} <p> comment {{forloop.counter}} by {{comment.name}} on {{comment.created}} </p> <div class="cb">{{comment.body|linebreaks}}</div> <hr> {%endfor%} {%else%} <p>There are NO Comments Yet !!!</p> {%endif%} {%if csubmit %} <h2>Your Comment Added Succefully</h2> {%else%} <form method="post"> {{form.as_p}} {%csrf_token%} <input type="submit" name="" value="Submit Comment"> </form> {%endif%} </div> {%endblock%} here I defined my form forms.py from Blog.models import Comment class CommentForm(ModelForm): class … -
How to add a new obj from html in django
So im trying to make this page where i add new category which only has name. But when i try it, i just get a "non-string type" as the name. So it works i guess just doesn't take whatever i give it in my input in html. HTML: <input type="text" class="form-control" placeholder="Name" id = "category-create-name" name= "category_name"> <input type="submit" class="login-button" value="Post"> Model: class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Form: class CategoryCreateForm(forms.ModelForm): class Meta: model = Category fields = ('name',) widgets = { 'category_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name', 'id':'category-create-name'}), } View: class CategoryCreateView(CreateView): form_class = CategoryCreateForm template_name = 'product/new_category.html' success_url = '/dashboard/' -
Django Rest Framework trying to get similar products with serializer reversed
i`m new to DRF and im trying to serialize similar product on product. heres my code models.py class Product(models.Model): headline = models.CharField(max_length=150) category = models.ManyToManyField(Category, related_name="products") tag = models.TextField(null=True, blank=True) sku = models.CharField(max_length=50, unique=True) sell_limit = models.IntegerField(default=10) price = models.FloatField(default=0) class SimilarProduct(models.Model): on_product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True, related_name="on_products") product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True, related_name="products") serializers.py class ProductDetailSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() similar = serializers.SerializerMethodField() in serializers i have written this type of code which dont works. #CODE : def get_similar(self, obj): product_query = Product.objects.filter(pk__in=obj.on_products.values_list("id")) return ProductListSerializer(product_query, many=True).data and heres my ProductListSerializer class ProductListSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() price = serializers.SerializerMethodField() i want to get similar products of product but it dont works. any ideas how to solve? -
Vue.js and Django multiple image rendering
I am having some major issues trying to render multiple images to my Vue.js frontend from a static folder in my Django project. I can get one image showing without issues but it does not seem to work for multiple images. My images are uploaded via the admin section of the app. Any help would be really appreciated I have spent days on this!!!!! Here is my models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return self.title class LessonImage(models.Model): lesson_image = models.ForeignKey(Lesson, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to ='uploads/') def save(self, *args, **kwargs): super(LessonImage, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 1125 or img.width > 1125: img.thumbnail((1125,1125)) img.save(self.image.path,quality=70,optimize=True) def get_images(self): if self.lesson_image: return settings.WEBSITE_URL + self.lesson_image.url And my serializers.py. * Im not sure I needed to implement the image models in the serializers but I have tried this to test: class … -
chat app work perfectly in local but stopped working when deployed to heroku - django
I did a chatting part in my web app with django it works perfectly in local but after I deployed it, it doesn't work: in the template this is the connection request part with js: /* connection request */ const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendName['username'] + '/' ); in my chat app this I have routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<friend>\w+)/$', consumers.ChatConsumer.as_asgi()), ] it works perfectly in local but not anymore working after deployement, am I messing something -
Javascript file make css not to work in django
When i include the js file in base.html <script src="static/assets/js/functions.js"></script> the CSS stops working entirely but when i remove the JS file or comment it out the CSS start loading and rendering well. I even tried putting the whole js code manually into the base.html but it still doesnt work i dont really know what to do right now. base.html <head> <title>Eduport - LMS, Education and Course Theme</title> <!-- Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="Webestica.com"> <meta name="description" content="Eduport- LMS, Education and Course Theme"> <!-- Favicon --> <link rel="shortcut icon" href="{% static 'assets/images/logo.svg' %}"> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;700&family=Roboto:wght@400;500;700&display=swap"> <!-- Plugins CSS --> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/font-awesome/css/all.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/bootstrap-icons/bootstrap-icons.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/tiny-slider/tiny-slider.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/vendor/glightbox/css/glightbox.css' %}"> <!-- Theme CSS --> <link id="style-switch" rel="stylesheet" type="text/css" href="{% static 'assets/css/style.css' %}"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-7N7LGGGWT1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-7N7LGGGWT1'); </script> </head> <!-- Footer --> <!-- Bootstrap JS --> <script src="{% static 'assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js' %}"></script> … -
Why the session data isn't flush when I logout?
Working on a simple project using Django 3.8, I have recently added a login register form to the application. The login register works very well but when I log out from the account the session isn't flushed, and that means that I can still login without entering the credentials as normally would it be. To create the login/register I have used the Django library which is: from django.contrib.auth import authenticate, login, logout, and in the documentation, it says that the logout(request) function deletes the session by itself: https://docs.djangoproject.com/en/4.0/topics/auth/default/ but actually, the session isn't flushed after I log out. I also check the process in Application, Cookies in the inspect. To understand better of what I have done, will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): user = request.user count_item = todo.objects.count() all_items = todo.objects.filter(user=request.user).order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) … -
HandshakeException: Handshake error in client (OS Error: I/flutter ( 9113): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(handshake.cc:359))
Connection code till yesterday everything working properly but now it giving the error to connect the json data. ........................................................................................................................................................................................... class ProductDataStacture with ChangeNotifier { List<Products> _products = []; List<Banners> _banners = []; List<Categories> _category = []; List<Random> _random = []; Future<bool> getProducts() async { String url = 'https://shymee.com'; try { // http.Response response = await http.get(Uri.parse(url + "/home"), var response = await http.get(Uri.parse(url + "/home"), headers: { 'Authorization': 'token a867c3c092e8b1195f398ed5ca52dda4e5ff5ed8' }); var data = json.decode(response.body); print(data); List<Products> prod = []; List<Banners> bann = []; List<Categories> cate = []; List<Random> ran = []; data['products'].forEach((element) { Products product = Products.fromJson(element); prod.add(product); print("this is product ${product}"); }); data['banners'].forEach((element) { Banners banner = Banners.fromJson(element); bann.add(banner); }); data['categories'].forEach((element) { Categories category = Categories.fromJson(element); cate.add(category); }); data['random'].forEach((element) { Random random = Random.fromJson(element); ran.add(random); }); _products = prod; _banners = bann; _category = cate; _random = ran; return true; } catch (e) { print("e getProducts"); print(e); return false; } } List<Products> get productsList { return [..._products]; } List<Banners> get bannersList { return [..._banners]; } List<Categories> get categoryList { return [..._category]; } List<Random> get randomList { return [..._random]; } } -
Referencing a field in Django template gives output None
I've got a problem. I don't know how to reference product category on my for loop in Django Template. I have added a random category to a Product (in database), but no matter which category i choose, the output on the site from {{product.product_category.name}}is "None" : def all_products(request): product = Product.objects.all().order_by('-created_at').a paginator = Paginator(product, 25) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, } return render(request, 'ecommerce/all_products.html', context) then my for loop on Django template looks like this {% for product in page_obj %} <div class="col-xl-4"> <a class="card border border-light hover-shadow-9 px-4 py-2" href="{% url 'ecommerce:product_detail_view' product.slug %}"> <p class="mb-0 small-3 text-light">{{ product.product_producer }}</p> <p class="mb-0">{{ product.name }}</p> <p class="mb-0">{{ product.product_category.name }}</p> </a> </div> {% endfor %} Model product looks like this class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) product_category = models.ManyToManyField(EcommerceProductCategory) description = RichTextField(max_length=2000, null=True, blank=True) product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE) creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator') points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu') unique_id = models.CharField(max_length=256, unique=True) type_of_unique_id = models.CharField(max_length=64) product_img = models.FileField(upload_to='ecommerce_product_img/', null=True, blank=True) And the categories are connected with EcommerceProductCategory class EcommerceProductCategory(MPTTModel): name = models.CharField(max_length=64, null=True, unique=False) slug = models.SlugField(max_length=40, unique=False, … -
How to use the cached results in cacheops with django
I am trying to use cacheops where I have a view that contains a variable I want to cache bo = Bo.objects.all().cache() The chached bo I tried to use in another view like this all = cache.get('bo') This does not work Here is the traceback .... File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\cacheops\simple.py", line 83, in get return self._get(get_prefix() + cache_key) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\cacheops\simple.py", line 99, in _get raise CacheMiss cacheops.simple.CacheMiss My settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } CACHEOPS_DEGRADE_ON_FAILURE=True CACHEOPS_ENABLED = True CACHEOPS_REDIS = { 'host': 'localhost', 'port': 6379,} CACHEOPS = { 'libman.*': {'ops': 'all', 'timeout': 60*15},} -
Django: in template take only first 2 letters of a variable taken by database
I'm new to Django and I'm trying to get only the first 2 letters of a Variable Name passed on by the database. Here's my HTML code: <td class="process-title"> <p data-letters="{{account.variable_name}}" class="text-accounts"> {{account.variable_name }}</p> </td> In the data-letters Tag I'd like to pass only 2 letters instead of the whole word. This is my view.py: def accounts(request): if request.user.is_authenticated: all_accounts = Accounts.objects.all().order_by('variable_name') context = { "accounts": all_accounts, } return render(request, 'engine/accounts.html', context) I'm attaching a picture of the result I'm trying to achieve. How can I achieve this? Thank you all -
How to create model objects via a submitted form
How to create model objects via a submitted form. Like here is a model:- class <-->(models.Model): Name = models.CharField(max_length=122) Student_Code = models.CharField(max_length=122) E_Mail = models.CharField(max_length=122) Password = models.CharField(max_length=122) Date = models.DateField() Time = models.CharField(max_length=122, default=None) def __str__(self): return str(self.Date) I want to create a new model class in which I want to change <--> to a desired name from views.py. -
KeyCloack integration wirh DRF (Django Rest Framework)
I am a beginner level DRF developer. I am trying to integrate Keycloak with Django Rest Framework. Unfortunately, I was unable to find any type of help/blog/tutorial online. If anyone here has any kind of information regarding this, kindly share. Eagerly waiting for your reply. Thanks -
Using signals for two models both inheriting from User in Django
Suppose we have two models that have signal to the User model: from django.db import models from django.contrib.auth.models import User from django.db.models import signals class Company(User): name = models.CharField(null=True, blank=True, max_length=30) if created: Company.objects.create( user_ptr_id=instance.id, username=instance.username, password=instance.password, email=instance.email, first_name=instance.first_name, last_name=instance.last_name, is_active=instance.is_active, is_superuser=instance.is_superuser, is_staff=instance.is_staff, date_joined=instance.date_joined, ) signals.post_save.connect( create_company, sender=User, weak=False, dispatch_uid="create_companies" ) class Individual(User): name = models.CharField(null=True, blank=True, max_length=30) def create_job_seeker(sender, instance, created, **kwargs): """ :param instance: Current context User instance :param created: Boolean value for User creation :param kwargs: Any :return: New Seeker instance """ if created: ''' we should add a condition on whether the Company uses the same username if true, then, we must not create a JobSeeker and we would disable the account using Firebase Admin ''' JobSeeker.objects.create( user_ptr_id=instance.id, username=instance.username, password=instance.password, email=instance.email, first_name=instance.first_name, last_name=instance.last_name, is_active=instance.is_active, is_superuser=instance.is_superuser, is_staff=instance.is_staff, date_joined=instance.date_joined, ) signals.post_save.connect( create_job_seeker, sender=User, weak=False, dispatch_uid="create_job_seekers" ) Now, each time a User is created we should be allowed to extend it through both Individual and Company models. But, I want to prohibit the usage of both objects. User can either have a Company or an Individual object to be edited not both. Should I override the save method such as this: def save(self, *args, **kwargs): if not Company.objects.filter(username=self.username).exists(): super(Model, … -
How to more Enhance my Machine Learning code? [closed]
Hello Thanks in Advance...! In my Django Project this is the ai.py file. Here, I am using Best Predictive Model LSTM for getting prediction. I want more improvement in this Model.. HOW??? Here is set the weights 70% for first 2 weeks and 30% for pending data. For getting max efficiency I am using **adam and Nadam ** optimizers. **Anyone is here to improve this model??? ** # start up keras from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout from keras.optimizers import Adam, Nadam from sklearn.preprocessing import MinMaxScaler # assert optimizer if optimizer not in ['adam', 'nadam']: print("Invalid optimizer specified, can either be adam or nadam") return # prepare data supervised_df = series_to_supervised(df, cols_in, cols_out, days_in, days_out) values_in = supervised_df.filter(regex='t-').columns values_out = supervised_df.drop(columns=values_in).values values_in = supervised_df[values_in].values # scale data scaler_in = MinMaxScaler(feature_range=(-1, 1)) scaler_out = MinMaxScaler(feature_range=(-1, 1)) values_in = scaler_in.fit_transform(values_in) values_out = scaler_out.fit_transform(values_out) # divide data into train, valid, test train_x, train_y = values_in[:int(len(values_in) * 0.80)], values_out[:int(len(values_out) * 0.80)] valid_x, valid_y = values_in[int(len(values_in) * 0.80):], values_out[int(len(values_out) * 0.80):] # reshape data n_cols = len(cols_in) train_x = train_x.reshape((train_x.shape[0], int(train_x.shape[1] / n_cols), n_cols)) valid_x = valid_x.reshape((valid_x.shape[0], int(valid_x.shape[1] / n_cols), n_cols)) # weights to add # weight_dict = {k: v for …