Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST EmailAddress matching query does not exist
I am using django rest-auth and allauth to authenticate users. After successful signup and email verification, I implemented a login view which subclasses rest-auth.views.LoginView like below: class ThLoginView(LoginView): def get(self, request): form = CustomUserLoginForm() return render(request, "users/login.html", context={"form": form}) with my own form: class CustomUserLoginForm(AuthenticationForm): class Meta: model = CustomUser fields = ('email',) The problem is that when I login I get this error: DoesNotExist at /users/login/ EmailAddress matching query does not exist. Another important thing that I have changed is that I am using email as the signup/login rather than the username: Settings.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_UNIQUE_EMAIL = True and my user model overwrites AbstractBaseUser like so: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) username = models.CharField(max_length=254, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email The error seems to suggest that the search algorithm is not looking in the right place for the emails. The user's email is definitely entered since I can oversee this in the admin page. why … -
django channels private chat
i am creating a django private chat application using django channels. i am facing the problem about redis. someone told me that redis is not supported in windows OS. can any one have alternate.. settings.py Channel_layer CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } and error shown is connected {'type': 'websocket.connect'} WebSocket CONNECT /chat/abdullah/ [127.0.0.1:55869] Exception inside application: ERR unknown command 'EVAL' File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\utils.py", line 59, in await_many_dispatch await task File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch result = task.result() File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 429, in receive real_channel File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 484, in receive_single index, channel_key, timeout=self.brpop_timeout File "C:\Users\Unknown\PycharmProjects\online_forum\venv\lib\site-packages\channels_redis\core.py", line 327, in _brpop_with_clean await connection.eval(cleanup_script, keys=[], args=[channel, backup_queue]) ERR unknown command 'EVAL' WebSocket DISCONNECT /chat/abdullah/ [127.0.0.1:55869] -
Load/dump fixture from/to json string in django unittest
I have a custom model in django with overriden to_python() and get_db_prep_save() methods. I discovered a bug: when dumping and reloading data it was inconsistent. The bug is fixed but I want to unittest it with simple json string. My question is: how can I call loaddata / dumpdata inside unittest. I want to to create following scenarios: from django.test import TestCase class CustomModelTest(TestCase): def test_load_fixture(self): mydata = '[{"model": "some_app.custommodel", "pk": 1, "fields": {"custom_field": "some correct value"}}]' django.some_interface_to_load_fixture.loaddata(mydata) // data could be as json string, file, stream make some assertions on database model custommodel def test_dump_fixture(self): mymodel = create model object with some data result = django.some_interface_to_dump_fixture.dumpdata() make some assertions on result I know there is fixture=[] field which can be used in django unittests, it could solve loading fixtures scenarios. But if someone could point me to some interface to load or dump fixture data on demand it would be great. -
How to call view for Form in Html template
I want to make a html template in which i want to make three form.(A,B,C) 'A' form should load as default and having two button to open form B and C. A form should call view.A and grab data. Now on button click Form B should be load and Fetch data from view.B as same for C <form name='A' > //should call view.A button B <-- should call Form B and form B grab data from B button C <-- should call Form c and form C grab data from C I do not know this is possible or not !! Help!!!! -
Date' value has an invalid date format. It must be in YYYY-MM-DD format
I am using 3 Date-Fields in models.py and after makemigrations, I did migrate and turned into error. Error: django.core.exceptions.ValidationError: ["'Date' value has an invalid date format. It must be in YYYY-MM-DD format."] Even I removed all the model fields on models.py file and then migrated, but still giving the error. Please anyone who know the best solution? -
Can two Django Objects have multiple intermediate models between them?
In Django, is it possible to create multiple many to many relationships via multiple intermediate models between two models? For example, I have an object user and an object stock_position, and every time the user makes a trade, I want to make an intermediate model (transaction) that has user and stock_position as foreign keys. -
URL is not jumping to right number in Django
models.py from django.db import models class Profile(models.Model): name=models.CharField(max_length=20 ) age=models.IntegerField() def __str__(self): return self.name class Like(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) like=models.IntegerField(default=0) def __str__(self): return self.choice_text views.py from django.shortcuts import render from .models import Profile, Like # Create your views here. def index(request): all_name=Profile.objects.all() context={'all_name':all_name} return render(request, 'database/index.html',context) def detail(request, profile_id): all_likes=Like.objects.get(pk=profile_id) return render(request, 'database/detail.html', {'all_likes':all_likes}) index.html <h1>hey</h1> {% for name in all_name %} <li><a href="{% url 'database:detail' user.id %}">{{ name.name }}</a></li> {% endfor %} detail.html {{all_likes}} urls.py from django.urls import path from . import views app_name='database' urlpatterns = [ path('index/', views.index, name='index'), path('<int:profile_id>/', views.detail, name='detail'), ] now http://127.0.0.1:8000/database/index/ produces two list item, but when I click on both, i am redirecting to http://127.0.0.1:8000/database/1/ . http://127.0.0.1:8000/database/2/ is working manually but not when I click. Couldn't figure out the error in the code. -
Using related_name to return queryset not working in django?
Here I am working with two models.Both models have ForeignKey relation to the User model. Here I wanted to query staffs, is_reviewed_by and sent_by and I tried like this. When I do filter it returns the queryset but when I used related_name to query then it throws AttributeError. How can i do this? `Exception Value: 'Leave' object has no attribute 'reviewed_by models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateField() end_day = models.DateField() is_reviewed_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='reviewed_by',blank=True,null=True) class LeaveReply(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='leave_status') leave = models.ForeignKey(Leave,on_delete=models.CASCADE,related_name='leave_status') sub = models.CharField(max_length=300,blank=True,null=True) msg = models.TextField(blank=True,null=True) sent_on = models.DateTimeField(auto_now_add=True) sent_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='sent_by') views.py def leave_detail(request, pk): leave = get_object_or_404(Leave, pk=pk) reviewers = leave.reviewed_by.all() # not working staffs = leave.staff_leave.all() # does not works staffs = Leave.objects.filter(staff=leave.staff) # this works reviewers = Leave.objects.filter(is_reviewed_by=leave.is_reviewed_by) # works reply_sender = LeaveReply.objects.filter(sent_by=leave.is_reviewed_by) #works reply_sender = leave.sent_by.all() # doesn't works -
how to make a website share some part of its database to other website?
i have a search website that show products and i'm creating e-commerce website for every customer so i want to give them an option so they can choose which product to be shown in my website search result for example : mysite.com, customer1.com, customer2.com so each customer has it's own database and its own website including item1 in their database customer1 and customer2 choose to show item1 in my search result when i search item1 in mysite.com i can see item1 as result is this possible? and how can i do that?(am i good with django or i should go with php or else ) -
adding country and cities django
i want to add country and cities in forms currently i'm using django-countries for country but i'm gettings this error: django.core.exceptions.FieldError: Unknown field(s) (country) specified for CustomUser forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from bootstrap_datepicker_plus import DatePickerInput from tempus_dominus.widgets import DatePicker from .models import CustomUser from django_countries.fields import CountryField class RegistrationForm(UserCreationForm): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) Mobile_Number = forms.CharField(label='Mobile Number', widget= forms.NumberInput) Artist_Category = forms.ChoiceField(choices=CHOICES) bio = forms.CharField(widget=forms.Textarea,label = 'something about yourself') portfolio = forms.URLField(label = 'enter your portfolio') country = CountryField(blank_label = '(select_country)') # country = forms.co class Meta: model = CustomUser fields = ('email','password','Mobile_Number','Artist_Category','portfolio','country','bio',) .......................... -
Django CMS Plugin not loading CSS
I made a django CMS plugin for my news website, from the "article" model. The plugin is "working" in the way that I see all the raw HTML with the data that I want displayed, but It does not apply CSS to my article and I got no clue why. any idea ? My code : plugin: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from news_cms_integration.models import ArticlePluginModel from django.utils.translation import ugettext as _ @plugin_pool.register_plugin # register the plugin class ArticlePluginPublisher(CMSPluginBase): model = ArticlePluginModel # model where plugin data are saved module = _("Article") name = _("Article Plugin") # name of the plugin in the interface render_template = "news_cms_integration/article_plugin.html" def render(self, context, instance, placeholder): context.update({'instance': instance}) return context my plugin html : {% load sekizai_tags %} {% render_block "css" %} <h1>{{ instance.article.title }}</h1> <section class="container post-details-area"> <div class="container single-article-div"> <hr class="hr-single hr-top"> <h2 id="article-title" class="single-article-titles">{{ article.title }}</h2> <hr class="hr-single"> <img class="single-article-img" src="{{ article.article_image.url }}" alt=""> <!-- *********************************** --> <hr class="hr-single"> <p>Category: {{ article.article_category }}</p> <hr class="hr-single"> <div class="row justify-content-center"> <!-- Post Details Content Area --> <div class="col-12 col-xl-8"> <div class="post-details-content bg-white box-shadow"> <div class="blog-thumb"> </div> <div class="blog-content"> <div class="post-meta"> <a href="#">{{ article.pub_date }}</a> </div> <h3 class="single-article-titles post-title"> {{ article.description … -
How can I direct to different apps with different logins in Django project?
I have different apps for different clients in a Django project. And I have a login page. A client can log in and the login credentials will direct to the respective app. Something like the app is created for a particular client and other clients can't access to that particular app. How can I do that? I am confused in redirecting to the particular app in urls.py in Django main project folder (not in urls.py of each app). -
How to trace permission denied 403 error in Django
I am having trouble tracing down a 403 error since I don't get the debug log. On sign up my users select the type of user that they are using a model.CharField: class User(AbstractUser): EMPLOYEE_CHOICES = ( ('dealer', 'DEALER'), ('server', 'SERVER'),) employee_type = models.CharField(max_length=30, choices=EMPLOYEE_CHOICES, default='dealer') During registration I use the users previous selection to assign them to a group: # Register page view def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() emp_type = form.cleaned_data.get('employee_type') group = Group.objects.get(name=emp_type) user.groups.add(group) username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I have a view which is filtered by a PermissionRequiredMixin: # View to create a memo class MemoCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): permission_required = 'memos.can_change_memo' model = Memo fields = ['title', 'content'] All my users which were assigned to the groups which could access this page used to be able to access this page. Nothing should have changed but I seem to only be able to get superusers to be able to access this page. Even when I manually add 100% permissions in the admin panel to a user it … -
How to accept payment in django rest framework based Application?
I am going to start making my first production level API based website. It being my first attempt, I am confused with some of the things: 1> How to accept payments in a rest API based application? 2> As I need to make different UI for accessing the data of my application, does payment now becomes a part of my frontend only? I want to integrate a payments Gateway with my application. I am starting with developing API for my application first. Also suggest, should I use different UI (react/ angular / etc.) or should I use django templates at the starting. -
How to scroll to specific element using the Infinite Scroll With Django?
When I initially load the page, It loads 10 items(1,2,3...10) and after scrolling down I am getting another 10 items(11,12,13,...20). But I need to directly scroll to the 12th element. I am using the Waypoint infinite scrolling(JQuery) and Django pagination. Jquery : $(document).ready(function() { $('html, body').animate({ scrollTop: $("#2").offset().top }, 'slow'); }); // waypoint code: var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], context: document.getElementById('#16'), onBeforePageLoad: function() { $('.loading').show(); }, onAfterPageLoad: function($items) { $('.loading').hide(); } }); While scrolling down the data coming from the Django pagination by triggering the call : http://localhost:8000/polls/?page=2&type=testpoll I need to scroll to an element in the 'page=2' while loading the page initially. How can I do this? -
Django how to display in template a list of distinct value from one column
I try to display a list (in a select) of distinct value of a specific column from a table. The table name is : RankingHasEntreprise and the column name is : risk I did this in my view: risks = RankingHasEntreprise.objects.values_list('risk', flat=True).distinct() risk = "a" # to simplify my code print(risks.count()) # this return 5 return render(request, 'testFiltre.html',{'risk': risk,'risks': risks,}) This is my template: <div class="form-group col-md-2 col-lg-2"> <label for="Risk">Risk</label> <p>{{ risks.count }}</p> <select id="Risk" class="form-control" name="Risk"> {% for risksloop in risks %} {% if risk|add:"0" != risksloop %} <option value="{{ risksloop }}">{{ risksloop}}</option> {% else %} <option selected value="{{ risksloop }}">{{ risksloop }}</option> {% endif %} {% endfor %} </select> </div> And this is the result I get : visual result \n As you can see my select get a value for each tuple of my table "RankingHasEntreprise". This select should only have 5 distinct values a-b-c-d-e. What is disturbing is that when I do a count on my list in my view or template it display me 5. Thanks for reading ! I hope you can solve it =) Cordially -
index.html file for GitHub repository website
I am attempting to publish my website that I have uploaded into a github repository. When I run the website locally (using django) I can see it working perfectly with all of my backgrounds and animations from the css files. This was using the index.html file in the templates folder. When I attempted to run using the github pages, I had to create an index.html file in the main folder so that it can be run from the start. However, this causes my website to include only text files and images, no animations, backgrounds, or colors from my css files. The settings.py has STATIC_URL = '/static/' How can I use the new index.html to call all of my css files? Folder static (folder) css js scss img _init__.py settings.py urls.py Other Folder migrations (folder) templates (folder) index.html views.py admin.py init.py index.py (new for github) -
autocomplete enables for username and password when adding custom fields to django usercreateform
I am using AbstractUser to extend the built in User model. I then Use the UserCreateForm to create add users to the application. When i add my custom fields that I created to the "fields = []" the built in username and password fields in the rendered form starts to autocomplete like its a login, when i remove my custom fields it goes back to normal Link to image with no custom fields rendering as desired https://imgur.com/JFGswFN link to image with custom fields rendering with problem https://imgur.com/rlZI032 may have to copy paste images in web browser first time posting here and could not figure out how to upload an image or get a link to work. I have tried the following and none of it works: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'autocomplete': 'off'}) <form method="POST" autocomplete='off' novalidate> and also tried adding it to the widget section in the Meta class for username and password1 fields. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.text import slugify import string class Department(models.Model): department = models.CharField(max_length=30, unique=True) slug = models.SlugField(unique=True) class Meta: ordering = ['department'] def save(self, *args, **kwargs): self.slug = slugify(self.department) self.department = self.department.title() super(Department, self).save() def __str__(self): … -
Django+Heroku : 500 error when debug=False
This question has been asked before, and I have read all of the solutions that I could find so far. I have a django site hosted on a Heroku free account. It works perfectly when debug is set to true, but when debug is set to false, I receive a 500 server error when trying to access the site on myapp.herokuapp.com . manage.py runserver works perfectly fine I have tried all of the following suggestions, all of which either fail or change the error from 500 to Internal Server Error: commenting out the line STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' creating a custom 500 error page (I don't understand how this would fix the error anyways, but I gave it a shot) Changing allowed hosts to ['*', '.***.com', '.herokuapp.com', 'localhost', '127.0.0.1'] Adding the line COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False) Changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my settings.py I can copy any additional code as needed """ Django settings for personal_portfolio project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import dj_database_url import django_heroku # Build paths inside … -
Django render can't locate a template that actually exists
I have the following view in my Django project: import os from django.shortcuts import render from JumboDjango import settings # Create your views here. def index(request): filename = os.path.join(settings.BASE_DIR, 'frontend/source/public/index.html') return render(request, filename) But, when it is called, it raises the following exception: Internal Server Error: / Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/hugovillalobos/anaconda3/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/views.py", line 8, in index return render(request, filename) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjangoVenv/lib/python3.7/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html [26/Sep/2019 02:51:04] "GET / HTTP/1.1" 500 79956 You can see in the following image that /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html actually exists: I don't know if I am missing any Django configuration, or something. -
Server closed the connection unexpectedly sometimes
Project background: Django project, I use gunicorn to run the project, in the project, i use python socket io to process some event Postgresql, config like this: DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': xxx, 'USER': xxx, 'PASSWORD': xxx, 'HOST': 'xxx', 'PORT': '5432', 'CONN_MAX_AGE': 60 * 10, # seconds 'OPTIONS': { 'connect_timeout': 20, }, } the python socket io will keep a thread to process some events. so the thread has its own postgresql database connection. sometimes, I find it will throw database connection problem, like this, I don't know why the database connection isn't be closed normally Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/engineio/server.py", line 520, in _trigger_event return self.handlers[event](*args) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 590, in _handle_eio_message self._handle_event(sid, pkt.namespace, pkt.id, pkt.data) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 526, in _handle_event self._handle_event_internal(self, sid, data, namespace, id) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 529, in _handle_event_internal r = server._trigger_event(data[0], namespace, sid, *data[1:]) File "/usr/local/lib/python2.7/site-packages/socketio/server.py", line 558, in _trigger_event return self.handlers[namespace][event](*args) File "/usr/src/app/async_worker/controllers/server/event_handler.py", line 61, in on_jira_handle_from_client_retrieve ticket = Ticket.get_ticket_by_id(ticket_id) File "/usr/src/app/review/models/ticket.py", line 144, in get_ticket_by_id return Ticket.objects.filter(id=ticket_id).first() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 564, in first objects = list((self if self.ordered else self.order_by('pk'))[:1]) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line … -
Python crashes while closing and open new Keras(tensorflow) session
I'm making a model to service with Keras & Django. The purpose is initializing models with various hyperparams or load models, which are same architecture but, weights(parameters) and hyperparameters are different. Because weights are valid in each session, 'model_init' or 'load_model' method close and open tf.Session() each time it is called. However, After initializing new model or load other models, Python crashes and Django service shuts down. It seems to be related with session & memory. Below is my code: class keras_model: session = None graph = None model = None def model_init(~): # hyper parameter setting tf.reset_default_graph() self.graph = None if self.session is not None: self.session.close() # del self.session self.session = None self.graph = tf.Graph() with self.graph.as_default(): self.session = tf.Session(graph=self.graph) with self.session.as_default(): # model definition self.model = models.Model(~) self.model.compile(~) def train(): with tf.device(self.device): with self.graph.as_default(): with self.session.as_default(): training_log = self.model.fit(~) return training_log def predict(): ~ def load_model(): tf.reset_default_graph() self.graph = None if self.session is not None: self.session.close() self.session = None self.graph = tf.Graph() with self.graph.as_default(): self.session = tf.Session(graph=self.graph) with self.session.as_default(): # load model architecture self.model = model_from_json(~) # load model weight self.model.load_weights(~) def save_model(): ~ Any idea or suggestion would be appreciated. -
Using Django, how to filter from an object based on FK using a column and get distinct values
My DB query is below: select distinct m.topic from education.sessions s, education.modules m where s.subject_id = 'Biology' and s.module_id = m.id and m.status = 'Active' order by m.topic I am trying the equivalent of the above in QuerySet and I do not seem to get it.First off, I do not know where to include the status='active' check and the "Order By". Session and Module are my 2 tables with Session having a FK on module. Module has 2 columns Subject and Topic and I need the unique topics for the given subject if status = 'Active' In Views.py, I have the below: def load_topics(request): subject = request.GET.get('subject') topics = Session.objects.filter(subject=subject).values_list('module__topic', flat=True).distinct() return render(request, 'evaluation/topic_dropdown_list_options.html', {'topics': topics}) -
In the Django, get multiple Counts of various conditions
I am developing "Admin DashBoard" with Django 2.2 I'd count "Objects" of various conditions from one table and send them to the template. My code is below.. # model class User(models.Model): uid = models.AutoField(primary_key=True) status = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) created_at_unix = models.CharField(max_length=100, blank=True, null=True) country_code = models.IntegerField(blank=True, null=True) recommender_id = models.ForeignKey('self', on_delete=models.SET_NULL ,blank=True, null=True, db_column='recommender_id') is_agreement = models.PositiveIntegerField(blank=True, null=True) delete_yn = models.CharField(max_length=1, default='n') is_sms = models.PositiveIntegerField(blank=True, null=True) is_email = models.PositiveIntegerField(blank=True, null=True) is_push = models.PositiveIntegerField(blank=True, null=True) def index(request): # New User user_lastweek = User.objects.filter(created_at__gte=last_monday, created_at__lte=last_sunday).count() user_thisweek = User.objects.filter(created_at__gte=this_monday, created_at__lte=tomorrow).count() user_variation = user_thisweek - user_lastweek # User total user_total_lastweek = User.objects.filter(created_at__lte=last_sunday).count() user_total_thisweek = User.objects.filter(created_at__lte=tomorrow).count() user_total_variation = user_total_thisweek - user_total_lastweek context = { 'user_lastweek':user_lastweek, ... } return render(request, 'main/index.html', context) I have written only a few of the many conditions. But my code is causing duplicate query hitting every time. The result I need is like.. 1. user_lastweek : 114 2. user_thisweek : 98 3. user_total_lastweek : 1232 4. user_total_thisweek : 1330 How is it efficient to render to a template with only one query or fewer queries? -
django DB linked with AWS S3 on heroku
Currently I'm trying to make a website for a friend, who will have ability to save Models in django admin panel. I have already realased it on Heroku however due to the problem that any changes to the heroku filesystem whilst the dyno is running only last untill that dyno is shut down or restarted and what it means that the data which is created by my friend will be gone. In order to solve this problem I decided to connect it with AWS S3 and save there whole data. I found some answers about uploading media files like photos, but neither of them is about saving the whole model. It's like saving database there. Am I thinking wrong? How can I do this? I have already done things like creating bucket and connecting it with django with secret keys etc.