Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django change last_login from DateTimeField to IntegerField
i have a litte probleme i have a legacy database that have a users table and in the table of users the last_login field is an integerfield when I have extend an absractbaseuser and put the last_login in IntegerField it give a me an error when trying to connect to django dashboard it say that the last_login field expected a number but got date time value any help please ? -
How to add empty_label with smart-selects ChainedForeignKey in Django
I have the following models: class CompanyRole(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Office(models.Model): company_role = models.ForeignKey(CompanyRole, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) def __str__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) company_role = models.ForeignKey(CompanyRole, on_delete=models.SET_NULL, null=True) office = ChainedForeignKey( Office, on_delete=models.SET_NULL, null=True, blank=True, chained_field="company_role", chained_model_field="company_role", show_all=False, auto_choose=True, sort=True, ) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username And the following form: class RegisterForm(UserCreationForm): office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office') def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.pop("autofocus", None) class Meta: model = User fields = ["username", "email", "company_role", "office"] This was all working fine with the chained selects from smart-selects app, however I needed to show the empty_label to show 'Select Office' which I managed to do by adding the following line to my form as shown above: office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office') But since adding that line to my form the empty_label now shows but the chained selection is broken as in previously the user would select company role and depending on selection would populate the list of offices. For example: company role selection was translator then no offices would be populated but if they selected … -
JQuery UI Autocomplete for Django
The project I'm currently working on requires that a form field have autocomplete functionality. The data to be populated in the autocomplete list is pulled each time the page is loaded using an API call to a 3rd-party platform. Is it possible to call a Django views function (that will implement the above mentioned API call) to provide the JQuery-UI source with the list for auto-completion? According to the documentation (https://api.jqueryui.com/autocomplete/#option-source), the source function type might be the best option for my scenario, but I might be mistaken. So I'm open to a better way of doing it in JQuery-UI if possible. thanks. -
How "--keepdb" affects setUpTestData?
From the Django documentation I see that a Django TestCase wraps the tests within two nested atomic() blocks: one for the whole class and one for each test. Then I see that setUpTestData method "allows the creation of initial data at the class level, once for the whole TestCase": so we're talking about the whole class atomic block. This means that the --keepdb flag should not affect this behaviour, because what this flag do is just skip the database create/destroy. But I noticed that if I run the test with the --keepdb flag the data I create in the setUpTestData method are preserved. I'm fine with this but I want to understand what --keepdb exactly does, because I can't understand why this happens. I tried to look directly at the Django TestCase class source code but I don't see any check about the --keepdb option. Why - if I run my test with the --keepdb option - the data I create in setUpTestData method are preserved? -
Heroku Python Local Environment Variables
Working on a heroku django project. Goal: I want to run the server locally with same code on cloud too (makes sense). Problem: Environments differ from a linux server (heroku) to a local PC windows system. Local environment variables differ from cloud Heroku config vars. Heroku config vars can be setup easily using the CLI heroku config:set TIMES=2. While setting up local env vars is a total mess. I tried the following in cmd: py -c "import os;os.environ['Times']=2" # To set an env var then py -c "import os;os.environ.get('Times','Not Found')" stdout: "Not Found". After a bit of research it appeared to be that such env vars are stored temporarily per process/session usage. So I came up with the idea of using .env file. I would like os.environ to be redirected to .env file of the root heroku project instead of the PC env vars. So I found this perfect tool direnv perfect solution for Unix-like OSs but not for Windows. views.py code (runs perfect on cloud, sick on the local machine): import os import requests from django.shortcuts import render from django.http import HttpResponse from .models import Greeting def index(request): # get method takes 2 parameters (env_var_string,return value if var is … -
Getting sum of averages in a django queryset
def get_queryset(self): current_academic_year = get_current_academic_year() domains = Domain.objects.all() start_date = self.request.query_params.get("start_date", current_academic_year.start_date) end_date = self.request.query_params.get("end_date", current_academic_year.end_date) queryset = Account.objects.annotate(**{ f"domain_overall_{domain.uuid}": Avg( "assessed_from__accountevaluationresult__calculated_rating", filter=Q( assessed_from__updated__range=(start_date, end_date) ) & Q(assessed_from__domain=domain) ) for domain in domains }).annotate(**{f"domains_total": ~query~ }) There are five domains. Here I got 5 key-value pairs with certain calculated values for each domain. I need to get the sum of those values from the first annotation, but have no idea how to retrieve it in continuous annotations. Response I need in a json must be like this: "domain_overall_8939396e-d0a9-4c87-afe1-ae3a4660d84b": 2, "domain_overall_786a99b4-38fd-4b60-ac91-5a09f007db32": 1, "domain_overall_a1f503a7-5e77-47ee-a812-7ae1fb4e8a84": 1, "domain_overall_4c55b38b-8471-48d1-bc43-323570b290a4": 1, "domain_overall_6ec0c80b-5afe-4ac2-8c07-0fff5c4f023c": 3, "domains_total": 8, What is the best approach/solution here? -
Getting error "product has no attribute " ON SerializerMethodField
Im using django raw query for some reason. where as product dont have fieldsexpiry_date so im externally adding this and some fields by using SerializerMethodField(). The thing is it is working in local fine but getting error in production 'Product' object has no attribute 'expiry_date'. CODE: # VIEWS query = Product.objects.raw( 'SELECT * FROM product p LEFT JOIN category c ON p.category=c.id WHERE p.id=' + str(product_id) ).using('product') serializer = RawSingleStockData(query[0], context={"stock": query2}).data # SERIALIZER class RawSingleStockData(serializers.Serializer): ... expiry_date = serializers.SerializerMethodField() ... def get_expiry_date(self, obj): return False ERROR: File "/home/aaa/aaa/pharmacy_product_list/views.py" in post 222. serializer = RawSingleStockData(query[0], context={"stock": query2}).data File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data 559. ret = super().data File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data 261. self._data = self.to_representation(self.instance) File "/home/aaa/aaa/pharmacy_product_list/serializer.py" in to_representation 1118. representation = super().to_representation(instance) File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation 513. attribute = field.get_attribute(instance) File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute 476. raise type(exc)(msg) Exception Type: AttributeError at /pharmacy_product_list/product/name/ Exception Value: Got AttributeError when attempting to get a value for field `expiry_date` on serializer `RawSingleStockData`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'expiry_date'. -
The SECRET_KEY setting must not be empty. Django docker
i tried to find solution on stack and other websites but without result. Im fighting with django for some days. I got my django app dockerized and it works fine. I'm using .env file to serve secret variables. And here start the problem. I can't use travis CI or debug mode in Visual Studio Code becouse my env variables are not visible. When im trying to run travis or debuger, im getting error "The SECRET_KEY setting must not be empty". The question is, how to properly configure my django app or docker instance to use env variables in every situation? Some days ago i tried to write secret_key without hidding it, but my debuger is failing on connection with database, so it seems that my variables are not visible at all. But as i said, when i run my app in normal mode or as a docker instance it works fine, my .env file is visible for django. Here you can find my settings.py SECRET_KEY = os.getenv('SEC_KEY') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': 5432 } } And here is my docker-compose file: version: '3.4' services: electronicshop: image: electronicshop build: context: …