Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin custom form - Foreign key field as searchable instead on dropdown
class modelA(Base): account = models.ForeignKey… user = models.ForeignKey… class modelB(Base): user = models.ForeignKey… amount = models….. class modelC(Base): modelA = models.ForeignKey(modelA) modelB = models.ForeignKey(modelC) class formA(forms.ModelForm): account = forms.ModelChoiceField(queryset=Account.objects.all()) user = forms.ModelChoiceField(queryset=User.objects.all()) amount = CustomField….. def save() … class formAAdmin(admin.ModelAdmin): form = formA raw_id_fields = (‘account’) // Cannot use account as it does not belong to modelC. Account is shown as a dropdown but I want it as a popup where we can search. I am getting this error when I added account in raw_id_fields. : (admin:E002) the value of ‘raw_id_fields[0]’ referes to account which is not an attribute of ‘modelC’ . Since account is not part of the modelC, it just displayes it as a dropdown. How can I make it show search for account? -
Simpe upload image button in django
I am new in Django, so do not be mad, i just do not know how to add a button which will upload a file to the specific post in my model. So the problem is how to get the identifier of each post from my model without go to specific url, only in page with all posts My model: class Post(models.Model): title = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=50, unique=True) project_image = models.ImageField(upload_to='images/', blank=True) technologists = models.ManyToManyField('ImageTag', blank=True, related_name='tags') description = models.CharField(max_length=200, blank=True) programme_language = models.CharField(max_length=40, blank=True) update_time = models.CharField(max_length=40, blank=True) link = models.URLField() def __str__(self): return self.title def get_absolute_url(self): """Gettign the absolute url of index.html""" return reverse('project_detail_url', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('project_edit_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('project_delete_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): """Complement the method save of django Model""" # if not self.id: # self.slug = gen_slug(self.title) if not self.slug: self.slug = gen_slug(self.title) if self.slug: checker = self.slug.strip() if checker: pass else: self.slug = gen_slug(self.title) super().save(*args, **kwargs) my main html pattern which extend base html pattern and which contain each post detail from my model: {% extends 'base.html' %} {% block content %} {% for post in posts %} <div class="post-wrap"> <div class="title_and_image"> <h2>{{ post.title }}</h2> … -
Django ModelSelect2MultipleWidget FormView won't display initial data
I am using django_select2.forms.ModelSelect2MultipleWidget, forms.Form, FormView. I have 3 tables: Job, HelpText, JobHelpText. From a Job detail page, I want to direct to the Form view (autocomplete multiple select widget), and for that input to have the initial data of all other Jobs associated with that Help Text. What is working: I can autocomplete search for jobs. It only gives access to jobs without help text (like desired). Python print statement is even showing the correct initial data. What won't work: The initial data won't pre-fill in the input box. class Foo(models.Model): job_name = models.CharField(max_length=200, blank=False, null=False) env = models.CharField(max_length=200, blank=False, null=False) ... def __str__(self): return self.job_name class HelpText(models.Model): name = models.CharField(unique=True, max_length=255) ... def __str__(self): return self.name class FooHelpText(models.Model): foo = models.OneToOneField(Autosys, on_delete=models.CASCADE,) help_text = models.ForeignKey(HelpText, on_delete=models.DO_NOTHING, ) ... def __str__(self): return str(self.foo) class ManageFooJobs(AdminCapableJSMixin, django_select2.forms.ModelSelect2MultipleWidget): """ only show foo jobs that have no help text """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = models.Foo.objects.filter(foohelptext__isnull=True) search_fields = [ 'job_name__icontains', ] class ManageJobsForm(forms.Form): """ add or remove jobs """ foo_jobs = forms.MultipleChoiceField( widget=widgets.ManageFooJobs(), required=False, ) class ManageJobsView(LoginRequiredMixin, BootstrapFormMixin, FormView): """ able to add and remove jobs from a help text """ form_class = forms.ManageJobsForm def get_initial(self, *args, **kwargs): initial … -
Add vue js to existing web app (written in django) using docker
I have an existing web app that is written in Django. The app is currently in a Docker container. I have also integrated django REST framework Problem: I am a new developer, therefore I do not know how to add vue js to my existing web app. Attempted solutions: I have spent a few days searching online and although I found a number of tutorials online, none of them solved my specific problem. My tutor told me that I need to add a container that uses vue to my existing situation...that is going to require moving the docker-compose fly and make some changes to the paths in it –– which sounds pretty straight forward, but after attempting to make the addition and changes, this task has turned out to be not so simple. Not asking for someone to give me a step by step answer, rather I would appreciate any tips, suggestions that will help me get going in the right direction to solve my problem. -
Access dynamically created model django
I was working on a Django app which requires creating tables dynamically. def dcreatedb(request): attrs = { 'name': models.CharField(max_length=20), '__module__': 'data.models' } model = type('books', (models.Model,), attrs) with connection.schema_editor() as schema_editor: schema_editor.create_model(model) return HttpResponse('done') The above dcreatedb view creates a model dynamically. But I need to access the same model in some other view but the view is not in the models.py file in the app and created dynamically by the dcreatedb view. def dinsertdb(request): # access the book model and do some work return HttpResponse('work done') for instance let us suppose a model named books is created by the dcreatedb view dynamically, and now I want to access the same model in the dinsertdb view.(Both the dcreatedb model and the dinsertdb models are in the same views.py file under the same app.) How can this be done? Thanks -
Unable to loop through an object in JavaScript
I’m a bit lacking of knowledge in JS. I am accessing some data through an API and retrieving it as JSON. This data is getting into JS very nicely. But I do not really understand with which type object I’m dealing with. I cannot determine the length and also the other loop methods do not work. But I can access the object elements like an array with REValues[0] – first element. '''function drawTable() { debugger; var REValues = {{ json|safe }}; var data = new google.visualization.DataTable(); data.addColumn('number', 'ID'); data.addColumn('string', 'Stadt'); data.addColumn('string', 'Bezirk'); data.addColumn('number', 'Einkaufswert'); data.addColumn('number', 'Fläche'); data.addColumn('number', 'Miete'); for (var REValue in REValues) { debugger; }''' enter image description here -
Django PermissionDenied empty page in production
I have a Django app that is not displaying permission denied exceptions correctly. The project has a custom 403.html template that displays perfectly fine locally and used to work on production but at some point stopped working and I am having a heck of a time tracking down why. The app is served using Apache and Nginx. 403.html extends base.html and should show the normal site styling, menus, etc with the passed in exception message displayed. On production though, every single PermissionDenied raised shows a blank white page stating: "You don't have permission to access /some/path on this server." The Nginx access log shows a single 403 request to the route in question and nothing in the error log. The Apache access log also shows a 403 GET request to the given route. The error log shows the expected PermissionDenied exception. As part of debugging I have tried changing the default permission_denied view that comes included in django. If I change the view to return HttpResponse('test'), the permission denied response still shows a white page, but it does show the given text, 'test'. But if I try the following instead: log.info('a') resp = render(request, '403.html', context={'exception': str(exception)} log.info('b') return HttpResponse(resp) … -
I am getting an error when I am updating the post. It displays in the comment section but not update the post
I am new in Django. I am making Simple Blog site. But I am getting an error when I am updating the post. It displays in the comment section but not update the post. Here is the Code in; View.py from django.db.models import Count, Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect, reverse from .forms import CommentForm, PostForm from .models import Post, Author from marketing.models import Signup def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None def search(request): queryset = Post.objects.all() quary = request.GET.get('q') if quary: queryset = queryset.filter( Q(title__icontains=quary) | Q(overview__icontains=quary) ).distinct() context = { 'queryset' : queryset } return render(request, 'search_results.html', context) def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset def index(request): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[0:3] if request.method == 'POST': email = request.POST['email'] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest } return render(request, 'index.html', context) def blog(request): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:5] post_list = Post.objects.all() paginator = Paginator(post_list, 4) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset' : paginated_queryset, 'most_recent' … -
Django - 'NoneType' object has no attribute 'threads'
Hello guys so I am trying to add a category system for posts by following a tutorial on this website https://djangopy.org/how-to/how-to-implement-categories-in-django/ (I changed my code up a little) I get this error 'NoneType' object has no attribute 'threads' every time I try and go to the category page to view the posts inside that category. models.py: from django.db import models from django.urls import reverse from django.utils.text import slugify class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def save(self, *args, **kwargs): value = self.name self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Thread(models.Model): ... category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE, related_name='threads') ... def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] ... views.py: from django.shortcuts import render, HttpResponseRedirect from django.contrib import messages from .models import Category, Thread from .forms import SubmitScamNumber def show_category_view(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [ x.slug for … -
Django multiple models , multiple fields lookup in autofield coloumn
I have two models BOQ and DPR boq model choicestype=(('start','start'),('finish','finish')) class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300,null=True,blank=True) linktype = models.CharField(choices=choicestype,max_length=300,null=True,blank=True) linkduration = models.IntegerField(default=0) plannedstart = models.DateField(null=True,blank=True) plannedfinish = models.DateField(null=True,blank=True) actualstart = models.DateField(null=True,blank=True) actualfinish = models.DateField(null=True,blank=True) DPR class dprmodel(models.Model): Date=models.DateField() Contractor=models.CharField(max_length=300) Building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) Level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) Activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) Subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) Status=models.CharField(choices=choicestype,max_length=300) Labor=models.IntegerField() Both the models have Building,Level,Activity,Sub Activity as common fields. My entry in BOQ code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) MY DPR Entry Date :10-1-2019 contractor :A building=A-1 Level=L-1 Activity=Activity-A Subactivity=Subactivity-A Status =Start Labor=2 I need to populate the Actual start date in boqmodel such that if boqmodel.building = dprmodel.building and boqmodel.level = dprmodel.level and boqmodel.activity = dprmodel.activity and boqmodel.subactivity = dprmodel.subactivity and dpr.status=start. If the above condition exists then boq.actualstart=dpr.date I am thinking of creating a new field in two models by joining the building,level,activity and subactivity .Then i can join two models using the newly created fields. Any help would be appreciated. -
Django Insert Data Into Fields QuerySet
I have two views, K8Points & K8PointsClassroom. K8Points you select your classroom, hit submit and it runs the query on another view called K8PointsClassroom. My Issue: The for loop runs and populates my student names on the html page, however when you click on the level up button under the student name, you get a pop up box. Screen shots attached. What i want is the fields to automatically be populated with the correct data. Class room and Student Name inside the popup window. How do i do that ? Can i do it off the for loop ? Thanks HTML {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2>{% load static %} <img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> My Classroom</h2> <br> <br> <form action="/points/k8_points_classroom" method="POST"> {% csrf_token %} <!-- Start Date --> <div class="container"> <div class="container"> <div class='row'> <div class="col-4"> <p> Recording Data as User : {{user.username}} </p> <p><b> Classroom : {{class_name}} </b></p> </div> </div> <div class='row'> <div class = "col-2"> {{form.date|as_crispy_field }} </div> <div class = "col-2"> {{form.week_of|as_crispy_field }} </div> <div class = "col-2"> {{form.day|as_crispy_field }} </div> </div> </div> </form> <div class="jumbotron" align="middle"> … -
Filtering Django Simple-History by created/creator
I've created a simple Django data model that is using Django Simple-History for auditing: from django.db import models from simple_history.models import HistoricalRecords class AuditedModel(models.Model): history = HistoricalRecords(inherit=True) In the interest of DRY, I'm trying to leverage Simple-History's history_date & history_user attributes in place of adding created_at and created_by attributes. I've added a couple of properties to simplify accessing the history for these attributes as follows: @property def created_date(self): return self.history.earliest().history_date @property def created_by(self): return self.history.earliest().history_user This works fine when I'm working with an instance. Now, I'm running into issues when I try to filter querysets by history_date or history_user. For example, I can filter for objects created in the last 24hrs by doing this: queryset = AuditedModel.objects.all() queryset.filter( uuid__in=AuditedModel.history.annotate( created_date=Min('history_date'), ).filter( created_date__gte=timezone.now() - relativedelta(days=1) ).values_list( 'uuid', flat=True ) ) But, I'm unable to figure out how to filter the AuditedModel by more than one attribute. Ultimately, I'd like to get a queryset with new instances that were created by a specific user. Something like: queryset.filter( uuid__in=AuditedModel.history.annotate( created_date=Min('history_date'), ).filter( created_date__gte=timezone.now() - relativedelta(days=1) ).values_list( 'uuid', flat=True ), history__history_user=request.user ) This doesn't work as history can't be resolved, but it illustrates (I hope) what I'm trying to get at. Has anyone out there … -
Django prefetch_related but table not directly related
I have the following models set up. I'd like to get a queryset of Category objects and prefetch OrderLine objects but the problem is that they're not directly related but matched up through product__category. I'm thinking Subquery might work? class Category(models.Model): name = models.CharField(...) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', ...) name = models.CharField(...) price = models.DecimalField(...) class OrderLine(models.Model): product = models.ForeignKey(Product, related_name='orderlines', ...) I've tried the following but for each Category it will prefetch Product objects and for each Product it will prefetch OrderLine objects. from django.db.models import Prefetch categories = ( Category.objects.prefetch_related(Prefetch( 'products__orderlines', queryset=OrderLine.objects.filter(...) )) ) I've also tried with 'orderlines' but as expected get an error: AttributeError: Cannot find 'orderlines' on Category object, 'orderlines' is an invalid parameter to prefetch_related() -
Annotate queryset with percentage grouped by date
Suppose I have the following model: class Order(models.Model): category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, default=DEFAULT_CHOICE) created_at = models.DateTimeField(auto_now_add=True) I need to annotate an Order queryset with the percentage of each category grouped by month (based on the created_at field). I managed to write a query to count every Order grouped by month: orders_per_month = (Order.objects .annotate(month=TruncMonth('created_at')) .values('month') .annotate(count=Count('id')) .order_by('month') .values('month', 'count') ) Changing just the last .values() to .values('month', 'category', 'count'), I can get the count grouped by both category and month. Is it possible to get the percentage of each category grouped by month using Django's ORM? For example, if I had the following data: MONTH | CATEGORY Jan | 'A' Jan | 'B' Feb | 'A' I would like to get something similar to this: [ (Jan, 'A', 0.5), (Jan, 'B', 0.5), (Feb, 'A', 1), ] Thanks in advance. -
Error while embedding Amazon QuickSight dashboards with Django
I am trying to embed QuickSight dashboards into my django application. I followed all of the steps regarding embedding detailed in the following documentation: https://docs.aws.amazon.com/en_us/quicksight/latest/user/embedded-dashboards-setup.html Using the AWS CLI, I am able to assume an IAM role I created, register a user into my QS account, and get the dashboard embed url, and view the dashboard in a web browser. However, when trying to mimic the same behavior inside the application using the Python SDK, it yields the following: "We can't display this page (Not authorized)." We have whitelisted our domain within Quicksight, and tested it on 2 different servers. The user who is logged into the django app and is trying to view the dashboard already is in the QS account with the necessary permissions to view the dashboard. But still getting "We can't display this page (Not authorized)." Use of the Python SDK is below: def viewDashboard(request): import boto3 sts = boto3.client('sts') assumed_role_object = sts.assume_role( RoleArn="arn:aws:iam::********4324:role/QuickSightEmbed", RoleSessionName=email ) # From the response that contains the assumed role, get the temporary # credentials that can be used to make subsequent API calls credentials = assumed_role_object['Credentials'] # Use the temporary credentials that AssumeRole returns to make a # connection to … -
Django TestCase for group permissions?
I have a TestCase for some views, but I am also trying to incorporate tests for my post admin group. They have permissions to post.change_post and post.delete_post. Here is a little code snippet, from django.test import TestCase, Client from django.urls import reverse from fixtureless.factory import create from .models import Post class TestPostViews(TestCase): def setUp(self): super().setUp() self.user = get_user_model().objects.create(username='test_user') self.form = create(Post, {'title': 'test_title'}) self.client = Client() def test_update_post(self): """ Test UpdateView updates users post """ self.client.force_login(user=self.user) response = self.client.put(reverse('post:update', kwargs={'pk': self.form.pk}), {'title': 'testing'}) self.assertEqual(response.status_code, 200) # reloads a models value from the database self.form.refresh_from_db() self.assertEqual(self.form.title, 'test_title') def test_delete_confirm_page(self): """ Test DeleteView takes user to confirmation page """ self.client.force_login(user=self.user) response = self.client.get(reverse('post:delete', kwargs={'pk': self.form.pk})) self.assertContains(response, 'delete') def test_delete_post(self): """ Test DeleteView deletes a post """ self.client.force_login(user=self.user) response = self.client.post(reverse('post:delete', kwargs={'pk': self.form.pk})) self.assertRedirects(response, reverse('post:list')) self.assertFalse(Post.objects.filter(pk=self.form.pk).exists()) Any tips on this? Should I create a separate TestCase, or is there a way to add this in the initial setUp() method? -
Django class based views and taggit
# models for post class Post(models.Model): STATUS_CHOICE = [ ('draft', "Draft"), ('published', "Published") ] title = models.CharField(max_length=250) slug = models.SlugField(max_length=300, unique_for_date="publish") author = models.ForeignKey(User, related_name="blog_posts", on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICE, default="draft") class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.publish.strftime('%Y'), self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) # For Tagging Features tags = TaggableManager(blank=True) # Class Based views for the Post Create and adding tags for the Post dynamically # This is the Class Based View for Adding the Post and class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'body', 'status', 'tags'] def form_valid(self, form): form.instance.author = self.request.user form.instance.slug = slugify(form.instance.title) return super().form_valid(form) def AfterPostPosting(sender, instance, created, **kwargs): if created: if instance.tags.all().count()<=0: instance.tags.add(""+slugify(instance.slug)) instance.save_m2m() vars(instance) print(instance.tags.all().count()) print(instance.tags.all()) print(instance.slug) print(vars(instance)) post_save.connect(AfterPostPosting, sender=Post) ''' Blockquote Question : I added the tags by the slug field if user has not added the tags and I am adding the tags using Django's post_save signal but it is adding the tags to the 'Tag' model but not into the 'Post' model. But when i used the statement as "post_object.tags.all().count()" after adding the tags using post_save signal then it is showing me … -
Custom Django Admin Permissions for article Authors
I'm building a website that will include articles. Article content will be stored in a database model. Example: class article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() ... I'm wanting to use the built-in admin app for adding new articles to the website. And I'm going to have a group called 'author' which will allow other people to log in to the admin section and add new content. My issue is with the permissions. I want to give the 'author' group the permission to add, change, view and delete Articles. But I want to restrict this to only articles that they have created. Basically I don't want them to be able to update other author's posts. Is there a way that I can give them custom permissions so that they only have the ability to change, view, and delete only their own posts? -
Calculated django model field that depends on all the table
I have a model like this: class MyModel(): total_time = IntegerField total_score = IntegerField and I want to add a property or a field to this model which will be called rate and will be calculated according to those fields but on all the table, So if with have this models total time - 1, total score - 3 Total time - 2, total score - 2 Total time - 3, total score - 1 I want that if the rate is calculated by time number 3 is rated 1 but if it is calculated by score number one will be rated 1. What is the best practice for such case? Thank in advance !! -
Move Django Form init field from bottom of form?
How can I move the field that is created by __init__ from the bottom to a specified location on the form? class form(forms.Form): somefield = forms.ChoiceField() def __init__(self, *args, **kwargs): super(form, self).__init__(*args, **kwargs) self.fields['etc'] = forms.ChoiceField I have tried using form ordering but that didn't have an effect? -
Django get_context_data
Is it possible to ‘skip’ a code in get_context_data? I have this parent class and wrote a child class everytime I context.update({}) I want to skip or not run certain key in the parent class, cause it is affecting the performance, especially when parent class has multiple queries inside them, and I don’t want them in the child but certain key, val in the parent? -
Custom django signal not updating my models
I am trying to implement a custom signal but I have never done this before, so I seem to have messed this up. Here is my code from models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete from django.dispatch import Signal from django.db.models import Max,Count from django.apps import apps # Create your models here. class Player(models.Model): player_name = models.CharField(max_length=150) current_level_no = models.IntegerField(null=True) no_of_moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players' def __str__(self): return self.player_name class PlayerStats(models.Model): player_name = models.ForeignKey(to=Player, on_delete=models.CASCADE) level_no = models.IntegerField(null=True) moves = models.IntegerField(null=True) class Meta: verbose_name_plural = 'Players Stats' # It works! TotalLevels = 25 MaxCurrentLevel = PlayerStats.objects.aggregate(max_levels=Max('level_no'))['max_levels'] PlayerCount = Player.objects.aggregate(count_players=Count('player_name', distinct=True))['count_players'] def create_player(sender, instance, created, **kwargs): if created: new_username=instance.username Player.objects.create(player_name=new_username, current_level_no=None, no_of_moves=None) def delete_player(sender, instance, **kwargs): deleted_username=instance.username Player.objects.filter(player_name=deleted_username).delete() def create_player_stat(sender, instance, **kwargs): for x in range(1, TotalLevels+1): PlayerStats.objects.create(player_name=instance, level_no=x, moves=None) UpdateLevelsSignal = Signal(providing_args=['Update']) if MaxCurrentLevel != TotalLevels and PlayerCount != 0: UpdateLevelsSignal.send(UpdateLevelsSignal,Update=True) def UpdateLevels(sender, Update,**kwargs): if Update: if MaxCurrentLevel < TotalLevels: for x in Player.objects.all().values_list('player_name', flat=True): instance = Player.object.get(player_name=x) for y in range(TotalLevels-MaxCurrentLevel, TotalLevels+1): PlayerStats.objects.create(player_name=instance, level_no=y, moves=None) else: for x in Player.objects.all().values_list('player_name', flat=True): instance = Player.object.get(player_name=x) for y in range(MaxCurrentLevel-TotalLevels, MaxCurrentLevel+1): PlayerStats.objects.filter(player_name=instance, level_no=y, moves=None).delete() post_save.connect(create_player, sender=User) post_delete.connect(delete_player, sender=User) post_save.connect(create_player_stat, sender=Player) UpdateLevelsSignal.connect(UpdateLevels, … -
How to display image from Postgres Database using python views.py
I have a table is postgres database and the table has a column name castimage with the data type bytea. I inserted image into the column with a query (it shows [binary data]). When i tried to show the image in my HTML page it doesn't show. Is there a way to display image in my page? OR should I change the field data type which I used to store Image? views.py def search(request): FormSearchMovies1=FormSearchMovies() image=Tblcast.objects.get() return render(request,"search.html",{'FormSearchMovies1':FormSearchMovies1,'image': image}) models.py class Tblcast(models.Model): castid = models.AutoField(primary_key=True) castname = models.CharField(max_length=100) castimage = models.BinaryField() HTML <img src="{{image.castimage.url}}" alt="CastImage" class="img-fluid"> -
Hot to modify JS/AJAX so that dependent drop-down loads with options when the page first loads?
I have a form with a dependent drop-down. This secondary drop-down is hidden whenever the primary option selected does not have any secondary options, and when the page first loads. Whenever the form is submitted, only the first field gets cleared out, since most of the time the drop-downs remain the same, however, since the script works whenever there is a change in the primary drop-down, since the load upon does not constitute a change, it just keeps the selected/submitted option on the primary drop-down, and will just display an empty secondary drop-down, even when the primary option selected does have secondary options. I got most of the JS from the drop-down from a tutorial, as I am not very familiar with it. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two are supposed to remain, however, when the page reloads upon submission, it looks like this, and the station has been cleared according to the debugger since there are none technically. I don't care so much … -
django-channels does not work with daphne on linux server
I'm using Django-eventstream over Django channels to send an event to my client app (react using eventstream), on my local machine the events are sent correctly to the client. but when I upload the app to my Linux server the webhook just getting open and 'keep-alive' but the events won't get to the client at all. I use daphne to deploy my Asgi app and use Nginx as my getaway. when I use "python manage.py runserver" (on the Linux server) the client is getting all the messages. because of that my clients do get the messages when I use runserver command I assume that my Nginx configuration is right (correct me if I'm wrong) and the problem is in Daphne somehow. I don't see the events trying to be sent in the daphne logs at all. does anyone have a clue why this is happening? Thanks! the command I used to run Daphne: daphne --verbosity 3 -p 8001 my_project.asgi:application here is my Daphne log: [06/12/2019 14:52:34] INFO [daphne.cli:287] Starting server at tcp:port=8001:interface=127.0.0.1 2019-12-06 14:52:34,376 INFO Starting server at tcp:port=8001:interface=127.0.0.1 [06/12/2019 14:52:34] INFO [daphne.server:311] HTTP/2 support enabled 2019-12-06 14:52:34,377 INFO HTTP/2 support enabled [06/12/2019 14:52:34] INFO [daphne.server:311] Configuring endpoint tcp:port=8001:interface=127.0.0.1 2019-12-06 …