Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django proxy model: parent class accessing sub-class methods
I am trying to wrap my head around how proxy model works. Supposed I have a base class called Animal, and I would like to implement two sub-classes: Dog and Cow. They have the same data requirements, so I don't really want to create two separate tables. So I am trying using proxy models: class Animal(models.Models): name = models.CharField() animal_type = models.CharField(choices=(('Dog','Dog'),('Cow','Cow'))) def get_sound(self): if animal_type == 'Dog': return self.dog.get_sound() #doesn't work elif self.animal_type == 'Cow': return self.cow.get_sound() #doesn't work class Dog(Animal): class Meta: proxy=True def get_sound(self): return 'Woof' class Cow(Animal): class Meta: proxy=True def get_sound(self): return 'Moo' The problem I have is, how can I access the sub-class methods from the parent class? I have it as self.dog.get_sound(). This is possible in multi-table inheritance, but does not work in a proxy model. >>obj = Animal.objects.create(name='Max', animal_type='Dog') >>obj.get_sound() 'Woof' <-- what I'd like it to return Is proxy model the wrong way to do this? Would prefer to keep one table. -
Django Postgres Connection Pooling
How do you pool connections in Django v2.1 for a Postgres db? This heroku library is no longer supported. On the Django website it has a section about connection pooling for pgBouncer but can't seem to find a tutorial online for getting setup with pgBouncer or an example project. Any help would be greatly appreciated -
How to reference a nested model als foreign key in djongo
I'm experimenting with Djongo right now: Is there a possibility to reference the djongo nested models in another model as a foreign key? Or how would you deal with this structure in djongo? Clinic 1:n Wards - Ward 1:n Cases (The cases should still be in their own collection.) class Clinic(models.Model): ... wards = models.ArrayModelField(model_container=Ward, null=True,) ... class Case(models.Model): ward = models.ForeignKey( 'clinic.ward', on_delete=models.PROTECT) -
How to run django application on https?
I don't know much about how django works but I am interested in fixing a issue I found in open source project because I can write python code. I cloned the project and followed the steps as mentioned in this answer: how to run cloned django project and I am able to run the project locally with the command: python manage.py runserver and it is successfully running on http but I need to run application on https as it is integrated with salesforce application and salesforce not allowing http as callback. I have googled on how to run django on https but all I am seeing is how to run django https on nginx. I think I need to use library like letsencrypt.org but not sure how to do that. Here is the Github project I am trying to work on : https://github.com/benedwards44/packagebuilder -
Django render vs public API over ajax
I have a website that presents data from my DB publicly for all visitors of the site. So there are no accounts nor any restrictions. Sometimes the data in the DB has to be updated before it is shown to the user. This can lead to a significant lag while rendering the page. My idea was to expose a REST API for the public data and download the data on the client side asynchronous with ajax. But now I have worries that people could exploit my API and use it to serve data for their clients. They potentially could have done that before by "crawling" my site for the needed data. Is there anything I can do against third parties exploiting my API? Is there any law that would protect a public API? If I would like to "kind of protect" my data, would you try to find a solution to render everything on the server side? -
How to set verbose_name for external app model in Django?
I'm trying to set verbose_name for a model SocialAuthUser from django_social. I've tried to use proxy model, setting its Meta.verbose_name to desired value, but had no success (probably I did it wrong). If it's the way to go, I can provide more detail. It would be great to avoid installing pip module in editable mode just to replace verbose_name in admin site. Probably I can replace model name in admin site in some other way? I thought about adding custom link to admin site, but didn't research this method yet because it feels hacky. -
How do I set fields (from other fields) in Django before validation?
I have three fields in a Django model, first_name, last_name, and full_name. If full_name is not provided when created or blanked when updating, I want to recalculate it from first_name and last_name. I tried doing this: class Person(models.Model): first_name = models.CharField(null=False, blank=False, max_length=100) last_name = models.CharField(null=False, blank=False, max_length=100) full_name = models.CharField(null=False, blank=False, max_length=200) def clean_fields(self, exclude=None): if not self.full_name and self.first_name and self.last_name: self.full_name = self.first_name + " " + self.last_name return super(Person, self).clean_fields(exclude) When I try to save the object in the admin tool, full_name is successfully set, but I still get the full_name is blank validation error. What's the correct way of populating full_name in this case? -
Firebase (client-side vs server-side)
I'm building a PWA with django/python on the server-side and vue on the client-side and want to use firebase as a database as well as make use of the firebase authentication. After some thorough research I realised that I had to make a few choices. Question 1: Authentication I can do authentication on the client-side or server-side. Which one would be best (more secure) ? Question 2: Database In terms of CRUDS I am a bit conflicted. Do I write all my data to firestore from the client-side? Do I rather use api's to communicate with my backend and then write data to firestore from the backend? What are the security implications of doing this? Should I just use both in terms of context? If there are no security implications I would do my authentication client-side and my CRUDS from the server-side. I think I would also have to check authentication to write to the database from the backend. -
django models database schema
In Django, how would a database schema look like for a social media site like Instagram? For example, how would you make it so that one user can post multiple posts, and they can only have 1 profile? -
recursion error when trying to update record in Django
I am trying to use signals to update a record, and am getting a "recursion error". What I am trying to achieve: When a new customUser is saved into database, I want to see if the user inputted a serial number into deviceSerial Field. If there is a serial number, I want to set "isDevice" to True, as it defaults to false. The problem seems to occur when I use .save(). I'm assuming I need to use some type of update command instead? Error message: Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: C:\Users\matth\AppData\Local\Programs\Python\Python36\lib\copyreg.py in __newobj__, line 88 Python Executable: C:\Users\matth\AppData\Local\Programs\Python\Python36\python.exe My models.py: from django.db import models from django.conf import settings from defaults.models import DefaultDMLSProcessParams from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.db.models.signals import pre_save from django.core.files.storage import FileSystemStorage fs = FileSystemStorage(location='/media/photos') class CustomUser(AbstractUser): customerTag = models.CharField(max_length=50,) isAdmin = models.BooleanField(default = False,) isDevice = models.BooleanField(default = False,) notifications = models.BooleanField(default = True,) deviceSerial= models.CharField(max_length=50,) equipmentName= models.CharField(max_length=50,default=(str(equipment)+str(id)),) equipmentDescription = models.CharField(max_length=200,) image = models.ImageField(storage=fs, blank = True) def create_machine(sender, instance,**kwargs): hasSerial = len(instance.deviceSerial) if hasSerial >1: newRecordID = instance.id #grab id of record that was just saved newRecord = CustomUser.objects.get(id=newRecordID) #get object newRecord.isDevice = True #set to … -
The stylesheet style.css was not loaded because its MIME type, “text/plain”, is not “text/css”
I have a django website on my local and it was ok last week , i can not remember if i changed anything in its codes but today i faced some errors and css files are not working this is its error on browser developer tools: The stylesheet http://127.0.0.1:8000/static/css/style.css was not loaded because its MIME type, “text/plain”, is not “text/css”. and also same errors on aother pages related to css The stylesheet http://127.0.0.1:8000/static/autocomplete_light/select2.css was not loaded because its MIME type, “text/plain”, is not “text/css” -
Django Database Filter in views page
Hi i created Django app for users monthly project report. I added users project data in Django admin portal with completed year,month and date. Now i need to display the data in views page according to the month and year or any specific date which they are selecting in view page. for example if users want to see September 2018 month data, in data.html page users will select 2018 and September from drop down list and they will click generate button to get the report for that selected month and year. below i attached screenshot link for data.html page. Please help me out. Thanks in advance. https://i.stack.imgur.com/7vyrM.jpg -
Django has no response to anchor tag
<a href="#test" data-toggle="tab">test</a> ... <div class="tab-pane " id="test"> <table> ... </table> </div> When #test anchor is clicked, the behavior should be logged in the server. So in urls.py, I defined something like this url(r'#test$', views.log()) or url(r'.*#test$', views.log()) But it seems it doesn't work. I have to use anchor here, because I don't want to refresh the page. Any ideas? -
How to add permission to edit in Django view
I am adding a post edit form, so that user can add edit their post, Here is my edit view, which works fine, class PostEditView(View): form_class = PostEditForm template_name = 'mechinpy/edit/post.html' def get(self, request, slug): post = get_object_or_404(Post, slug=slug) form = self.form_class(instance=post) return render(request, self.template_name, {'form':form}) def post(self, request, slug): post = get_object_or_404(Post, slug=slug) form = self.form_class(request.POST,request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('mechinpy:detail', post.slug) else: return render(request, self.template_name, {'form':form}) Now anyone can able to edit the post. My question is how can I give permission only to the user who have posted to edit, and raise permission denied for others. I am trying to add get_object, but don't know how and where to add. -
Django Ajax Button - When I move the JS logic for the button to a separate file, the button can't find my Django link
I've got a follow button working well when included in the tag in the HTML for the specific page I want to use it for: function toggleFollow(){ $.ajax({ url: "{% url 'user_follow' view.kwargs.username %}", success: function(data) { $("#followCount").html(data.follower_count + ' Followers'); $('#followElement').html(data.button); console.log(data); }, error: function(error){ console.log(error); } }); }; But when I move this button to a separate file, I get the django error that "The current path didn't match any of these" and then it lists all of my paths. How do I call my django url inside of my button.js file? -
Python Celery: Update django model after state change
I managed to find 2 similar topics with discussion about this issue, but unfortunately I couldn't get what is the best solution from it: Update Django Model Field Based On Celery Task Status Update Django Model Field Based On Celery Task Status I use Django & Celery (+redis as Message broker) and I would like to update django model when celery task status changes(from pending -> success, pending -> failure) etc. My code: import time from celery import shared_task @shared_task(name="run_simulation") def run_simulation(simulation_id: str): t1_start = time.perf_counter() doSomeWork() # we may change this to sleep for instance t1_end = time.perf_counter() return{'process_time': t1_end - t1_start} and the particular view from which I am calling the task: def run_simulation(request): form = SimulationForm(request.POST) if form.is_valid(): new_simulation = form.save() new_simulation.save() task_id = tasks.run_simulation.delay(new_simulation.id) The question is, what is the preferred way to update django model state of Simulation when status of task has been changed? In the docs I found handlers that are using methods on_failure, on_success etc. http://docs.celeryproject.org/en/latest/userguide/tasks.html#handlers -
Django: Derived class of a non-abstract class to have a separate table
I have a Django model (A) and want to create a model (B) with the same fields and methods as A. If A were abstract, it would be made as simply making B derived from A. But A is not abstract. The best solution I came up with is: Make A1 and abstract model derived from A. Make B derived from A1. But this way, I would have an extra class A1 in the hierarchy, what is not good. -
I have a queryset and i want to modify it to be a dictionary of key and value where the value is an array
i want to change a query set to a dictionary and get an array which is the value of the key Branches: My dictionary is Iwant to get the array [0,1] how to do it? My code: my_dict = request.POST print(my_dict) input = [] Branches = my_dict['Branches'] -
Upload django project without ssh
i have finished my django project in local, now i want to upload it to fastcomet server, but without ssh . i setup a new python project named myproject on the cpanel and it shows me in the browser It works! Python 3.5.6 Now where must i upload the local django files and how to manage it settings. Thanks -
User edit profile form
it's me again! I got problem with creating edit form. https://github.com/Incybro/Forum I created accounts app which contains user profiles and I want to allow users to edit that informations. I read a lot of tutorials but I still don't understand how to do it :/ views.py from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def user_detail(request, pk): user = get_object_or_404(User, pk=pk) userprofile = user.userprofile return render(request, 'accounts/user_detail.html', {'userprofile': userprofile}) url.py path('<int:pk>/', views.user_detail, name='user_detail'), models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) website = models.URLField(default='', blank=True) city = models.CharField(max_length=100, default='', blank=True) signature = models.TextField(default='', blank=True) def create_profile(sender, **kwargs): #Funckja, ktora tworzy profile użytkownika user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) def __str__(self): #Definiujemy funkcje, która zwraca tytuł wpisu return self.user.username user_detail.html {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <p><a href="">Edit profile <span class="glyphicon glyphicon-pencil"></span></a></p> <p>Your nickname: <b>{{ user.username }}</b></p> <p>Your first name: <b>{{ user.first_name }}</b></p> <p>Your last name: <b>{{ user.last_name }}</b></p> <p>Your email: <b>{{ user.email }}</b></p> … -
Passing Html to Jinja from Models/DB and jinja in jinja?
So i am writing a personal website for myself and i don't wanna add each page from views and urls. I am trying to make a very dynamic website which admins can add pages from /admin but the problem right now is when i try to put jinja or html from my database by jinja templating. Jinja sees them as just str and directly output them raw. My English is bad but codes gonna explain everything (i gonna translate Turkish things with # python comment thing for making it more understandable: views: from django.shortcuts import render from umut.models import * # Create your views here. def sayfa#page(request, sayfalinki#pagelink stands for pagename): içerik#content = Sayfalar.objects.get(baslik=sayfalinki) return render(request, "umut/umut-şablon.html" , {"içerik":içerik}) model: from django.db import models # Create your models here. class Sayfalar(models.Model): baslik#title = models.CharField(max_length=15) title = models.CharField(max_length=30) icerik#content = models.TextField(max_length=5000) urls: from django.urls import path, include from . import views urlpatterns = [ #path('', views.anasayfa, name= 'anasayfa#mainpage'), path('<str:sayfalinki>', views.sayfa) ] template: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static "umut/umut-style.css" %}"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{içerik.title}}</title> </head> <body> <header> <h1 class="anabaslik">Umut Özsoy</h1> </header> <nav> {% for i in sayfalar %} <a href="{{i.link}}">{{i.isim}}</a> {% … -
Django: How to import Websocket data into Database
Currently I am working with Websockets. I need help regarding same. Environment: Windows 8.1 Django 2.0 PostgreSQL Python 3.6 Below is the mention scenario: Application connects to the Websocket endpoint. Endpoint sends a stream of data(approx 120-150 JSON objects per second). Application after receiving the data must now store the data into the local database. As the data is important, no loss of data is expected. Have tried following some of the tutorials, they have mentioned libraries and tools such as, Redis RabbitMQ Channels Django-websocket-redis Need help in understanding how the flow works and how and where to use these libraries. Thank You. -
What is the efficient session expiry time?
I am workig on a django ecommerce website in which i want to implement session id for anonymous user and store their cart data in session. But I am confused whether setting expiry duration of session for long time is efficient or not. -
django and django rest framework instance.save() doesn't save to database
I have an update method where immediately after user.update() I need to send an email where I pass the user's id as a parameter to the send_email_to(user_id) method. But inside this method, I again get the user from the user_id passed and send an email. But it appears that the user is not updated yet to the database and results in sending mail to the previously saved email. How to force to save to db immediately after instance.save() or instance.update()? I have tried user.refresh_from_db() and that clearly shows that the user is not updated yet. Help me overcome this. -
Django: Having multiple foreign keys stored in the same attribute of a model
My question is related to this one, where the author wanted to store a reference to a model in the attribute of another model using Django's models.ForeignKey field type. My question is, would the exact same method work, if an article had multiple authors, or is something additional needed to establish this?